scoop:scoop.terminal.asyncio:0.1.0
src/reader.scoop
Selected production source · src/reader.scoop
1
package scoop.terminal.asyncio3
import scoop.asyncio.*4
import scoop.platform.memory.NativeByteBuffer5
import scoop.terminal.TerminalDisconnectedException6
import scoop.terminal.protocol.*7
import scoop.time.Duration9
internal class SessionReader(private val tty: AsyncTty, internal val parser: InputParser,10
private val raw: AtomicBoolean) {11
private var ended: Boolean = false12
internal val exhausted: Boolean get() = ended && !parser.hasPending14
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 None31
}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(_) -> true44
case Resize(val columns, val rows) -> { parser.feedResize(columns, rows); true }45
case End -> { ended = true; parser.finish(); true }46
case TimedOut -> false47
}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
}56
}