scoop:scoop.terminal:0.1.0
src/internal/input/characters.scoop
Selected production source · src/internal/input/characters.scoop
1
package scoop.terminal.internal.input3
import scoop.terminal.protocol.*4
import scoop.terminal.event.*5
import scoop.time.Duration7
internal fun InputParser.startKey(byte: Int, now: Duration) {8
if (byte == 27) {9
mode = InputMode.Escape10
escapeStarted = Some(now)11
} else if (byte < 128) {12
emit(withAlt(plainKey(byte, raw)))13
} else if (byte >= 194 && byte <= 244) {14
mode = InputMode.Utf815
utf8Width = if (byte < 224) 2L else if (byte < 240) 3L else 4L16
pending.add(byte.toByte())17
} else emit(InputItem.Invalid("invalid UTF-8 initial byte"))18
}20
internal fun InputParser.continueUtf8(byte: Int, now: Duration) {21
if (byte < 128 || byte > 191) {22
emit(InputItem.Invalid("invalid UTF-8 continuation byte"))23
startKey(byte, now)24
return25
}26
pending.add(byte.toByte())27
if (pending.size < utf8Width) return28
val text = String.fromUtf8OrNone(pending)29
if (text == None) emit(InputItem.Invalid("invalid UTF-8 scalar"))30
else emit(withAlt(characterKey(text!!.getCharAt(0L))))31
}33
private fun InputParser.withAlt(event: KeyEvent): InputItem =34
InputItem.User(Event.Key(if (alt)35
KeyEvent(event.code, event.modifiers.with(KeyModifier.Alt), event.kind, event.state) else event))37
private fun characterKey(character: Char): KeyEvent = KeyEvent(KeyCode.Char(character),38
if (isUppercaseKey(character)) KeyModifiers().with(KeyModifier.Shift) else KeyModifiers())40
private fun plainKey(byte: Int, raw: Boolean): KeyEvent {41
if (byte == 13 || (byte == 10 && !raw)) return KeyEvent(KeyCode.Enter)42
if (byte == 9) return KeyEvent(KeyCode.Tab)43
if (byte == 127) return KeyEvent(KeyCode.Backspace)44
val control = KeyModifiers().with(KeyModifier.Control)45
if (byte == 0) return KeyEvent(KeyCode.Char(' '), control)46
if (byte >= 1 && byte <= 26) return KeyEvent(KeyCode.Char((byte + 96).toChar()), control)47
if (byte >= 28 && byte <= 31) return KeyEvent(KeyCode.Char((byte + 24).toChar()), control)48
return characterKey(byte.toChar())49
}