Debian Codegraph @

input/parse.go

raw
1 package input
2
3 import (
4 "bytes"
5 "encoding/base64"
6 "slices"
7 "strings"
8 "unicode"
9 "unicode/utf8"
10
11 "github.com/charmbracelet/x/ansi"
12 "github.com/charmbracelet/x/ansi/parser"
13 "github.com/rivo/uniseg"
14 )
15
16 // Flags to control the behavior of the parser.
17 const (
18 // When this flag is set, the driver will treat both Ctrl+Space and Ctrl+@
19 // as the same key sequence.
20 //
21 // Historically, the ANSI specs generate NUL (0x00) on both the Ctrl+Space
22 // and Ctrl+@ key sequences. This flag allows the driver to treat both as
23 // the same key sequence.
24 FlagCtrlAt = 1 << iota
25
26 // When this flag is set, the driver will treat the Tab key and Ctrl+I as
27 // the same key sequence.
28 //
29 // Historically, the ANSI specs generate HT (0x09) on both the Tab key and
30 // Ctrl+I. This flag allows the driver to treat both as the same key
31 // sequence.
32 FlagCtrlI
33
34 // When this flag is set, the driver will treat the Enter key and Ctrl+M as
35 // the same key sequence.
36 //
37 // Historically, the ANSI specs generate CR (0x0D) on both the Enter key
38 // and Ctrl+M. This flag allows the driver to treat both as the same key.
39 FlagCtrlM
40
41 // When this flag is set, the driver will treat Escape and Ctrl+[ as
42 // the same key sequence.
43 //
44 // Historically, the ANSI specs generate ESC (0x1B) on both the Escape key
45 // and Ctrl+[. This flag allows the driver to treat both as the same key
46 // sequence.
47 FlagCtrlOpenBracket
48
49 // When this flag is set, the driver will send a BS (0x08 byte) character
50 // instead of a DEL (0x7F byte) character when the Backspace key is
51 // pressed.
52 //
53 // The VT100 terminal has both a Backspace and a Delete key. The VT220
54 // terminal dropped the Backspace key and replaced it with the Delete key.
55 // Both terminals send a DEL character when the Delete key is pressed.
56 // Modern terminals and PCs later readded the Delete key but used a
57 // different key sequence, and the Backspace key was standardized to send a
58 // DEL character.
59 FlagBackspace
60
61 // When this flag is set, the driver will recognize the Find key instead of
62 // treating it as a Home key.
63 //
64 // The Find key was part of the VT220 keyboard, and is no longer used in
65 // modern day PCs.
66 FlagFind
67
68 // When this flag is set, the driver will recognize the Select key instead
69 // of treating it as a End key.
70 //
71 // The Symbol key was part of the VT220 keyboard, and is no longer used in
72 // modern day PCs.
73 FlagSelect
74
75 // When this flag is set, the driver will use Terminfo databases to
76 // overwrite the default key sequences.
77 FlagTerminfo
78
79 // When this flag is set, the driver will preserve function keys (F13-F63)
80 // as symbols.
81 //
82 // Since these keys are not part of today's standard 20th century keyboard,
83 // we treat them as F1-F12 modifier keys i.e. ctrl/shift/alt + Fn combos.
84 // Key definitions come from Terminfo, this flag is only useful when
85 // FlagTerminfo is not set.
86 FlagFKeys
87
88 // When this flag is set, the driver will enable mouse mode on Windows.
89 // This is only useful on Windows and has no effect on other platforms.
90 FlagMouseMode
91 )
92
93 // Parser is a parser for input escape sequences.
94 type Parser struct {
95 flags int
96 }
97
98 // NewParser returns a new input parser. This is a low-level parser that parses
99 // escape sequences into human-readable events.
100 // This differs from [ansi.Parser] and [ansi.DecodeSequence] in which it
101 // recognizes incorrect sequences that some terminals may send.
102 //
103 // For instance, the X10 mouse protocol sends a `CSI M` sequence followed by 3
104 // bytes. If the parser doesn't recognize the 3 bytes, they might be echoed to
105 // the terminal output causing a mess.
106 //
107 // Another example is how URxvt sends invalid sequences for modified keys using
108 // invalid CSI final characters like '$'.
109 //
110 // Use flags to control the behavior of ambiguous key sequences.
111 func NewParser(flags int) *Parser {
112 return &Parser{flags: flags}
113 }
114
115 // parseSequence finds the first recognized event sequence and returns it along
116 // with its length.
117 //
118 // It will return zero and nil no sequence is recognized or when the buffer is
119 // empty. If a sequence is not supported, an UnknownEvent is returned.
120 func (p *Parser) parseSequence(buf []byte) (n int, Event Event) {
121 if len(buf) == 0 {
122 return 0, nil
123 }
124
125 switch b := buf[0]; b {
126 case ansi.ESC:
127 if len(buf) == 1 {
128 // Escape key
129 return 1, KeyPressEvent{Code: KeyEscape}
130 }
131
132 switch bPrime := buf[1]; bPrime {
133 case 'O': // Esc-prefixed SS3
134 return p.parseSs3(buf)
135 case 'P': // Esc-prefixed DCS
136 return p.parseDcs(buf)
137 case '[': // Esc-prefixed CSI
138 return p.parseCsi(buf)
139 case ']': // Esc-prefixed OSC
140 return p.parseOsc(buf)
141 case '_': // Esc-prefixed APC
142 return p.parseApc(buf)
143 case '^': // Esc-prefixed PM
144 return p.parseStTerminated(ansi.PM, '^', nil)(buf)
145 case 'X': // Esc-prefixed SOS
146 return p.parseStTerminated(ansi.SOS, 'X', nil)(buf)
147 default:
148 n, e := p.parseSequence(buf[1:])
149 if k, ok := e.(KeyPressEvent); ok {
150 k.Text = ""
151 k.Mod |= ModAlt
152 return n + 1, k
153 }
154
155 // Not a key sequence, nor an alt modified key sequence. In that
156 // case, just report a single escape key.
157 return 1, KeyPressEvent{Code: KeyEscape}
158 }
159 case ansi.SS3:
160 return p.parseSs3(buf)
161 case ansi.DCS:
162 return p.parseDcs(buf)
163 case ansi.CSI:
164 return p.parseCsi(buf)
165 case ansi.OSC:
166 return p.parseOsc(buf)
167 case ansi.APC:
168 return p.parseApc(buf)
169 case ansi.PM:
170 return p.parseStTerminated(ansi.PM, '^', nil)(buf)
171 case ansi.SOS:
172 return p.parseStTerminated(ansi.SOS, 'X', nil)(buf)
173 default:
174 if b <= ansi.US || b == ansi.DEL || b == ansi.SP {
175 return 1, p.parseControl(b)
176 } else if b >= ansi.PAD && b <= ansi.APC {
177 // C1 control code
178 // UTF-8 never starts with a C1 control code
179 // Encode these as Ctrl+Alt+<code - 0x40>
180 code := rune(b) - 0x40
181 return 1, KeyPressEvent{Code: code, Mod: ModCtrl | ModAlt}
182 }
183 return p.parseUtf8(buf)
184 }
185 }
186
187 func (p *Parser) parseCsi(b []byte) (int, Event) {
188 if len(b) == 2 && b[0] == ansi.ESC {
189 // short cut if this is an alt+[ key
190 return 2, KeyPressEvent{Text: string(rune(b[1])), Mod: ModAlt}
191 }
192
193 var cmd ansi.Cmd
194 var params [parser.MaxParamsSize]ansi.Param
195 var paramsLen int
196
197 var i int
198 if b[i] == ansi.CSI || b[i] == ansi.ESC {
199 i++
200 }
201 if i < len(b) && b[i-1] == ansi.ESC && b[i] == '[' {
202 i++
203 }
204
205 // Initial CSI byte
206 if i < len(b) && b[i] >= '<' && b[i] <= '?' {
207 cmd |= ansi.Cmd(b[i]) << parser.PrefixShift
208 }
209
210 // Scan parameter bytes in the range 0x30-0x3F
211 var j int
212 for j = 0; i < len(b) && paramsLen < len(params) && b[i] >= 0x30 && b[i] <= 0x3F; i, j = i+1, j+1 {
213 if b[i] >= '0' && b[i] <= '9' {
214 if params[paramsLen] == parser.MissingParam {
215 params[paramsLen] = 0
216 }
217 params[paramsLen] *= 10
218 params[paramsLen] += ansi.Param(b[i]) - '0'
219 }
220 if b[i] == ':' {
221 params[paramsLen] |= parser.HasMoreFlag
222 }
223 if b[i] == ';' || b[i] == ':' {
224 paramsLen++
225 if paramsLen < len(params) {
226 // Don't overflow the params slice
227 params[paramsLen] = parser.MissingParam
228 }
229 }
230 }
231
232 if j > 0 && paramsLen < len(params) {
233 // has parameters
234 paramsLen++
235 }
236
237 // Scan intermediate bytes in the range 0x20-0x2F
238 var intermed byte
239 for ; i < len(b) && b[i] >= 0x20 && b[i] <= 0x2F; i++ {
240 intermed = b[i]
241 }
242
243 // Set the intermediate byte
244 cmd |= ansi.Cmd(intermed) << parser.IntermedShift
245
246 // Scan final byte in the range 0x40-0x7E
247 if i >= len(b) || b[i] < 0x40 || b[i] > 0x7E {
248 // Special case for URxvt keys
249 // CSI <number> $ is an invalid sequence, but URxvt uses it for
250 // shift modified keys.
251 if b[i-1] == '$' {
252 n, ev := p.parseCsi(append(b[:i-1], '~'))
253 if k, ok := ev.(KeyPressEvent); ok {
254 k.Mod |= ModShift
255 return n, k
256 }
257 }
258 return i, UnknownEvent(b[:i-1])
259 }
260
261 // Add the final byte
262 cmd |= ansi.Cmd(b[i])
263 i++
264
265 pa := ansi.Params(params[:paramsLen])
266 switch cmd {
267 case 'y' | '?'<<parser.PrefixShift | '$'<<parser.IntermedShift:
268 // Report Mode (DECRPM)
269 mode, _, ok := pa.Param(0, -1)
270 if !ok || mode == -1 {
271 break
272 }
273 value, _, ok := pa.Param(1, -1)
274 if !ok || value == -1 {
275 break
276 }
277 return i, ModeReportEvent{Mode: ansi.DECMode(mode), Value: ansi.ModeSetting(value)}
278 case 'c' | '?'<<parser.PrefixShift:
279 // Primary Device Attributes
280 return i, parsePrimaryDevAttrs(pa)
281 case 'u' | '?'<<parser.PrefixShift:
282 // Kitty keyboard flags
283 flags, _, ok := pa.Param(0, -1)
284 if !ok || flags == -1 {
285 break
286 }
287 return i, KittyEnhancementsEvent(flags)
288 case 'R' | '?'<<parser.PrefixShift:
289 // This report may return a third parameter representing the page
290 // number, but we don't really need it.
291 row, _, ok := pa.Param(0, 1)
292 if !ok {
293 break
294 }
295 col, _, ok := pa.Param(1, 1)
296 if !ok {
297 break
298 }
299 return i, CursorPositionEvent{Y: row - 1, X: col - 1}
300 case 'm' | '<'<<parser.PrefixShift, 'M' | '<'<<parser.PrefixShift:
301 // Handle SGR mouse
302 if paramsLen == 3 {
303 return i, parseSGRMouseEvent(cmd, pa)
304 }
305 case 'm' | '>'<<parser.PrefixShift:
306 // XTerm modifyOtherKeys
307 mok, _, ok := pa.Param(0, 0)
308 if !ok || mok != 4 {
309 break
310 }
311 val, _, ok := pa.Param(1, -1)
312 if !ok || val == -1 {
313 break
314 }
315 return i, ModifyOtherKeysEvent(val) //nolint:gosec
316 case 'I':
317 return i, FocusEvent{}
318 case 'O':
319 return i, BlurEvent{}
320 case 'R':
321 // Cursor position report OR modified F3
322 row, _, rok := pa.Param(0, 1)
323 col, _, cok := pa.Param(1, 1)
324 if paramsLen == 2 && rok && cok {
325 m := CursorPositionEvent{Y: row - 1, X: col - 1}
326 if row == 1 && col-1 <= int(ModMeta|ModShift|ModAlt|ModCtrl) {
327 // XXX: We cannot differentiate between cursor position report and
328 // CSI 1 ; <mod> R (which is modified F3) when the cursor is at the
329 // row 1. In this case, we report both messages.
330 //
331 // For a non ambiguous cursor position report, use
332 // [ansi.RequestExtendedCursorPosition] (DECXCPR) instead.
333 return i, MultiEvent{KeyPressEvent{Code: KeyF3, Mod: KeyMod(col - 1)}, m}
334 }
335
336 return i, m
337 }
338
339 if paramsLen != 0 {
340 break
341 }
342
343 // Unmodified key F3 (CSI R)
344 fallthrough
345 case 'a', 'b', 'c', 'd', 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'P', 'Q', 'S', 'Z':
346 var k KeyPressEvent
347 switch cmd {
348 case 'a', 'b', 'c', 'd':
349 k = KeyPressEvent{Code: KeyUp + rune(cmd-'a'), Mod: ModShift}
350 case 'A', 'B', 'C', 'D':
351 k = KeyPressEvent{Code: KeyUp + rune(cmd-'A')}
352 case 'E':
353 k = KeyPressEvent{Code: KeyBegin}
354 case 'F':
355 k = KeyPressEvent{Code: KeyEnd}
356 case 'H':
357 k = KeyPressEvent{Code: KeyHome}
358 case 'P', 'Q', 'R', 'S':
359 k = KeyPressEvent{Code: KeyF1 + rune(cmd-'P')}
360 case 'Z':
361 k = KeyPressEvent{Code: KeyTab, Mod: ModShift}
362 }
363 id, _, _ := pa.Param(0, 1)
364 if id == 0 {
365 id = 1
366 }
367 mod, _, _ := pa.Param(1, 1)
368 if mod == 0 {
369 mod = 1
370 }
371 if paramsLen > 1 && id == 1 && mod != -1 {
372 // CSI 1 ; <modifiers> A
373 k.Mod |= KeyMod(mod - 1)
374 }
375 // Don't forget to handle Kitty keyboard protocol
376 return i, parseKittyKeyboardExt(pa, k)
377 case 'M':
378 // Handle X10 mouse
379 if i+3 > len(b) {
380 return i, UnknownEvent(b[:i])
381 }
382 return i + 3, parseX10MouseEvent(append(b[:i], b[i:i+3]...))
383 case 'y' | '$'<<parser.IntermedShift:
384 // Report Mode (DECRPM)
385 mode, _, ok := pa.Param(0, -1)
386 if !ok || mode == -1 {
387 break
388 }
389 val, _, ok := pa.Param(1, -1)
390 if !ok || val == -1 {
391 break
392 }
393 return i, ModeReportEvent{Mode: ansi.ANSIMode(mode), Value: ansi.ModeSetting(val)}
394 case 'u':
395 // Kitty keyboard protocol & CSI u (fixterms)
396 if paramsLen == 0 {
397 return i, UnknownEvent(b[:i])
398 }
399 return i, parseKittyKeyboard(pa)
400 case '_':
401 // Win32 Input Mode
402 if paramsLen != 6 {
403 return i, UnknownEvent(b[:i])
404 }
405
406 vrc, _, _ := pa.Param(5, 0)
407 rc := uint16(vrc) //nolint:gosec
408 if rc == 0 {
409 rc = 1
410 }
411
412 vk, _, _ := pa.Param(0, 0)
413 sc, _, _ := pa.Param(1, 0)
414 uc, _, _ := pa.Param(2, 0)
415 kd, _, _ := pa.Param(3, 0)
416 cs, _, _ := pa.Param(4, 0)
417 event := p.parseWin32InputKeyEvent(
418 nil,
419 uint16(vk), //nolint:gosec // Vk wVirtualKeyCode
420 uint16(sc), //nolint:gosec // Sc wVirtualScanCode
421 rune(uc), // Uc UnicodeChar
422 kd == 1, // Kd bKeyDown
423 uint32(cs), //nolint:gosec // Cs dwControlKeyState
424 rc, // Rc wRepeatCount
425 )
426
427 if event == nil {
428 return i, UnknownEvent(b[:])
429 }
430
431 return i, event
432 case '@', '^', '~':
433 if paramsLen == 0 {
434 return i, UnknownEvent(b[:i])
435 }
436
437 param, _, _ := pa.Param(0, 0)
438 switch cmd {
439 case '~':
440 switch param {
441 case 27:
442 // XTerm modifyOtherKeys 2
443 if paramsLen != 3 {
444 return i, UnknownEvent(b[:i])
445 }
446 return i, parseXTermModifyOtherKeys(pa)
447 case 200:
448 // bracketed-paste start
449 return i, PasteStartEvent{}
450 case 201:
451 // bracketed-paste end
452 return i, PasteEndEvent{}
453 }
454 }
455
456 switch param {
457 case 1, 2, 3, 4, 5, 6, 7, 8,
458 11, 12, 13, 14, 15,
459 17, 18, 19, 20, 21,
460 23, 24, 25, 26,
461 28, 29, 31, 32, 33, 34:
462 var k KeyPressEvent
463 switch param {
464 case 1:
465 if p.flags&FlagFind != 0 {
466 k = KeyPressEvent{Code: KeyFind}
467 } else {
468 k = KeyPressEvent{Code: KeyHome}
469 }
470 case 2:
471 k = KeyPressEvent{Code: KeyInsert}
472 case 3:
473 k = KeyPressEvent{Code: KeyDelete}
474 case 4:
475 if p.flags&FlagSelect != 0 {
476 k = KeyPressEvent{Code: KeySelect}
477 } else {
478 k = KeyPressEvent{Code: KeyEnd}
479 }
480 case 5:
481 k = KeyPressEvent{Code: KeyPgUp}
482 case 6:
483 k = KeyPressEvent{Code: KeyPgDown}
484 case 7:
485 k = KeyPressEvent{Code: KeyHome}
486 case 8:
487 k = KeyPressEvent{Code: KeyEnd}
488 case 11, 12, 13, 14, 15:
489 k = KeyPressEvent{Code: KeyF1 + rune(param-11)}
490 case 17, 18, 19, 20, 21:
491 k = KeyPressEvent{Code: KeyF6 + rune(param-17)}
492 case 23, 24, 25, 26:
493 k = KeyPressEvent{Code: KeyF11 + rune(param-23)}
494 case 28, 29:
495 k = KeyPressEvent{Code: KeyF15 + rune(param-28)}
496 case 31, 32, 33, 34:
497 k = KeyPressEvent{Code: KeyF17 + rune(param-31)}
498 }
499
500 // modifiers
501 mod, _, _ := pa.Param(1, -1)
502 if paramsLen > 1 && mod != -1 {
503 k.Mod |= KeyMod(mod - 1)
504 }
505
506 // Handle URxvt weird keys
507 switch cmd {
508 case '~':
509 // Don't forget to handle Kitty keyboard protocol
510 return i, parseKittyKeyboardExt(pa, k)
511 case '^':
512 k.Mod |= ModCtrl
513 case '@':
514 k.Mod |= ModCtrl | ModShift
515 }
516
517 return i, k
518 }
519
520 case 't':
521 param, _, ok := pa.Param(0, 0)
522 if !ok {
523 break
524 }
525
526 var winop WindowOpEvent
527 winop.Op = param
528 for j := 1; j < paramsLen; j++ {
529 val, _, ok := pa.Param(j, 0)
530 if ok {
531 winop.Args = append(winop.Args, val)
532 }
533 }
534
535 return i, winop
536 }
537 return i, UnknownEvent(b[:i])
538 }
539
540 // parseSs3 parses a SS3 sequence.
541 // See https://vt100.net/docs/vt220-rm/chapter4.html#S4.4.4.2
542 func (p *Parser) parseSs3(b []byte) (int, Event) {
543 if len(b) == 2 && b[0] == ansi.ESC {
544 // short cut if this is an alt+O key
545 return 2, KeyPressEvent{Code: rune(b[1]), Mod: ModAlt}
546 }
547
548 var i int
549 if b[i] == ansi.SS3 || b[i] == ansi.ESC {
550 i++
551 }
552 if i < len(b) && b[i-1] == ansi.ESC && b[i] == 'O' {
553 i++
554 }
555
556 // Scan numbers from 0-9
557 var mod int
558 for ; i < len(b) && b[i] >= '0' && b[i] <= '9'; i++ {
559 mod *= 10
560 mod += int(b[i]) - '0'
561 }
562
563 // Scan a GL character
564 // A GL character is a single byte in the range 0x21-0x7E
565 // See https://vt100.net/docs/vt220-rm/chapter2.html#S2.3.2
566 if i >= len(b) || b[i] < 0x21 || b[i] > 0x7E {
567 return i, UnknownEvent(b[:i])
568 }
569
570 // GL character(s)
571 gl := b[i]
572 i++
573
574 var k KeyPressEvent
575 switch gl {
576 case 'a', 'b', 'c', 'd':
577 k = KeyPressEvent{Code: KeyUp + rune(gl-'a'), Mod: ModCtrl}
578 case 'A', 'B', 'C', 'D':
579 k = KeyPressEvent{Code: KeyUp + rune(gl-'A')}
580 case 'E':
581 k = KeyPressEvent{Code: KeyBegin}
582 case 'F':
583 k = KeyPressEvent{Code: KeyEnd}
584 case 'H':
585 k = KeyPressEvent{Code: KeyHome}
586 case 'P', 'Q', 'R', 'S':
587 k = KeyPressEvent{Code: KeyF1 + rune(gl-'P')}
588 case 'M':
589 k = KeyPressEvent{Code: KeyKpEnter}
590 case 'X':
591 k = KeyPressEvent{Code: KeyKpEqual}
592 case 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y':
593 k = KeyPressEvent{Code: KeyKpMultiply + rune(gl-'j')}
594 default:
595 return i, UnknownEvent(b[:i])
596 }
597
598 // Handle weird SS3 <modifier> Func
599 if mod > 0 {
600 k.Mod |= KeyMod(mod - 1)
601 }
602
603 return i, k
604 }
605
606 func (p *Parser) parseOsc(b []byte) (int, Event) {
607 defaultKey := func() KeyPressEvent {
608 return KeyPressEvent{Code: rune(b[1]), Mod: ModAlt}
609 }
610 if len(b) == 2 && b[0] == ansi.ESC {
611 // short cut if this is an alt+] key
612 return 2, defaultKey()
613 }
614
615 var i int
616 if b[i] == ansi.OSC || b[i] == ansi.ESC {
617 i++
618 }
619 if i < len(b) && b[i-1] == ansi.ESC && b[i] == ']' {
620 i++
621 }
622
623 // Parse OSC command
624 // An OSC sequence is terminated by a BEL, ESC, or ST character
625 var start, end int
626 cmd := -1
627 for ; i < len(b) && b[i] >= '0' && b[i] <= '9'; i++ {
628 if cmd == -1 {
629 cmd = 0
630 } else {
631 cmd *= 10
632 }
633 cmd += int(b[i]) - '0'
634 }
635
636 if i < len(b) && b[i] == ';' {
637 // mark the start of the sequence data
638 i++
639 start = i
640 }
641
642 for ; i < len(b); i++ {
643 // advance to the end of the sequence
644 if slices.Contains([]byte{ansi.BEL, ansi.ESC, ansi.ST, ansi.CAN, ansi.SUB}, b[i]) {
645 break
646 }
647 }
648
649 if i >= len(b) {
650 return i, UnknownEvent(b[:i])
651 }
652
653 end = i // end of the sequence data
654 i++
655
656 // Check 7-bit ST (string terminator) character
657 switch b[i-1] {
658 case ansi.CAN, ansi.SUB:
659 return i, UnknownEvent(b[:i])
660 case ansi.ESC:
661 if i >= len(b) || b[i] != '\\' {
662 if cmd == -1 || (start == 0 && end == 2) {
663 return 2, defaultKey()
664 }
665
666 // If we don't have a valid ST terminator, then this is a
667 // cancelled sequence and should be ignored.
668 return i, UnknownEvent(b[:i])
669 }
670
671 i++
672 }
673
674 if end <= start {
675 return i, UnknownEvent(b[:i])
676 }
677
678 data := string(b[start:end])
679 switch cmd {
680 case 10:
681 return i, ForegroundColorEvent{ansi.XParseColor(data)}
682 case 11:
683 return i, BackgroundColorEvent{ansi.XParseColor(data)}
684 case 12:
685 return i, CursorColorEvent{ansi.XParseColor(data)}
686 case 52:
687 parts := strings.Split(data, ";")
688 if len(parts) == 0 {
689 return i, ClipboardEvent{}
690 }
691 if len(parts) != 2 || len(parts[0]) < 1 {
692 break
693 }
694
695 b64 := parts[1]
696 bts, err := base64.StdEncoding.DecodeString(b64)
697 if err != nil {
698 break
699 }
700
701 sel := ClipboardSelection(parts[0][0]) //nolint:unconvert
702 return i, ClipboardEvent{Selection: sel, Content: string(bts)}
703 }
704
705 return i, UnknownEvent(b[:i])
706 }
707
708 // parseStTerminated parses a control sequence that gets terminated by a ST character.
709 func (p *Parser) parseStTerminated(intro8, intro7 byte, fn func([]byte) Event) func([]byte) (int, Event) {
710 defaultKey := func(b []byte) (int, Event) {
711 switch intro8 {
712 case ansi.SOS:
713 return 2, KeyPressEvent{Code: 'x', Mod: ModShift | ModAlt}
714 case ansi.PM, ansi.APC:
715 return 2, KeyPressEvent{Code: rune(b[1]), Mod: ModAlt}
716 }
717 return 0, nil
718 }
719 return func(b []byte) (int, Event) {
720 if len(b) == 2 && b[0] == ansi.ESC {
721 return defaultKey(b)
722 }
723
724 var i int
725 if b[i] == intro8 || b[i] == ansi.ESC {
726 i++
727 }
728 if i < len(b) && b[i-1] == ansi.ESC && b[i] == intro7 {
729 i++
730 }
731
732 // Scan control sequence
733 // Most common control sequence is terminated by a ST character
734 // ST is a 7-bit string terminator character is (ESC \)
735 start := i
736 for ; i < len(b); i++ {
737 if slices.Contains([]byte{ansi.ESC, ansi.ST, ansi.CAN, ansi.SUB}, b[i]) {
738 break
739 }
740 }
741
742 if i >= len(b) {
743 return i, UnknownEvent(b[:i])
744 }
745
746 end := i // end of the sequence data
747 i++
748
749 // Check 7-bit ST (string terminator) character
750 switch b[i-1] {
751 case ansi.CAN, ansi.SUB:
752 return i, UnknownEvent(b[:i])
753 case ansi.ESC:
754 if i >= len(b) || b[i] != '\\' {
755 if start == end {
756 return defaultKey(b)
757 }
758
759 // If we don't have a valid ST terminator, then this is a
760 // cancelled sequence and should be ignored.
761 return i, UnknownEvent(b[:i])
762 }
763
764 i++
765 }
766
767 // Call the function to parse the sequence and return the result
768 if fn != nil {
769 if e := fn(b[start:end]); e != nil {
770 return i, e
771 }
772 }
773
774 return i, UnknownEvent(b[:i])
775 }
776 }
777
778 func (p *Parser) parseDcs(b []byte) (int, Event) {
779 if len(b) == 2 && b[0] == ansi.ESC {
780 // short cut if this is an alt+P key
781 return 2, KeyPressEvent{Code: 'p', Mod: ModShift | ModAlt}
782 }
783
784 var params [16]ansi.Param
785 var paramsLen int
786 var cmd ansi.Cmd
787
788 // DCS sequences are introduced by DCS (0x90) or ESC P (0x1b 0x50)
789 var i int
790 if b[i] == ansi.DCS || b[i] == ansi.ESC {
791 i++
792 }
793 if i < len(b) && b[i-1] == ansi.ESC && b[i] == 'P' {
794 i++
795 }
796
797 // initial DCS byte
798 if i < len(b) && b[i] >= '<' && b[i] <= '?' {
799 cmd |= ansi.Cmd(b[i]) << parser.PrefixShift
800 }
801
802 // Scan parameter bytes in the range 0x30-0x3F
803 var j int
804 for j = 0; i < len(b) && paramsLen < len(params) && b[i] >= 0x30 && b[i] <= 0x3F; i, j = i+1, j+1 {
805 if b[i] >= '0' && b[i] <= '9' {
806 if params[paramsLen] == parser.MissingParam {
807 params[paramsLen] = 0
808 }
809 params[paramsLen] *= 10
810 params[paramsLen] += ansi.Param(b[i]) - '0'
811 }
812 if b[i] == ':' {
813 params[paramsLen] |= parser.HasMoreFlag
814 }
815 if b[i] == ';' || b[i] == ':' {
816 paramsLen++
817 if paramsLen < len(params) {
818 // Don't overflow the params slice
819 params[paramsLen] = parser.MissingParam
820 }
821 }
822 }
823
824 if j > 0 && paramsLen < len(params) {
825 // has parameters
826 paramsLen++
827 }
828
829 // Scan intermediate bytes in the range 0x20-0x2F
830 var intermed byte
831 for j := 0; i < len(b) && b[i] >= 0x20 && b[i] <= 0x2F; i, j = i+1, j+1 {
832 intermed = b[i]
833 }
834
835 // set intermediate byte
836 cmd |= ansi.Cmd(intermed) << parser.IntermedShift
837
838 // Scan final byte in the range 0x40-0x7E
839 if i >= len(b) || b[i] < 0x40 || b[i] > 0x7E {
840 return i, UnknownEvent(b[:i])
841 }
842
843 // Add the final byte
844 cmd |= ansi.Cmd(b[i])
845 i++
846
847 start := i // start of the sequence data
848 for ; i < len(b); i++ {
849 if b[i] == ansi.ST || b[i] == ansi.ESC {
850 break
851 }
852 }
853
854 if i >= len(b) {
855 return i, UnknownEvent(b[:i])
856 }
857
858 end := i // end of the sequence data
859 i++
860
861 // Check 7-bit ST (string terminator) character
862 if i < len(b) && b[i-1] == ansi.ESC && b[i] == '\\' {
863 i++
864 }
865
866 pa := ansi.Params(params[:paramsLen])
867 switch cmd {
868 case 'r' | '+'<<parser.IntermedShift:
869 // XTGETTCAP responses
870 param, _, _ := pa.Param(0, 0)
871 switch param {
872 case 1: // 1 means valid response, 0 means invalid response
873 tc := parseTermcap(b[start:end])
874 // XXX: some terminals like KiTTY report invalid responses with
875 // their queries i.e. sending a query for "Tc" using "\x1bP+q5463\x1b\\"
876 // returns "\x1bP0+r5463\x1b\\".
877 // The specs says that invalid responses should be in the form of
878 // DCS 0 + r ST "\x1bP0+r\x1b\\"
879 // We ignore invalid responses and only send valid ones to the program.
880 //
881 // See: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands
882 return i, tc
883 }
884 case '|' | '>'<<parser.PrefixShift:
885 // XTVersion response
886 return i, TerminalVersionEvent(b[start:end])
887 }
888
889 return i, UnknownEvent(b[:i])
890 }
891
892 func (p *Parser) parseApc(b []byte) (int, Event) {
893 if len(b) == 2 && b[0] == ansi.ESC {
894 // short cut if this is an alt+_ key
895 return 2, KeyPressEvent{Code: rune(b[1]), Mod: ModAlt}
896 }
897
898 // APC sequences are introduced by APC (0x9f) or ESC _ (0x1b 0x5f)
899 return p.parseStTerminated(ansi.APC, '_', func(b []byte) Event {
900 if len(b) == 0 {
901 return nil
902 }
903
904 switch b[0] {
905 case 'G': // Kitty Graphics Protocol
906 var g KittyGraphicsEvent
907 parts := bytes.Split(b[1:], []byte{';'})
908 g.Options.UnmarshalText(parts[0]) //nolint:errcheck,gosec
909 if len(parts) > 1 {
910 g.Payload = parts[1]
911 }
912 return g
913 }
914
915 return nil
916 })(b)
917 }
918
919 func (p *Parser) parseUtf8(b []byte) (int, Event) {
920 if len(b) == 0 {
921 return 0, nil
922 }
923
924 c := b[0]
925 if c <= ansi.US || c == ansi.DEL || c == ansi.SP {
926 // Control codes get handled by parseControl
927 return 1, p.parseControl(c)
928 } else if c > ansi.US && c < ansi.DEL {
929 // ASCII printable characters
930 code := rune(c)
931 k := KeyPressEvent{Code: code, Text: string(code)}
932 if unicode.IsUpper(code) {
933 // Convert upper case letters to lower case + shift modifier
934 k.Code = unicode.ToLower(code)
935 k.ShiftedCode = code
936 k.Mod |= ModShift
937 }
938
939 return 1, k
940 }
941
942 code, _ := utf8.DecodeRune(b)
943 if code == utf8.RuneError {
944 return 1, UnknownEvent(b[0])
945 }
946
947 cluster, _, _, _ := uniseg.FirstGraphemeCluster(b, -1)
948 text := string(cluster)
949 for i := range text {
950 if i > 0 {
951 // Use [KeyExtended] for multi-rune graphemes
952 code = KeyExtended
953 break
954 }
955 }
956
957 return len(cluster), KeyPressEvent{Code: code, Text: text}
958 }
959
960 func (p *Parser) parseControl(b byte) Event {
961 switch b {
962 case ansi.NUL:
963 if p.flags&FlagCtrlAt != 0 {
964 return KeyPressEvent{Code: '@', Mod: ModCtrl}
965 }
966 return KeyPressEvent{Code: KeySpace, Mod: ModCtrl}
967 case ansi.BS:
968 return KeyPressEvent{Code: 'h', Mod: ModCtrl}
969 case ansi.HT:
970 if p.flags&FlagCtrlI != 0 {
971 return KeyPressEvent{Code: 'i', Mod: ModCtrl}
972 }
973 return KeyPressEvent{Code: KeyTab}
974 case ansi.CR:
975 if p.flags&FlagCtrlM != 0 {
976 return KeyPressEvent{Code: 'm', Mod: ModCtrl}
977 }
978 return KeyPressEvent{Code: KeyEnter}
979 case ansi.ESC:
980 if p.flags&FlagCtrlOpenBracket != 0 {
981 return KeyPressEvent{Code: '[', Mod: ModCtrl}
982 }
983 return KeyPressEvent{Code: KeyEscape}
984 case ansi.DEL:
985 if p.flags&FlagBackspace != 0 {
986 return KeyPressEvent{Code: KeyDelete}
987 }
988 return KeyPressEvent{Code: KeyBackspace}
989 case ansi.SP:
990 return KeyPressEvent{Code: KeySpace, Text: " "}
991 default:
992 if b >= ansi.SOH && b <= ansi.SUB {
993 // Use lower case letters for control codes
994 code := rune(b + 0x60)
995 return KeyPressEvent{Code: code, Mod: ModCtrl}
996 } else if b >= ansi.FS && b <= ansi.US {
997 code := rune(b + 0x40)
998 return KeyPressEvent{Code: code, Mod: ModCtrl}
999 }
1000 return UnknownEvent(b)
1001 }
1002 }