From 2a5e795203ef50afec7a27984cb40f668b06d2f9 Mon Sep 17 00:00:00 2001 From: Edwin Jakobs Date: Sun, 7 Nov 2021 15:31:35 +0100 Subject: [PATCH] [orx-olive] Add Once delegate --- orx-jvm/orx-olive/src/main/kotlin/OliveProgram.kt | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/orx-jvm/orx-olive/src/main/kotlin/OliveProgram.kt b/orx-jvm/orx-olive/src/main/kotlin/OliveProgram.kt index 482a66ce..2146d2a4 100644 --- a/orx-jvm/orx-olive/src/main/kotlin/OliveProgram.kt +++ b/orx-jvm/orx-olive/src/main/kotlin/OliveProgram.kt @@ -5,8 +5,11 @@ import org.openrndr.Program import java.io.File import java.nio.file.Files import java.nio.file.Paths +import kotlin.reflect.KProperty import kotlin.streams.toList + + open class OliveProgram(private val sourceLocation: String, private val scriptHost: OliveScriptHost, resources: Resources?) : Program() { val olive = extend(Olive(scriptMode = ScriptMode.OLIVE_PROGRAM, resources = resources)) { script = sourceLocation @@ -14,6 +17,18 @@ open class OliveProgram(private val sourceLocation: String, private val scriptHo } } +/** + * Delegate used to create instances exactly once. Instances survive a script reload. + */ +class Once(val build:() -> T) { + companion object { + private val values = mutableMapOf() + } + @Suppress("UNCHECKED_CAST") + operator fun getValue(thisRef:Any?, property:KProperty<*>) : T = values.getOrPut(property.name) { build() } as T +} + + fun stackRootClassName(thread: Thread = Thread.currentThread(), sanitize: Boolean = true): String { val root = Thread.currentThread().stackTrace.last() val rootClass = root.className