Scoop API

scoop:scoop.terminal.asyncio:0.1.0

src/raw_scope.scoop

Selected production source · src/raw_scope.scoop

1package scoop.terminal.asyncio
3import scoop.asyncio.*
5/**
6 * Runs a suspending block in raw mode and restores the previous non-raw state on exit when this
7 * scope changed it. Already-raw sessions retain their mode.
8 */
9public suspend fun <R> AsyncTerminalSession.withRawMode(block: suspend () -> R): R {
10 val scope = RawModeScope(this, false)
11 withAccess(true, true) suspend { scope.enter() }
12 return scope.useAsync suspend { block() }
15internal class RawModeScope(private val session: AsyncTerminalSession,
16 private val reserved: Boolean) : AsyncCloseable {
17 private var changed: Boolean = false
18 internal suspend fun enter() {
19 if (!session.raw.load()) {
20 session.changeRaw(true)
21 changed = true
22 }
23 }
24 public override suspend fun close() {
25 if (changed && !session.gate.isClosing && !session.isClosed) {
26 if (reserved) session.changeRaw(false) else session.disableRawMode()
27 }
28 changed = false
29 }
32internal suspend fun AsyncTerminalSession.changeRaw(enabled: Boolean) {
33 try { if (enabled) tty.enableRawMode() else tty.disableRawMode() }
34 catch (primary: Throwable) {
35 try { refreshRaw() }
36 catch (cleanup: Throwable) { throw ResourceUseException(primary, cleanup) }
37 throw primary
38 }
39 refreshRaw()
42private suspend fun AsyncTerminalSession.refreshRaw() {
43 if (!gate.isClosing && !isClosed) raw.store(tty.isRawMode())