diff options
author | nea <nea@nea.moe> | 2023-05-29 23:28:52 +0200 |
---|---|---|
committer | nea <nea@nea.moe> | 2023-05-29 23:28:52 +0200 |
commit | dd0afac3a8459035827dac36986a690c8a9541ea (patch) | |
tree | 2bc3ab50b69590a6811a8265f4c533163d07457c /src/main/kotlin/moe/nea/firmament/util/async/input.kt | |
parent | c133505e3b1f8e5aeb62c1a0e99513ec4bfcf239 (diff) | |
download | Firmament-dd0afac3a8459035827dac36986a690c8a9541ea.tar.gz Firmament-dd0afac3a8459035827dac36986a690c8a9541ea.tar.bz2 Firmament-dd0afac3a8459035827dac36986a690c8a9541ea.zip |
Add price checker
Diffstat (limited to 'src/main/kotlin/moe/nea/firmament/util/async/input.kt')
-rw-r--r-- | src/main/kotlin/moe/nea/firmament/util/async/input.kt | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/src/main/kotlin/moe/nea/firmament/util/async/input.kt b/src/main/kotlin/moe/nea/firmament/util/async/input.kt new file mode 100644 index 0000000..ac1cfb4 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/async/input.kt @@ -0,0 +1,45 @@ +package moe.nea.firmament.util.async + +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlin.coroutines.resume +import moe.nea.firmament.events.HandledScreenKeyPressedEvent +import moe.nea.firmament.keybindings.IKeyBinding + +private object InputHandler { + data class KeyInputContinuation(val keybind: IKeyBinding, val onContinue: () -> Unit) + + private val activeContinuations = mutableListOf<KeyInputContinuation>() + + fun registerContinuation(keyInputContinuation: KeyInputContinuation): () -> Unit { + synchronized(InputHandler) { + activeContinuations.add(keyInputContinuation) + } + return { + synchronized(this) { + activeContinuations.remove(keyInputContinuation) + } + } + } + + init { + HandledScreenKeyPressedEvent.subscribe { event -> + synchronized(InputHandler) { + val toRemove = activeContinuations.filter { + event.matches(it.keybind) + } + toRemove.forEach { it.onContinue() } + activeContinuations.removeAll(toRemove) + } + } + } +} + +suspend fun waitForInput(keybind: IKeyBinding): Unit = suspendCancellableCoroutine { cont -> + val unregister = + InputHandler.registerContinuation(InputHandler.KeyInputContinuation(keybind) { cont.resume(Unit) }) + cont.invokeOnCancellation { + unregister() + } +} + + |