Scoop API

scoop:scoop.terminal:0.1.0

src/internal/input/characters.scoop

Selected production source · src/internal/input/characters.scoop

1package scoop.terminal.internal.input
3import scoop.terminal.protocol.*
4import scoop.terminal.event.*
5import scoop.time.Duration
7internal fun InputParser.startKey(byte: Int, now: Duration) {
8 if (byte == 27) {
9 mode = InputMode.Escape
10 escapeStarted = Some(now)
11 } else if (byte < 128) {
12 emit(withAlt(plainKey(byte, raw)))
13 } else if (byte >= 194 && byte <= 244) {
14 mode = InputMode.Utf8
15 utf8Width = if (byte < 224) 2L else if (byte < 240) 3L else 4L
16 pending.add(byte.toByte())
17 } else emit(InputItem.Invalid("invalid UTF-8 initial byte"))
20internal 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 return
25 }
26 pending.add(byte.toByte())
27 if (pending.size < utf8Width) return
28 val text = String.fromUtf8OrNone(pending)
29 if (text == None) emit(InputItem.Invalid("invalid UTF-8 scalar"))
30 else emit(withAlt(characterKey(text!!.getCharAt(0L))))
33private 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))
37private fun characterKey(character: Char): KeyEvent = KeyEvent(KeyCode.Char(character),
38 if (isUppercaseKey(character)) KeyModifiers().with(KeyModifier.Shift) else KeyModifiers())
40private 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())