gitstack

grindlemire/go-tui code browser

12.2 KB Go 519 lines 2026-03-28 ยท 7746d43 raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
package tui

import (
	"fmt"
	"unicode/utf8"

	"github.com/grindlemire/go-tui/internal/debug"
)

// parseInput parses buffered bytes into events.
// Handles:
// - Single printable characters -> KeyEvent{Key: KeyRune, Rune: r}
// - Control characters (0x00-0x1F) -> appropriate KeyEvent
// - CSI sequences (\x1b[...) -> Arrow keys, function keys with modifiers
// - SS3 sequences (\x1bO...) -> Some function keys
// - Alt+key: \x1b + printable -> KeyRune with ModAlt
func parseInput(data []byte) []Event {
	debug.Topic("keys", "parseInput: raw bytes (%d): %v", len(data), formatBytes(data))
	var events []Event
	i := 0

	for i < len(data) {
		b := data[i]

		// Check for escape sequence
		if b == 0x1b {
			// Look ahead to determine sequence type
			if i+1 >= len(data) {
				// Lone escape at end - treat as escape key
				events = append(events, KeyEvent{Key: KeyEscape})
				i++
				continue
			}

			next := data[i+1]
			switch next {
			case '[':
				// Check for SGR mouse sequence (ESC [ <)
				if i+2 < len(data) && data[i+2] == '<' {
					mouseEvent, consumed := parseMouseSGR(data[i:])
					if consumed > 0 {
						events = append(events, mouseEvent)
						i += consumed
						continue
					}
				}
				// CSI sequence
				key, mod, r, consumed := parseCSISequence(data[i:])
				if consumed > 0 {
					if key != KeyNone {
						events = append(events, KeyEvent{Key: key, Rune: r, Mod: mod})
					}
					i += consumed
					continue
				}
				// Failed to parse, treat as escape
				events = append(events, KeyEvent{Key: KeyEscape})
				i++
				continue

			case 'O':
				// SS3 sequence (function keys)
				if i+2 < len(data) {
					key := parseSS3(data[i+2])
					if key != KeyNone {
						events = append(events, KeyEvent{Key: key})
						i += 3
						continue
					}
				}
				// Failed to parse, treat as escape
				events = append(events, KeyEvent{Key: KeyEscape})
				i++
				continue

			default:
				// Alt+key combination
				if next >= 0x20 && next < 0x7f {
					events = append(events, KeyEvent{Key: KeyRune, Rune: rune(next), Mod: ModAlt})
					i += 2
					continue
				}
				// Unknown sequence, treat as escape
				events = append(events, KeyEvent{Key: KeyEscape})
				i++
				continue
			}
		}

		// Control characters (0x00-0x1F, except 0x1b which is handled above)
		if b < 0x20 {
			key, r, mod := controlToKey(b)
			events = append(events, KeyEvent{Key: key, Rune: r, Mod: mod})
			i++
			continue
		}

		// DEL character (0x7F) is backspace on most terminals
		if b == 0x7f {
			events = append(events, KeyEvent{Key: KeyBackspace})
			i++
			continue
		}

		// Printable characters (including multi-byte UTF-8)
		r, size := utf8.DecodeRune(data[i:])
		if r == utf8.RuneError && size == 1 {
			// Invalid UTF-8, skip byte
			i++
			continue
		}
		events = append(events, KeyEvent{Key: KeyRune, Rune: r})
		i += size
	}

	for _, ev := range events {
		if ke, ok := ev.(KeyEvent); ok {
			debug.Topic("keys", "parseInput: event Key=%s Rune=%q Mod=%s", ke.Key, ke.Rune, ke.Mod)
		} else if me, ok := ev.(MouseEvent); ok {
			debug.Topic("keys", "parseInput: mouse Button=%d Action=%d X=%d Y=%d", me.Button, me.Action, me.X, me.Y)
		}
	}
	return events
}

// formatBytes returns a human-readable hex dump of raw input bytes.
func formatBytes(data []byte) string {
	if len(data) == 0 {
		return "[]"
	}
	return fmt.Sprintf("%x", data)
}

// controlToKey converts a control character (0x00-0x1F) to a normalized key event.
// Ambiguous bytes (0x09, 0x0D, 0x1B) keep their semantic Key.
// All other Ctrl+letter bytes produce {KeyRune, letter, ModCtrl}.
//
// Why 0x08 is NOT mapped to KeyBackspace:
//
// Modern terminals send 0x7F for the Backspace key (handled separately in
// parseInput), so 0x08 only arrives as Ctrl+H. We let it fall through to
// the Ctrl+letter default: {KeyRune, 'h', ModCtrl}. Without this,
// On(KeyCtrlH, handler) would silently never fire in legacy mode because
// 0x08 would parse as KeyBackspace, which doesn't match the Ctrl+H pattern.
// In Kitty mode, Ctrl+H arrives as CSI 104;5u and Backspace as CSI 127;1u,
// so the distinction is handled by the CSI parser instead.
//
// The tradeoff: terminals configured with "stty erase ^H" send 0x08 for
// Backspace. On those (rare) setups, Backspace will fire KeyCtrlH handlers
// instead of KeyBackspace handlers. Users in that situation can reconfigure
// their terminal or bind both KeyBackspace and KeyCtrlH.
func controlToKey(b byte) (Key, rune, Modifier) {
	switch b {
	case 0x09:
		return KeyTab, 0, ModNone
	case 0x0d:
		return KeyEnter, 0, ModNone
	case 0x1b:
		return KeyEscape, 0, ModNone
	case 0x00:
		return KeyRune, ' ', ModCtrl // Ctrl+Space
	default:
		if b >= 0x01 && b <= 0x1a {
			return KeyRune, rune('a' + b - 1), ModCtrl
		}
		return KeyNone, 0, ModNone
	}
}

