clean up gtk kt

This commit is contained in:
Johannes Frohnmeyer 2023-07-14 15:24:32 +02:00
parent 7805400e43
commit b8f30247ea
Signed by: Johannes
GPG Key ID: E76429612C2929F4
15 changed files with 118 additions and 137 deletions

View File

@ -74,54 +74,50 @@ object GtkEnvBackend : EnvBackend {
ok: Runnable?, ok: Runnable?,
cancel: Runnable? cancel: Runnable?
) { ) {
run { val dialog = AlertDialog("")
val dialog = AlertDialog("") dialog.message = title
dialog.message = title dialog.detail = markup
dialog.detail = markup dialog.modal = true
dialog.modal = true when {
when { cancel == null -> {
cancel == null -> { dialog.setButtons(arrayOf(I18n["ok"]))
dialog.setButtons(arrayOf(I18n["ok"])) dialog.defaultButton = 0
dialog.defaultButton = 0 dialog.cancelButton = -1
dialog.cancelButton = -1
}
ok == null -> {
dialog.setButtons(arrayOf("Cancel"))
dialog.defaultButton = -1
dialog.cancelButton = 0
}
else -> {
dialog.setButtons(arrayOf("OK", "Cancel"))
dialog.defaultButton = 0
dialog.cancelButton = 1
}
} }
dialog.choose(parent, Cancellable()) { _, res, _ -> ok == null -> {
val result = dialog.chooseFinish(res) dialog.setButtons(arrayOf("Cancel"))
val cancelIdx = dialog.cancelButton dialog.defaultButton = -1
val defaultIdx = dialog.defaultButton dialog.cancelButton = 0
if (result == cancelIdx) cancel?.run()
if (result == defaultIdx) ok?.run()
} }
else -> {
dialog.setButtons(arrayOf("OK", "Cancel"))
dialog.defaultButton = 0
dialog.cancelButton = 1
}
}
dialog.choose(parent, Cancellable()) { _, res, _ ->
val result = dialog.chooseFinish(res)
val cancelIdx = dialog.cancelButton
val defaultIdx = dialog.defaultButton
if (result == cancelIdx) cancel?.run()
if (result == defaultIdx) ok?.run()
} }
} }
private fun processResponses(dialog: Dialog, ok: Runnable?, cancel: Runnable?): Dialog.Response { private fun processResponses(dialog: Dialog, ok: Runnable?, cancel: Runnable?): Dialog.Response = Dialog.Response { responseId: Int ->
return Dialog.Response { responseId: Int -> when (ResponseType.of(responseId)) {
when (ResponseType.of(responseId)) { ResponseType.OK -> {
ResponseType.OK -> { dialog.close()
dialog.close() ok?.run()
ok?.run()
}
ResponseType.CLOSE, ResponseType.CANCEL -> {
dialog.close()
cancel?.run()
}
ResponseType.DELETE_EVENT -> dialog.destroy()
else -> Utils.LOGGER.error("Unexpected response type: $responseId")
} }
ResponseType.CLOSE, ResponseType.CANCEL -> {
dialog.close()
cancel?.run()
}
ResponseType.DELETE_EVENT -> dialog.destroy()
else -> Utils.LOGGER.error("Unexpected response type: $responseId")
} }
} }
} }

View File

@ -31,19 +31,17 @@ object GtkMain {
} }
@JvmStatic @JvmStatic
fun showGui(args: Array<String>): Int { fun showGui(args: Array<String>): Int = setupApplication(args) {
return setupApplication(args) { //TODO update check
//TODO update check AccountManager.loadAccounts()
AccountManager.loadAccounts() GtkMenubar.create(this)
GtkMenubar.create(this) val window = MainWindow(this)
val window = MainWindow(this) window.visible = true
window.visible = true GtkEnvBackend.dialogParent = window
GtkEnvBackend.dialogParent = window window.onCloseRequest {
window.onCloseRequest { GtkEnvBackend.dialogParent = null
GtkEnvBackend.dialogParent = null this.quit()
this.quit() false
false
}
} }
} }

View File

