diff options
author | nea <nea@nea.moe> | 2023-08-11 22:42:01 +0200 |
---|---|---|
committer | nea <nea@nea.moe> | 2023-08-15 19:38:27 +0200 |
commit | b32f5da88c355645a9eaf343987f10506aa25bee (patch) | |
tree | 0bd12cb09844907fdaf8048601b4192df17c9244 /src/main/kotlin/moe/nea/firmament/gui/config/ManagedOption.kt | |
parent | 2b33dd1b11a0a64e1c32a3bf639d73a952b10e75 (diff) | |
download | Firmament-b32f5da88c355645a9eaf343987f10506aa25bee.tar.gz Firmament-b32f5da88c355645a9eaf343987f10506aa25bee.tar.bz2 Firmament-b32f5da88c355645a9eaf343987f10506aa25bee.zip |
Add slightly more modular options
Diffstat (limited to 'src/main/kotlin/moe/nea/firmament/gui/config/ManagedOption.kt')
-rw-r--r-- | src/main/kotlin/moe/nea/firmament/gui/config/ManagedOption.kt | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/src/main/kotlin/moe/nea/firmament/gui/config/ManagedOption.kt b/src/main/kotlin/moe/nea/firmament/gui/config/ManagedOption.kt new file mode 100644 index 0000000..3ffe0b0 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/gui/config/ManagedOption.kt @@ -0,0 +1,58 @@ +/* + * SPDX-FileCopyrightText: 2023 Linnea Gräf <nea@nea.moe> + * + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package moe.nea.firmament.gui.config + +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlin.properties.ReadWriteProperty +import kotlin.reflect.KProperty +import net.minecraft.text.Text +import moe.nea.firmament.Firmament + +class ManagedOption<T : Any>( + val element: ManagedConfigElement, + val propertyName: String, + val default: () -> T, + val handler: ManagedConfig.OptionHandler<T> +) : ReadWriteProperty<Any?, T> { + + val rawLabelText = "firmament.config.${element.name}.${propertyName}" + val labelText = Text.translatable(rawLabelText) + + lateinit var value: T + + override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { + this.value = value + } + + override fun getValue(thisRef: Any?, property: KProperty<*>): T { + return value + } + + fun load(root: JsonElement) { + if (root is JsonObject && root.containsKey(propertyName)) { + try { + value = handler.fromJson(root[propertyName]!!) + return + } catch (e: Exception) { + Firmament.logger.error( + "Exception during loading of config file ${element.name}. This will reset this config.", + e + ) + } + } + value = default() + } + + fun toJson(): JsonElement? { + return handler.toJson(value) + } + + fun appendToGui(guiapp: GuiAppender) { + handler.emitGuiElements(this, guiapp) + } +} |