// parseCSISequence parses a CSI escape sequence starting at data[0].
// Returns the key, modifier, rune (for Kitty protocol), and number of bytes consumed.
// Returns (KeyNone, ModNone, 0, 0) if parsing fails.
func parseCSISequence(data []byte) (Key, Modifier, rune, int) {
	if len(data) < 3 || data[0] != 0x1b || data[1] != '[' {
		return KeyNone, ModNone, 0, 0
	}

	// Parse parameters (numbers separated by ;)
	var params []int
	currentParam := 0
	hasParam := false
	i := 2

	for i < len(data) {
		b := data[i]

		if b >= '0' && b <= '9' {
			currentParam = currentParam*10 + int(b-'0')
			hasParam = true
			i++
			continue
		}

		if b == ';' {
			params = append(params, currentParam)
			currentParam = 0
			hasParam = false
			i++
			continue
		}

		// Final byte (determines the key)
		if b >= 0x40 && b <= 0x7e {
			if hasParam {
				params = append(params, currentParam)
			}
			if b == 'u' {
				// Kitty keyboard protocol: CSI code ; modifiers u
				key, r, mod := parseKittyKey(params)
				return key, mod, r, i + 1
			}
			key, mod := parseCSI(params, b)
			return key, mod, 0, i + 1
		}

		// Unexpected character
		return KeyNone, ModNone, 0, 0
	}

	// Incomplete sequence
	return KeyNone, ModNone, 0, 0
}

// parseCSI parses a complete CSI sequence given parameters and final byte.
// Returns (Key, Modifier).
func parseCSI(params []int, final byte) (Key, Modifier) {
	mod := ModNone

	// Extract modifier from params (xterm-style: CSI 1;mod X)
	if len(params) >= 2 {
		mod = decodeModifier(params[1])
	}

	switch final {
	case 'A':
		return KeyUp, mod
	case 'B':
		return KeyDown, mod
	case 'C':
		return KeyRight, mod
	case 'D':
		return KeyLeft, mod
	case 'H':
		return KeyHome, mod
	case 'F':
		return KeyEnd, mod
	case '~':
		// Extended keys: CSI n ~
		if len(params) == 0 {
			return KeyNone, ModNone
		}
		switch params[0] {
		case 1:
			return KeyHome, mod
		case 2:
			return KeyInsert, mod
		case 3:
			return KeyDelete, mod
		case 4:
			return KeyEnd, mod
		case 5:
			return KeyPageUp, mod
		case 6:
			return KeyPageDown, mod
		case 11:
			return KeyF1, mod
		case 12:
			return KeyF2, mod
		case 13:
			return KeyF3, mod
		case 14:
			return KeyF4, mod
		case 15:
			return KeyF5, mod
		case 17:
			return KeyF6, mod
		case 18:
			return KeyF7, mod
		case 19:
			return KeyF8, mod
		case 20:
			return KeyF9, mod
		case 21:
			return KeyF10, mod
		case 23:
			return KeyF11, mod
		case 24:
			return KeyF12, mod
		}
	case 'P':
		return KeyF1, mod
	case 'Q':
		return KeyF2, mod
	case 'R':
		return KeyF3, mod
	case 'S':
		return KeyF4, mod
	case 'Z':
		// Backtab (Shift+Tab) - CSI Z
		return KeyTab, ModShift
	}

	return KeyNone, ModNone
}

// kittySpecialKeys maps Kitty keyboard protocol code points to Key constants.
// These are Unicode code points assigned by the protocol for functional keys
// that don't have a natural Unicode representation.
//
// Only code points sent in flag-1 (disambiguate) mode are included here.
// Code points in the 57xxx range (F-keys, navigation, keypad alternatives)
// are only sent in flag-2+ "report all keys" mode. Under flag 1, F-keys
// arrive as standard sequences (CSI 11~, SS3 P, etc.) handled by
// parseCSI/parseSS3, and keypad keys use their legacy code points (9, 13, 127).
var kittySpecialKeys = map[int]Key{
	9:   KeyTab,
	13:  KeyEnter,
	27:  KeyEscape,
	127: KeyBackspace,
}

