scoop:scoop.terminal:0.1.0
src/internal/platform/handle.scoop
Selected production source · src/internal/platform/handle.scoop
1
package scoop.terminal.internal.platform3
import scoop.platform.io.WriteZeroException4
import scoop.platform.memory.NativeByteBuffer5
import scoop.platform.system.*6
import scoop.terminal.TerminalSize8
internal class TerminalHandle {9
private var pointer: Ptr<Unit>? = None10
internal val isRaw: Boolean get() {11
@Unsafe12
{13
return nativeRawEnabled(pointer!!)14
}15
}16
internal val isClosed: Boolean get() = pointer == None17
internal fun <R> withPointer(block: (Ptr<Unit>) -> R): R = block(pointer!!)19
internal fun open() {20
@Unsafe21
{22
val result = nativeOpen()23
if (result.value == None)24
failTerminal("open terminal", result.error)25
pointer = result.value26
}27
}29
internal fun setRaw(enabled: Boolean) {30
@Unsafe31
{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
@Unsafe40
{41
val result = nativeSize(pointer!!)42
val value = result.value43
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 0L56
@Unsafe57
{58
val written =59
buffer.withReadableBytes {60
data,61
_ -> @Unsafe62
{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.value69
}70
}71
buffer.skip(written)72
return written73
}74
}76
internal fun close() {77
val handle = pointer!!78
pointer = None79
@Unsafe80
{81
val result = nativeClose(handle)82
if (result.value < 0)83
failTerminal("close terminal", result.error)84
}85
}86
}88
internal fun failTerminal(operation: String, code: Int): Nothing {89
val error = terminalError(code)90
throw PlatformException(operation, error.kind, Some(error))91
}93
internal fun terminalError(code: Int): NativeError =94
NativeError(95
if (operatingSystem == OperatingSystem.Windows)96
NativeErrorDomain.Win3297
else98
NativeErrorDomain.PosixErrno,99
code100
)