scoop:scoop.terminal.asyncio:0.1.0
src/raw_scope.scoop
Selected production source · src/raw_scope.scoop
1
package scoop.terminal.asyncio3
import scoop.asyncio.*5
/**6
* Runs a suspending block in raw mode and restores the previous non-raw state on exit when this7
* scope changed it. Already-raw sessions retain their mode.8
*/9
public 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() }13
}15
internal class RawModeScope(private val session: AsyncTerminalSession,16
private val reserved: Boolean) : AsyncCloseable {17
private var changed: Boolean = false18
internal suspend fun enter() {19
if (!session.raw.load()) {20
session.changeRaw(true)21
changed = true22
}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 = false29
}30
}32
internal 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 primary38
}39
refreshRaw()40
}42
private suspend fun AsyncTerminalSession.refreshRaw() {43
if (!gate.isClosing && !isClosed) raw.store(tty.isRawMode())44
}