Scoop API

scoop:scoop.terminal:0.1.0

src/internal/platform/handle.scoop

Selected production source · src/internal/platform/handle.scoop

1package scoop.terminal.internal.platform
3import scoop.platform.io.WriteZeroException
4import scoop.platform.memory.NativeByteBuffer
5import scoop.platform.system.*
6import scoop.terminal.TerminalSize
8internal class TerminalHandle {
9 private var pointer: Ptr<Unit>? = None
10 internal val isRaw: Boolean get() {
11 @Unsafe
12 {
13 return nativeRawEnabled(pointer!!)
14 }
15 }
16 internal val isClosed: Boolean get() = pointer == None
17 internal fun <R> withPointer(block: (Ptr<Unit>) -> R): R = block(pointer!!)
19 internal fun open() {
20 @Unsafe
21 {
22 val result = nativeOpen()
23 if (result.value == None)
24 failTerminal("open terminal", result.error)
25 pointer = result.value
26 }
27 }
29 internal fun setRaw(enabled: Boolean) {
30 @Unsafe
31 {
32 val result = nativeRaw(pointer!!, enabled)
33 if (result.value < 0)
34 failTerminal("set terminal raw mode", result.error)
35 }
36 }
38 internal fun size(): TerminalSize {
39 @Unsafe
40 {
41 val result = nativeSize(pointer!!)
42 val value = result.value
43 if (value.columns < 0L)
44 failTerminal("terminal size", result.error)
45 return TerminalSize(value.columns, value.rows, value.widthPixels, value.heightPixels)
46 }
47 }
49 internal fun write(buffer: NativeByteBuffer, count: Long): Long {
50 if (count < 0L)
51 throw IllegalArgumentException(Some("negative terminal write count"))
52 if (count > buffer.readableBytes)
53 throw IndexOutOfBoundsException()
54 if (count == 0L)
55 return 0L
56 @Unsafe
57 {
58 val written =
59 buffer.withReadableBytes {
60 data,
61 _ -> @Unsafe
62 {
63 val result = nativeWrite(pointer!!, data!!, count)
64 if (result.value < 0L)
65 failTerminal("write terminal", result.error)
66 if (result.value == 0L)
67 throw WriteZeroException()
68 return@withReadableBytes result.value
69 }
70 }
71 buffer.skip(written)
72 return written
73 }
74 }
76 internal fun close() {
77 val handle = pointer!!
78 pointer = None
79 @Unsafe
80 {
81 val result = nativeClose(handle)
82 if (result.value < 0)
83 failTerminal("close terminal", result.error)
84 }
85 }
88internal fun failTerminal(operation: String, code: Int): Nothing {
89 val error = terminalError(code)
90 throw PlatformException(operation, error.kind, Some(error))
93internal fun terminalError(code: Int): NativeError =
94 NativeError(
95 if (operatingSystem == OperatingSystem.Windows)
96 NativeErrorDomain.Win32
97 else
98 NativeErrorDomain.PosixErrno,
99 code
100 )