Scoop API

scoop:scoop.terminal:0.1.0

src/session.scoop

Selected production source · src/session.scoop

1package scoop.terminal
3import scoop.terminal.protocol.*
4import scoop.platform.io.ByteSink
5import scoop.platform.memory.NativeByteBuffer
6import scoop.terminal.internal.platform.*
7import scoop.terminal.internal.input.*
8import scoop.terminal.event.Event
9import scoop.time.Duration
11/**
12 * Selects a process standard endpoint for terminal detection.
13 */
14public enum StandardStream {
15 /**
16 * Standard input.
17 */
18 Input,
19 /**
20 * Standard output.
21 */
22 Output,
23 /**
24 * Standard error.
25 */
26 Error
29/**
30 * Tests whether the selected standard endpoint refers to a terminal.
31 */
32public fun isTerminal(stream: StandardStream): Boolean {
33 val number =
34 when (stream) {
35 case Input -> 0;
36 case Output -> 1;
37 case Error -> 2
38 }
39 @Unsafe
40 {
41 return nativeIsTerminal(number)
42 }
45/**
46 * Terminal dimensions in character cells and platform-reported pixels.
47 */
48public struct TerminalSize(
49 val columns: Long,
50 val rows: Long,
51 val widthPixels: Long,
52 val heightPixels: Long
55/**
56 * An owned synchronous terminal session with input parsing, queries, byte output, and raw-mode
57 * restoration. Operations on one session must not overlap.
58 */
59public class TerminalSession private constructor(escapeDelay: Duration): ByteSink, Closeable {
60 private val terminal: TerminalHandle = TerminalHandle()
61 private val input: SessionInput = SessionInput(escapeDelay)
62 private val active: AtomicBoolean = AtomicBoolean(false)
63 /**
64 * Whether the native terminal handle has been closed.
65 */
66 public val isClosed: Boolean get() = withState { terminal.isClosed }
67 /**
68 * Whether this session currently has raw mode enabled.
69 */
70 public val isRawMode: Boolean get() = withTerminal { it.isRaw }
72 /**
73 * Opens owned terminal sessions independently of redirected standard streams.
74 */
75 public companion object {
76 /**
77 * Opens the terminal and initializes input parsing with a nonnegative Escape ambiguity
78 * delay.
79 */
80 public fun open(escapeDelay: Duration = Duration.milliseconds(50L)): TerminalSession {
81 val session = TerminalSession(escapeDelay)
82 session.terminal.open()
83 try {
84 session.input.initialize(session.terminal)
85 }
86 catch (primary: Throwable) {
87 try {
88 session.close()
89 }
90 catch (cleanup: Throwable) {
91 throw ResourceUseException(primary, cleanup)
92 }
93 throw primary
94 }
95 return session
96 }
97 }
99 private fun <R> withState(block: () -> R): R {
100 if (!active.compareAndSet(false, true))
101 throw IllegalStateException(Some("terminal operation is active"))
102 try {
103 return block()
104 }
105 finally {
106 active.store(false)
107 }
108 }
110 internal fun <R> withTerminal(block: (TerminalHandle) -> R): R =
111 withState {
112 if (terminal.isClosed)
113 throw IllegalStateException(Some("terminal is closed"))
114 block(terminal)
115 }
117 /**
118 * Queries current character-cell and pixel dimensions.
119 */
120 public fun size(): TerminalSize = withTerminal { it.size() }
121 /**
122 * Enables raw input mode, retaining the state needed for restoration.
123 */
124 public fun enableRawMode() {
125 withTerminal { it.setRaw(true) }
126 }
127 /**
128 * Restores the mode saved before raw input was enabled.
129 */
130 public fun disableRawMode() {
131 withTerminal { it.setRaw(false) }
132 }
133 /**
134 * Waits for the next user-facing event, preserving query replies for query processing.
135 */
136 public fun read(): Event = withTerminal { input.read(it) }
137 /**
138 * Waits up to a nonnegative duration and reports whether a user event is ready.
139 */
140 public fun poll(timeout: Duration): Boolean {
141 if (timeout < Duration.ZERO)
142 throw IllegalArgumentException(Some("negative terminal poll timeout"))
143 return withTerminal { input.poll(it, Some(timeout)) }
144 }
146 internal fun query(kind: QueryKind, timeout: Duration): InputItem {
147 if (timeout < Duration.ZERO)
148 throw IllegalArgumentException(Some("negative terminal query timeout"))
149 return withTerminal {
150 handle -> QueryRawScope(handle).use { input.query(handle, kind, timeout) }
151 }
152 }
154 /**
155 * Writes up to count readable bytes to the terminal and advances the input buffer.
156 */
157 public override fun writeFrom(buffer: NativeByteBuffer, count: Long): Long =
158 withTerminal { it.write(buffer, count) }
159 /**
160 * Checks the unbuffered terminal session state; queued library commands are written
161 * immediately.
162 */
163 public override fun flush() {
164 withTerminal {}
165 }
167 /**
168 * Restores terminal state and closes the owned handle; close cannot overlap another session
169 * operation.
170 */
171 public override fun close() {
172 withState {
173 if (!terminal.isClosed)
174 terminal.close()
175 Unit
176 }
177 }