Scoop API

scoop:scoop.terminal.asyncio:0.1.0

src/reader.scoop

Selected production source · src/reader.scoop

1package scoop.terminal.asyncio
3import scoop.asyncio.*
4import scoop.platform.memory.NativeByteBuffer
5import scoop.terminal.TerminalDisconnectedException
6import scoop.terminal.protocol.*
7import scoop.time.Duration
9internal class SessionReader(private val tty: AsyncTty, internal val parser: InputParser,
10 private val raw: AtomicBoolean) {
11 private var ended: Boolean = false
12 internal val exhausted: Boolean get() = ended && !parser.hasPending
14 internal suspend fun next(timeout: Duration?): InputItem? {
15 val started = inputNow()
16 while (true) {
17 if (parser.hasPending) return parser.next()
18 if (ended) throw TerminalDisconnectedException()
19 val received = receive(Some(Duration.ZERO))
20 if (parser.hasPending) return parser.next()
21 if (ended) throw TerminalDisconnectedException()
22 if (!received) {
23 parser.advance(inputNow())
24 if (parser.hasPending) return parser.next()
25 }
26 if (inputExpired(started, timeout)) {
27 if (received && !receive(Some(Duration.ZERO))) parser.advance(inputNow())
28 if (parser.hasPending) return parser.next()
29 if (ended) throw TerminalDisconnectedException()
30 return None
31 }
32 if (!received) receive(shorter(inputRemaining(started, timeout), parser.escapeRemaining))
33 }
34 }
36 internal suspend fun receiveAvailable() { if (!ended) receive(Some(Duration.ZERO)) }
38 private suspend fun receive(timeout: Duration?): Boolean {
39 val buffer = NativeByteBuffer.allocate(4096L)
40 try {
41 try {
42 return when (tty.receive(buffer, buffer.capacity, timeout)) {
43 case Bytes(_) -> true
44 case Resize(val columns, val rows) -> { parser.feedResize(columns, rows); true }
45 case End -> { ended = true; parser.finish(); true }
46 case TimedOut -> false
47 }
48 } finally {
49 // Cancellation still commits bytes read before the selected terminal result.
50 if (buffer.readableBytes > 0L) {
51 parser.feed(buffer.readBytes(buffer.readableBytes), inputNow(), raw.load())
52 }
53 }
54 } finally { buffer.close() }
55 }