Scoop API

scoop:scoop.terminal.asyncio:0.1.0

src/session.scoop

Selected production source · src/session.scoop

1package scoop.terminal.asyncio
3import scoop.asyncio.*
4import scoop.platform.memory.NativeByteBuffer
5import scoop.terminal.TerminalSize
6import scoop.terminal.event.Event
7import scoop.terminal.protocol.InputParser
8import scoop.time.Duration
10/**
11 * An event-loop-bound terminal session combining parsed input, terminal queries, raw-mode control,
12 * and asynchronous output. Operations require an active job on the owning loop; close the session
13 * after use.
14 */
15public class AsyncTerminalSession private constructor(
16 internal val tty: AsyncTty,
17 private val loop: EventLoop,
18 parser: InputParser
19): AsyncByteSink, AsyncCloseable {
20 internal val gate: SessionGate = SessionGate()
21 internal val raw: AtomicBoolean = AtomicBoolean(false)
22 internal val input: SessionInput = SessionInput(SessionReader(tty, parser, raw))
23 /**
24 * Whether the underlying asynchronous terminal handle is closed.
25 */
26 public val isClosed: Boolean get() = tty.isClosed
28 /**
29 * Opens a session over the event loop's terminal handle.
30 */
31 public companion object {
32 /**
33 * Opens the terminal on the supplied loop. `escapeDelay` controls how long an incomplete
34 * escape sequence may wait before being treated as input.
35 */
36 public suspend fun open(
37 loop: EventLoop,
38 escapeDelay: Duration = Duration.milliseconds(50L)
39 ): AsyncTerminalSession {
40 val parser = InputParser(escapeDelay)
41 val tty = loop.openTty()
42 try {
43 return AsyncTerminalSession(tty, loop, parser)
44 }
45 catch (primary: Throwable) {
46 try {
47 tty.close()
48 }
49 catch (cleanup: Throwable) {
50 throw ResourceUseException(primary, cleanup)
51 }
52 throw primary
53 }
54 }
55 }
57 private fun requireJob(cancellable: Boolean) {
58 val current =
59 contextOrNone<EventLoop>() ?: throw IllegalStateException(Some("missing event loop"))
60 if (current !== loop)
61 throw IllegalStateException(Some("wrong event loop"))
62 val job =
63 currentJobOrNone() ?: throw IllegalStateException(Some("terminal I/O requires a Job"))
64 if (job.isCompleted)
65 throw IllegalStateException(Some("terminal I/O requires an active Job"))
66 if (cancellable)
67 job.ensureActive()
68 if (tty.isClosed)
69 throw IoClosedException()
70 }
72 internal suspend fun <R> withAccess(
73 reading: Boolean,
74 writing: Boolean,
75 cancellable: Boolean = true,
76 block: suspend () -> R
77 ): R {
78 requireJob(cancellable)
79 gate.acquire(reading, writing)
80 try {
81 return block()
82 }
83 finally {
84 gate.release(reading, writing)
85 }
86 }
88 /**
89 * Waits for the next parsed keyboard, mouse, paste, focus, or resize event.
90 */
91 public suspend fun read(): Event = withAccess(true, false) suspend { input.read() }
92 /**
93 * Waits up to a nonnegative timeout for a parsed input event without consuming the event. A
94 * zero timeout checks current availability.
95 */
96 public suspend fun poll(timeout: Duration): Boolean {
97 if (timeout < Duration.ZERO)
98 throw IllegalArgumentException(Some("negative terminal poll timeout"))
99 return withAccess(true, false) suspend { input.poll(Some(timeout)) }
100 }
102 /**
103 * Reads the terminal dimensions, including pixel dimensions when the host supplies them.
104 */
105 public suspend fun size(): TerminalSize =
106 withAccess(true, true) suspend {
107 val value = tty.size()
108 TerminalSize(value.columns, value.rows, value.widthPixels, value.heightPixels)
109 }
110 /**
111 * Reads the actual terminal mode and refreshes the session's tracked raw-mode state.
112 */
113 public suspend fun isRawMode(): Boolean =
114 withAccess(true, true, false) suspend {
115 val value = tty.isRawMode()
116 raw.store(value)
117 value
118 }
119 /**
120 * Enables raw terminal input while reserving session input and output access.
121 */
122 public suspend fun enableRawMode() {
123 withAccess(true, true) suspend { changeRaw(true) }
124 }
125 /**
126 * Restores non-raw terminal input. Cleanup can call this even when the active job is
127 * cancelling.
128 */
129 public suspend fun disableRawMode() {
130 withAccess(true, true, false) suspend { changeRaw(false) }
131 }
133 /**
134 * Writes readable buffer bytes through the terminal handle and advances the buffer by actual
135 * progress.
136 */
137 public override suspend fun writeFrom(buffer: NativeByteBuffer, count: Long): Long =
138 withAccess(false, true) suspend { tty.writeFrom(buffer, count) }
139 /**
140 * Waits for buffered terminal output to be flushed.
141 */
142 public override suspend fun flush() {
143 withAccess(false, true) suspend { tty.flush() }
144 }
146 /**
147 * Closes the terminal handle and waits for active session operations to leave their access
148 * scopes. Repeated closes after cleanup return immediately.
149 */
150 public override suspend fun close() {
151 if (tty.isClosed && gate.isIdle)
152 return
153 if (!tty.isClosed)
154 requireJob(false)
155 gate.beginClose()
156 try {
157 tty.close()
158 }
159 finally {
160 gate.awaitIdle()
161 }
162 }