Skip to content

Commit 452b973

Browse files
committed
proper onChange listener invocation in settings
1 parent f0c3d08 commit 452b973

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

src/main/kotlin/com/lambda/config/Setting.kt

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import com.lambda.brigadier.executeWithResult
2929
import com.lambda.brigadier.required
3030
import com.lambda.command.CommandRegistry
3131
import com.lambda.command.commands.ConfigCommand
32+
import com.lambda.config.Setting.ValueListener
3233
import com.lambda.context.SafeContext
3334
import com.lambda.gui.dsl.ImGuiBuilder
3435
import com.lambda.threading.runSafe
@@ -98,6 +99,15 @@ abstract class SettingCore<T : Any>(
9899
val type: Type
99100
) {
100101
var value = defaultValue
102+
set(value) {
103+
val oldValue = field
104+
field = value
105+
listeners.forEach {
106+
if (it.requiresValueChange && oldValue == value) return@forEach
107+
it.execute(oldValue, value)
108+
}
109+
}
110+
val listeners = mutableListOf<ValueListener<T>>()
101111

102112
context(setting: Setting<*, T>)
103113
abstract fun ImGuiBuilder.buildLayout()
@@ -148,7 +158,6 @@ class Setting<T : SettingCore<R>, R : Any>(
148158
val visibility: () -> Boolean,
149159
) : Nameable, Describable {
150160
val originalCore = core
151-
val listeners = mutableListOf<ValueListener<R>>()
152161
var disabled = { false }
153162
var groups: MutableList<List<NamedEnum>> = mutableListOf()
154163

@@ -158,12 +167,7 @@ class Setting<T : SettingCore<R>, R : Any>(
158167

159168
operator fun getValue(thisRef: Any?, property: KProperty<*>) = core.value
160169
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: R) {
161-
val oldValue = core.value
162170
core.value = value
163-
listeners.forEach {
164-
if (it.requiresValueChange && oldValue == value) return@forEach
165-
it.execute(oldValue, value)
166-
}
167171
}
168172

169173
fun reset(silent: Boolean = false) {
@@ -192,19 +196,19 @@ class Setting<T : SettingCore<R>, R : Any>(
192196
* E.g., if the variable is a list, it will only register if the list reference changes, not if the content of the list changes.
193197
*/
194198
fun onValueChange(block: SafeContext.(from: R, to: R) -> Unit) = apply {
195-
listeners.add(ValueListener(true) { from, to ->
199+
core.listeners.add(ValueListener(true) { from, to ->
196200
runSafe {
197201
block(from, to)
198202
}
199203
})
200204
}
201205

202206
fun onValueChangeUnsafe(block: (from: R, to: R) -> Unit) = apply {
203-
listeners.add(ValueListener(true, block))
207+
core.listeners.add(ValueListener(true, block))
204208
}
205209

206210
fun onValueSet(block: (from: R, to: R) -> Unit) = apply {
207-
listeners.add(ValueListener(false, block))
211+
core.listeners.add(ValueListener(false, block))
208212
}
209213

210214
fun disabled(predicate: () -> Boolean) = apply {

0 commit comments

Comments
 (0)