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?,
cancel: Runnable?
) {
run {
val dialog = AlertDialog("")
dialog.message = title
dialog.detail = markup
dialog.modal = true
when {
cancel == null -> {
dialog.setButtons(arrayOf(I18n["ok"]))
dialog.defaultButton = 0
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
}
val dialog = AlertDialog("")
dialog.message = title
dialog.detail = markup
dialog.modal = true
when {
cancel == null -> {
dialog.setButtons(arrayOf(I18n["ok"]))
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()
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, _ ->
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 {
return Dialog.Response { responseId: Int ->
when (ResponseType.of(responseId)) {
ResponseType.OK -> {
dialog.close()
ok?.run()
}
ResponseType.CLOSE, ResponseType.CANCEL -> {
dialog.close()
cancel?.run()
}
ResponseType.DELETE_EVENT -> dialog.destroy()
else -> Utils.LOGGER.error("Unexpected response type: $responseId")
private fun processResponses(dialog: Dialog, ok: Runnable?, cancel: Runnable?): Dialog.Response = Dialog.Response { responseId: Int ->
when (ResponseType.of(responseId)) {
ResponseType.OK -> {
dialog.close()
ok?.run()
}
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
fun showGui(args: Array<String>): Int {
return setupApplication(args) {
//TODO update check
AccountManager.loadAccounts()
GtkMenubar.create(this)
val window = MainWindow(this)
window.visible = true
GtkEnvBackend.dialogParent = window
window.onCloseRequest {
GtkEnvBackend.dialogParent = null
this.quit()
false
}
fun showGui(args: Array<String>): Int = setupApplication(args) {
//TODO update check
AccountManager.loadAccounts()
GtkMenubar.create(this)
val window = MainWindow(this)
window.visible = true
GtkEnvBackend.dialogParent = window
window.onCloseRequest {
GtkEnvBackend.dialogParent = null
this.quit()
false
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -4,7 +4,7 @@ import org.gnome.gio.MenuItem
import org.gnome.gio.SimpleAction
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
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) {
var selected: T
get() = options[action.getState()!!.getInt32()]
get() = options[action.state!!.int32]
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) {
var state: Boolean
get() = action.getState()!!.boolean
get() = action.state!!.boolean
set(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)
action.onActivate { variant: Variant? ->
action.state = variant
onCheck.accept(options[variant!!.getInt32()])
onCheck.accept(options[variant!!.int32])
}
for ((i, option) in options.withIndex()) {
menu.appendItem(MenuItem(stringifier.apply(i, option), "$groupName$name($i)"))

View File

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

View File

@ -12,9 +12,9 @@ object Memory {
const val MB = KB * 1024
const val GB = MB * 1024
private val impl = when (OSUtils.TYPE) {
OSUtils.Type.LINUX -> LinuxMI()
OSUtils.Type.WINDOWS -> WindowsMI()
OSUtils.Type.MAC_OS -> MacOsMI()
OSUtils.Type.LINUX -> LinuxMI
OSUtils.Type.WINDOWS -> WindowsMI
OSUtils.Type.MAC_OS -> MacOsMI
}
private val totalMemory by lazy { impl.getTotalMemory() }
val maxMBForInstance: Long get() = (totalMemory / MB - 1024).coerceAtLeast(1024)
@ -23,7 +23,7 @@ object Memory {
fun getTotalMemory(): Long
}
private class LinuxMI : MI {
private object LinuxMI : MI {
override fun getTotalMemory(): Long {
try {
Files.lines(Path.of("/proc/meminfo")).use { stream ->
@ -45,49 +45,47 @@ object Memory {
}
}
companion object {
// Taken from oshi
private val BYTES_PATTERN = Pattern.compile("(\\d+) ?([kKMGT]?B?).*")
private val WHITESPACES = Pattern.compile("\\s+")
private fun parseDecimalMemorySizeToBinary(size: String): Long {
var mem = WHITESPACES.split(size)
if (mem.size < 2) {
// If no spaces, use regexp
val matcher = BYTES_PATTERN.matcher(size.trim { it <= ' ' })
if (matcher.find() && matcher.groupCount() == 2) {
mem = arrayOfNulls(2)
mem[0] = matcher.group(1)
mem[1] = matcher.group(2)
}
// Taken from oshi
private val BYTES_PATTERN = Pattern.compile("(\\d+) ?([kKMGT]?B?).*")
private val WHITESPACES = Pattern.compile("\\s+")
private fun parseDecimalMemorySizeToBinary(size: String): Long {
var mem = WHITESPACES.split(size)
if (mem.size < 2) {
// If no spaces, use regexp
val matcher = BYTES_PATTERN.matcher(size.trim { it <= ' ' })
if (matcher.find() && matcher.groupCount() == 2) {
mem = arrayOfNulls(2)
mem[0] = matcher.group(1)
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 {
s.toLong()
} catch (e: NumberFormatException) {
defaultLong
}
private fun parseLongOrDefault(s: String, defaultLong: Long): Long = try {
s.toLong()
} catch (e: NumberFormatException) {
defaultLong
}
}
private class WindowsMI : MI {
private object WindowsMI : MI {
override fun getTotalMemory(): Long {
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 {
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
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.URISyntaxException
class MicrosoftLoginDialog @JvmOverloads constructor(
class MicrosoftLoginDialog(
parent: Window?,
account: MicrosoftAccount? = null,
onClose: Runnable? = null