// parseKittyKey parses a Kitty keyboard protocol CSI u sequence.
// Format: CSI code ; modifiers u
// Returns (key, rune, modifier).
func parseKittyKey(params []int) (Key, rune, Modifier) {
	code := 0
	if len(params) > 0 {
		code = params[0]
	}

	mod := ModNone
	if len(params) > 1 {
		mod = decodeModifier(params[1])
	}

	// Map special Kitty code points to existing Key constants
	if key, ok := kittySpecialKeys[code]; ok {
		return key, 0, mod
	}

	// Regular Unicode code point (printable range)
	if code >= 32 {
		return KeyRune, rune(code), mod
	}

	// Code points 1-31 (excluding 9, 13, 27 handled above) are C0 control
	// codes. Kitty normally sends these with a modifier param (e.g. mod=5
	// for Ctrl), which maps them to printable code points instead. If a bare
	// C0 code somehow arrives here, we drop it rather than misinterpret it.
	return KeyNone, 0, ModNone
}

// parseSS3 parses an SS3 function key sequence.
// Returns the key constant for the given final byte.
func parseSS3(b byte) Key {
	switch b {
	case 'P':
		return KeyF1
	case 'Q':
		return KeyF2
	case 'R':
		return KeyF3
	case 'S':
		return KeyF4
	case 'A':
		return KeyUp
	case 'B':
		return KeyDown
	case 'C':
		return KeyRight
	case 'D':
		return KeyLeft
	case 'H':
		return KeyHome
	case 'F':
		return KeyEnd
	}
	return KeyNone
}

// decodeModifier decodes the xterm modifier parameter.
// The parameter is encoded as: 1 + (shift ? 1 : 0) + (alt ? 2 : 0) + (ctrl ? 4 : 0)
// So: 1=none, 2=shift, 3=alt, 4=shift+alt, 5=ctrl, 6=ctrl+shift, 7=ctrl+alt, 8=all
func decodeModifier(param int) Modifier {
	if param <= 1 {
		return ModNone
	}

	// Subtract 1 to get the raw flags
	flags := param - 1
	var mod Modifier
	if flags&1 != 0 {
		mod |= ModShift
	}
	if flags&2 != 0 {
		mod |= ModAlt
	}
	if flags&4 != 0 {
		mod |= ModCtrl
	}
	return mod
}

// parseMouseSGR parses an SGR-1006 mouse sequence.
// Format: ESC [ < button ; x ; y M (press) or ESC [ < button ; x ; y m (release)
// The button field encodes: button number + modifier bits
//
//	bits 0-1: button (0=left, 1=middle, 2=right, 3=release/none)
//	bit 2: shift
//	bit 3: meta/alt
//	bit 4: ctrl
//	bit 5: motion (drag)
//	bit 6: wheel (64=up, 65=down)
//
// Returns (MouseEvent, bytes consumed). Returns (MouseEvent{}, 0) on failure.
func parseMouseSGR(data []byte) (MouseEvent, int) {
	// Minimum: ESC [ < b ; x ; y M = 10 bytes for single digits
	if len(data) < 9 || data[0] != 0x1b || data[1] != '[' || data[2] != '<' {
		return MouseEvent{}, 0
	}

	// Parse: button ; x ; y
	i := 3
	button := 0
	x := 0
	y := 0
	stage := 0 // 0=button, 1=x, 2=y

	for i < len(data) {
		b := data[i]

		if b >= '0' && b <= '9' {
			switch stage {
			case 0:
				button = button*10 + int(b-'0')
			case 1:
				x = x*10 + int(b-'0')
			case 2:
				y = y*10 + int(b-'0')
			}
			i++
			continue
		}

		if b == ';' {
			stage++
			if stage > 2 {
				// Too many semicolons
				return MouseEvent{}, 0
			}
			i++
			continue
		}

		// Final byte: 'M' for press, 'm' for release
		if b == 'M' || b == 'm' {
			if stage != 2 {
				// Didn't get all three parameters
				return MouseEvent{}, 0
			}

			event := MouseEvent{
				X: x - 1, // Convert from 1-indexed to 0-indexed
				Y: y - 1,
			}

			// Decode button and modifiers
			if button&4 != 0 {
				event.Mod |= ModShift
			}
			if button&8 != 0 {
				event.Mod |= ModAlt
			}
			if button&16 != 0 {
				event.Mod |= ModCtrl
			}

			// Check for wheel events (bit 6 set)
			if button&64 != 0 {
				if button&1 != 0 {
					event.Button = MouseWheelDown
				} else {
					event.Button = MouseWheelUp
				}
				event.Action = MousePress // Wheel events are instantaneous
			} else {
				// Regular button event
				buttonNum := button & 3
				switch buttonNum {
				case 0:
					event.Button = MouseLeft
				case 1:
					event.Button = MouseMiddle
				case 2:
					event.Button = MouseRight
				case 3:
					event.Button = MouseNone // Release (legacy encoding)
				}

				// Determine action from final byte and motion bit
				if button&32 != 0 {
					event.Action = MouseDrag
				} else if b == 'M' {
					event.Action = MousePress
				} else {
					event.Action = MouseRelease
				}
			}

			return event, i + 1
		}

		// Unexpected character
		return MouseEvent{}, 0
	}

	// Incomplete sequence
	return MouseEvent{}, 0
}