@ -7,8 +7,11 @@ import org.gnome.gtk.Gtk
import org.gnome.gtk.Label import org.gnome.gtk.Label
import org.jetbrains.annotations.PropertyKey import org.jetbrains.annotations.PropertyKey
class ILabel(str: @PropertyKey(resourceBundle = I18n.BUNDLE) String, mode: Mode, vararg args: Any?) : class ILabel(
Label(I18n.get(str, *args)) { str: @PropertyKey(resourceBundle = I18n.BUNDLE) String,
mode: Mode,
vararg args: Any?
) : Label(I18n.get(str, *args)) {
constructor(str: @PropertyKey(resourceBundle = I18n.BUNDLE) String, vararg args: Any?) : this(str, Mode.NORMAL, *args) constructor(str: @PropertyKey(resourceBundle = I18n.BUNDLE) String, vararg args: Any?) : this(str, Mode.NORMAL, *args)
init { init {
@ -36,17 +39,14 @@ class ILabel(str: @PropertyKey(resourceBundle = I18n.BUNDLE) String, mode: Mode,
provider provider
} }
@JvmStatic fun theme(label: Label, mode: Mode) = when (mode) {
fun theme(label: Label, mode: Mode) { Mode.HEADING -> label.addCssClass("heading")
when (mode) { Mode.SUBTITLE -> {
Mode.HEADING -> label.addCssClass("heading") label.addCssClass("jf-subtitle")
Mode.SUBTITLE -> { label.styleContext.addProvider(provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
label.addCssClass("jf-subtitle")
label.styleContext.addProvider(provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
}
Mode.NORMAL -> {}
} }
Mode.NORMAL -> {}
} }
} }
} }

View File

@ -41,8 +41,6 @@ class InstanceThumbnail : Stack {
private const val IMAGE = "image" private const val IMAGE = "image"
private const val GENERIC = "generic" private const val GENERIC = "generic"
@JvmStatic @JvmStatic
fun castFrom(stack: Stack): InstanceThumbnail { fun castFrom(stack: Stack): InstanceThumbnail = InstanceThumbnail(stack.handle())
return InstanceThumbnail(stack.handle())
}
} }
} }

View File

@ -36,22 +36,20 @@ class IRow(
append(head) append(head)
} }
fun setButton(text: @PropertyKey(resourceBundle = I18n.BUNDLE) String, action: Button.Clicked?): Button { fun setButton(text: @PropertyKey(resourceBundle = I18n.BUNDLE) String, action: Button.Clicked?): Button =
return Button.newWithLabel(I18n[text]).apply { Button.newWithLabel(I18n[text]).apply {
packSmallEnd() packSmallEnd()
onClicked(action) onClicked(action)
} }
}
fun setDropdown(options: Array<String>, defaultIndex: Int, changed: IntConsumer): KDropDown<String> { fun setDropdown(options: Array<String>, defaultIndex: Int, changed: IntConsumer): KDropDown<String> =
return KDropDown(options, { it } , defaultIndex).apply { KDropDown(options, { it } , defaultIndex).apply {
onChange(changed) onChange(changed)
packSmallEnd() packSmallEnd()
} }
}
fun setSwitch(value: Boolean, changed: Consumer<Boolean>): Switch { fun setSwitch(value: Boolean, changed: Consumer<Boolean>): Switch =
return Switch().apply { Switch().apply {
packSmallEnd() packSmallEnd()
active = value active = value
onStateSet { state: Boolean -> onStateSet { state: Boolean ->
@ -59,25 +57,22 @@ class IRow(
false false
} }
} }
}
fun setSpinButton(value: Double, min: Double, max: Double, step: Double, changed: DoubleConsumer): SpinButton { fun setSpinButton(value: Double, min: Double, max: Double, step: Double, changed: DoubleConsumer): SpinButton =
return SpinButton.newWithRange(min, max, step).apply { SpinButton.newWithRange(min, max, step).apply {
packSmallEnd() packSmallEnd()
this.value = value this.value = value
onValueChanged { changed.accept(this.value) } onValueChanged { changed.accept(this.value) }
} }
}
fun setEntry(value: String?, changed: Consumer<String>): KEntry { fun setEntry(value: String?, changed: Consumer<String>): KEntry =
return KEntry(value).apply { KEntry(value).apply {
hexpand = true hexpand = true
valign = Align.CENTER valign = Align.CENTER
halign = Align.FILL halign = Align.FILL
onChange(changed) onChange(changed)
append(this) append(this)
} }
}
private fun Widget.packSmallEnd() { private fun Widget.packSmallEnd() {
firstChild!!.hexpand = true firstChild!!.hexpand = true

View File

@ -9,7 +9,7 @@ open class SettingsTab<T : Widget>(
protected val window: Window?, protected val window: Window?,
val content: T val content: T
) { ) {
protected fun showError(message: String, t: Throwable) { protected fun showError(message: String, t: Throwable) =
GtkEnvBackend.simpleDialog( GtkEnvBackend.simpleDialog(
window, window,
StringFormatter.toString(t), StringFormatter.toString(t),
@ -17,5 +17,4 @@ open class SettingsTab<T : Widget>(
null, null,
null null
) )
}
} }

View File

@ -10,7 +10,6 @@ import org.gnome.gtk.*
import org.jetbrains.annotations.PropertyKey import org.jetbrains.annotations.PropertyKey
open class SettingsWindow(app: Application?) : Window() { open class SettingsWindow(app: Application?) : Window() {
@JvmField
protected val stack: ViewStack protected val stack: ViewStack
init { init {

View File

@ -4,7 +4,7 @@ import org.gnome.gio.MenuItem
import org.gnome.gio.SimpleAction import org.gnome.gio.SimpleAction
import org.gnome.gio.ThemedIcon import org.gnome.gio.ThemedIcon
abstract class BuiltMenuItem protected constructor(action: SimpleAction, @JvmField protected val menuItem: MenuItem?) { abstract class BuiltMenuItem protected constructor(action: SimpleAction, protected val menuItem: MenuItem?) {
@JvmField @JvmField
protected val action: SimpleAction protected val action: SimpleAction

View File

@ -5,8 +5,8 @@ import org.gnome.glib.Variant
class BuiltRadioItem<T>(action: SimpleAction, private val options: List<T>) : BuiltMenuItem(action, null) { class BuiltRadioItem<T>(action: SimpleAction, private val options: List<T>) : BuiltMenuItem(action, null) {
var selected: T var selected: T
get() = options[action.getState()!!.getInt32()] get() = options[action.state!!.int32]
set(selected) { set(selected) {
action.setState(Variant.newInt32(options.indexOf(selected))) action.state = Variant.newInt32(options.indexOf(selected))
} }
} }

View File

@ -6,7 +6,7 @@ import org.gnome.glib.Variant
class BuiltToggleItem(action: SimpleAction, menuItem: MenuItem?) : BuiltMenuItem(action, menuItem) { class BuiltToggleItem(action: SimpleAction, menuItem: MenuItem?) : BuiltMenuItem(action, menuItem) {
var state: Boolean var state: Boolean
get() = action.getState()!!.boolean get() = action.state!!.boolean
set(state) { set(state) {
action.state = Variant.newBoolean(state) action.state = Variant.newBoolean(state)
} }

View File

@ -92,7 +92,7 @@ class MenuBuilder private constructor(map: ActionMap, menu: Menu, prefix: String
addAction(name, action) addAction(name, action)
action.onActivate { variant: Variant? -> action.onActivate { variant: Variant? ->
action.state = variant action.state = variant
onCheck.accept(options[variant!!.getInt32()]) onCheck.accept(options[variant!!.int32])
} }
for ((i, option) in options.withIndex()) { for ((i, option) in options.withIndex()) {
menu.appendItem(MenuItem(stringifier.apply(i, option), "$groupName$name($i)")) menu.appendItem(MenuItem(stringifier.apply(i, option), "$groupName$name($i)"))

View File

@ -8,12 +8,10 @@ object I18n {
private val bundle = ResourceBundle.getBundle(BUNDLE) private val bundle = ResourceBundle.getBundle(BUNDLE)
@JvmStatic @JvmStatic
operator fun get(key: @PropertyKey(resourceBundle = BUNDLE) String): String { operator fun get(key: @PropertyKey(resourceBundle = BUNDLE) String): String =
return bundle.getString(key) bundle.getString(key)
}
@JvmStatic @JvmStatic
operator fun get(key: @PropertyKey(resourceBundle = BUNDLE) String, vararg args: Any?): String { operator fun get(key: @PropertyKey(resourceBundle = BUNDLE) String, vararg args: Any?): String =
return String.format(bundle.getString(key), *args) String.format(bundle.getString(key), *args)
}
} }

View File

@ -12,9 +12,9 @@ object Memory {
const val MB = KB * 1024 const val MB = KB * 1024
const val GB = MB * 1024 const val GB = MB * 1024
private val impl = when (OSUtils.TYPE) { private val impl = when (OSUtils.TYPE) {
OSUtils.Type.LINUX -> LinuxMI() OSUtils.Type.LINUX -> LinuxMI
OSUtils.Type.WINDOWS -> WindowsMI() OSUtils.Type.WINDOWS -> WindowsMI
OSUtils.Type.MAC_OS -> MacOsMI() OSUtils.Type.MAC_OS -> MacOsMI
} }
private val totalMemory by lazy { impl.getTotalMemory() } private val totalMemory by lazy { impl.getTotalMemory() }
val maxMBForInstance: Long get() = (totalMemory / MB - 1024).coerceAtLeast(1024) val maxMBForInstance: Long get() = (totalMemory / MB - 1024).coerceAtLeast(1024)
@ -23,7 +23,7 @@ object Memory {
fun getTotalMemory(): Long fun getTotalMemory(): Long
} }
private class LinuxMI : MI { private object LinuxMI : MI {
override fun getTotalMemory(): Long { override fun getTotalMemory(): Long {
try { try {
Files.lines(Path.of("/proc/meminfo")).use { stream -> Files.lines(Path.of("/proc/meminfo")).use { stream ->
@ -45,49 +45,47 @@ object Memory {
} }
} }
companion object { // Taken from oshi
// Taken from oshi private val BYTES_PATTERN = Pattern.compile("(\\d+) ?([kKMGT]?B?).*")
private val BYTES_PATTERN = Pattern.compile("(\\d+) ?([kKMGT]?B?).*") private val WHITESPACES = Pattern.compile("\\s+")
private val WHITESPACES = Pattern.compile("\\s+") private fun parseDecimalMemorySizeToBinary(size: String): Long {
private fun parseDecimalMemorySizeToBinary(size: String): Long { var mem = WHITESPACES.split(size)
var mem = WHITESPACES.split(size) if (mem.size < 2) {
if (mem.size < 2) { // If no spaces, use regexp
// If no spaces, use regexp val matcher = BYTES_PATTERN.matcher(size.trim { it <= ' ' })
val matcher = BYTES_PATTERN.matcher(size.trim { it <= ' ' }) if (matcher.find() && matcher.groupCount() == 2) {
if (matcher.find() && matcher.groupCount() == 2) { mem = arrayOfNulls(2)
mem = arrayOfNulls(2) mem[0] = matcher.group(1)
mem[0] = matcher.group(1) mem[1] = matcher.group(2)
mem[1] = matcher.group(2)
}
} }
var capacity = parseLongOrDefault(mem[0], 0L)
if (mem.size == 2 && mem[1]!!.length > 1) {
when (mem[1]!![0]) {
'T' -> capacity = capacity shl 40
'G' -> capacity = capacity shl 30
'M' -> capacity = capacity shl 20
'K', 'k' -> capacity = capacity shl 10
else -> {}
}
}
return capacity
} }
var capacity = parseLongOrDefault(mem[0], 0L)
if (mem.size == 2 && mem[1]!!.length > 1) {
when (mem[1]!![0]) {
'T' -> capacity = capacity shl 40
'G' -> capacity = capacity shl 30
'M' -> capacity = capacity shl 20
'K', 'k' -> capacity = capacity shl 10
else -> {}
}
}
return capacity
}
private fun parseLongOrDefault(s: String, defaultLong: Long): Long = try { private fun parseLongOrDefault(s: String, defaultLong: Long): Long = try {
s.toLong() s.toLong()
} catch (e: NumberFormatException) { } catch (e: NumberFormatException) {
defaultLong defaultLong
}
} }
} }
private class WindowsMI : MI { private object WindowsMI : MI {
override fun getTotalMemory(): Long { override fun getTotalMemory(): Long {
return 32 * GB // This is currently unsupported, but any implementations by Windows user using panama are welcome return 32 * GB // This is currently unsupported, but any implementations by Windows user using panama are welcome
} }
} }
private class MacOsMI : MI { private object MacOsMI : MI {
override fun getTotalMemory(): Long { override fun getTotalMemory(): Long {
return 32 * GB // This is currently unsupported, but any implementations by MacOS user using panama are welcome return 32 * GB // This is currently unsupported, but any implementations by MacOS user using panama are welcome
} }

View File

@ -2,4 +2,4 @@ package io.gitlab.jfronny.inceptum.gtk.util
import java.util.stream.Stream import java.util.stream.Stream
inline fun <reified T> Stream<T>.toTypedArray(): Array<T> = toArray { arrayOfNulls<T>(it) } inline fun <reified T> Stream<T>.toTypedArray(): Array<T> = toArray(::arrayOfNulls)

View File

@ -9,7 +9,7 @@ import org.gnome.gtk.*
import java.net.URI import java.net.URI
import java.net.URISyntaxException import java.net.URISyntaxException
class MicrosoftLoginDialog @JvmOverloads constructor( class MicrosoftLoginDialog(
parent: Window?, parent: Window?,
account: MicrosoftAccount? = null, account: MicrosoftAccount? = null,
onClose: Runnable? = null onClose: Runnable? = null