comb-tui 0.2.0

A tiny native terminal-UI engine — surfaces, layers, widgets.
Documentation
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! Input events and the parser that turns raw terminal bytes into them.
//! Handles UTF-8 text, ctrl/alt/shift chords, CSI / kitty key encodings,
//! and SGR mouse reporting (`ESC [ < b ; x ; y M|m`).

#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct KeyMods {
    pub ctrl: bool,
    pub alt: bool,
    pub shift: bool,
}

impl KeyMods {
    pub const NONE: KeyMods = KeyMods {
        ctrl: false,
        alt: false,
        shift: false,
    };
    pub const CTRL: KeyMods = KeyMods {
        ctrl: true,
        alt: false,
        shift: false,
    };
    pub const ALT: KeyMods = KeyMods {
        ctrl: false,
        alt: true,
        shift: false,
    };
    pub const SHIFT: KeyMods = KeyMods {
        ctrl: false,
        alt: false,
        shift: true,
    };
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum KeyCode {
    Char(char),
    Enter,
    Esc,
    Backspace,
    Tab,
    Delete,
    Insert,
    Left,
    Right,
    Up,
    Down,
    Home,
    End,
    PageUp,
    PageDown,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Key {
    pub code: KeyCode,
    pub mods: KeyMods,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum MouseButton {
    Left,
    Middle,
    Right,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum MouseKind {
    Down(MouseButton),
    Up,
    Drag,
    Moved,
    ScrollUp,
    ScrollDown,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Mouse {
    pub kind: MouseKind,
    /// Zero-based column and row on screen.
    pub col: u16,
    pub row: u16,
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Event {
    Key(Key),
    Mouse(Mouse),
    Resize(u16, u16),
    /// Bracketed paste (`\x1b[200~` … `\x1b[201~`).
    Paste(String),
}

fn key(code: KeyCode, mods: KeyMods) -> Event {
    Event::Key(Key { code, mods })
}

/// Parse one event from the front of `buf`, removing the bytes it consumed.
/// Returns `None` only when `buf` is empty or holds an incomplete sequence.
pub fn parse(buf: &mut Vec<u8>) -> Option<Event> {
    if buf.is_empty() {
        return None;
    }

    let b0 = buf[0];
    if b0 == 0x1b {
        return parse_escape(buf);
    }

    // Single-byte keys.
    // In raw mode Enter is `\r`; Ctrl+J / some Shift+Enter fallbacks send `\n`.
    let ev = match b0 {
        b'\r' => Some((key(KeyCode::Enter, KeyMods::NONE), 1)),
        b'\n' => Some((key(KeyCode::Enter, KeyMods::SHIFT), 1)),
        0x7f | 0x08 => Some((key(KeyCode::Backspace, KeyMods::NONE), 1)),
        b'\t' => Some((key(KeyCode::Tab, KeyMods::NONE), 1)),
        0x01..=0x1a => {
            // Ctrl+letter (0x01 == ctrl-a). Tab/Enter handled above.
            let ch = (b0 - 1 + b'a') as char;
            Some((key(KeyCode::Char(ch), KeyMods::CTRL), 1))
        }
        0x1c => Some((key(KeyCode::Char('\\'), KeyMods::CTRL), 1)),
        0x1d => Some((key(KeyCode::Char(']'), KeyMods::CTRL), 1)),
        0x1e => Some((key(KeyCode::Char('^'), KeyMods::CTRL), 1)),
        0x1f => Some((key(KeyCode::Char('_'), KeyMods::CTRL), 1)),
        _ => None,
    };
    if let Some((event, n)) = ev {
        buf.drain(0..n);
        return Some(event);
    }

    // UTF-8 text.
    let len = utf8_len(b0);
    if buf.len() < len {
        return None; // wait for the rest of the codepoint
    }
    let ch = std::str::from_utf8(&buf[0..len])
        .ok()
        .and_then(|s| s.chars().next());
    buf.drain(0..len);
    ch.map(|c| key(KeyCode::Char(c), KeyMods::NONE))
}

fn parse_escape(buf: &mut Vec<u8>) -> Option<Event> {
    // Lone ESC: incomplete. Mouse / CSI sequences often arrive as ESC in one
    // read and `[…` in the next — treating this as Esc would false-trigger
    // interrupt. `Terminal::read_event` flushes a real Esc after a short timeout.
    if buf.len() == 1 {
        return None;
    }

    match buf[1] {
        b'[' => parse_csi(buf),
        b'O' => parse_ss3(buf),
        // ESC + CR == Alt+Enter (common multiline binding).
        b'\r' => {
            buf.drain(0..2);
            Some(key(KeyCode::Enter, KeyMods::ALT))
        }
        // ESC + LF == Alt+newline.
        b'\n' => {
            buf.drain(0..2);
            Some(key(KeyCode::Enter, KeyMods::ALT))
        }
        // ESC + printable == Alt+char.
        c if c >= 0x20 => {
            let len = utf8_len(c);
            if buf.len() < 1 + len {
                return None;
            }
            let ch = std::str::from_utf8(&buf[1..1 + len])
                .ok()
                .and_then(|s| s.chars().next());
            buf.drain(0..1 + len);
            ch.map(|c| key(KeyCode::Char(c), KeyMods::ALT))
        }
        _ => {
            buf.drain(0..1);
            Some(key(KeyCode::Esc, KeyMods::NONE))
        }
    }
}

fn parse_ss3(buf: &mut Vec<u8>) -> Option<Event> {
    if buf.len() < 3 {
        return None;
    }
    let code = match buf[2] {
        b'A' => KeyCode::Up,
        b'B' => KeyCode::Down,
        b'C' => KeyCode::Right,
        b'D' => KeyCode::Left,
        b'H' => KeyCode::Home,
        b'F' => KeyCode::End,
        _ => {
            buf.drain(0..3);
            return None;
        }
    };
    buf.drain(0..3);
    Some(key(code, KeyMods::NONE))
}

fn parse_csi(buf: &mut Vec<u8>) -> Option<Event> {
    // SGR mouse: ESC [ < b ; x ; y (M|m)
    if buf.len() >= 3 && buf[2] == b'<' {
        return parse_sgr_mouse(buf);
    }

    // Find the final byte (0x40..=0x7e) that ends the sequence.
    let mut end = None;
    for (i, &b) in buf.iter().enumerate().skip(2) {
        if (0x40..=0x7e).contains(&b) {
            end = Some(i);
            break;
        }
    }
    let end = end?; // incomplete; wait for more bytes
    let final_byte = buf[end];
    let params = parse_params(&buf[2..end]);

    // Bracketed paste: ESC [ 200 ~ <bytes> ESC [ 201 ~
    // Do not drain the start marker until the end marker is present.
    if final_byte == b'~' && params.first() == Some(&200) {
        return parse_bracketed_paste(buf, end);
    }

    let event = match final_byte {
        b'A' => Some(key(KeyCode::Up, mods_from_csi(&params, 1))),
        b'B' => Some(key(KeyCode::Down, mods_from_csi(&params, 1))),
        b'C' => Some(key(KeyCode::Right, mods_from_csi(&params, 1))),
        b'D' => Some(key(KeyCode::Left, mods_from_csi(&params, 1))),
        b'H' => Some(key(KeyCode::Home, mods_from_csi(&params, 1))),
        b'F' => Some(key(KeyCode::End, mods_from_csi(&params, 1))),
        // Kitty / fixterms: CSI <code> ; <mods[:event]> u
        b'u' => parse_csi_u(&buf[2..end]),
        b'~' => parse_csi_tilde(&params),
        _ => None,
    };

    buf.drain(0..=end);
    event
}

/// Consume `\x1b[200~…\x1b[201~` into [`Event::Paste`]. `start_end` is the
/// index of `~` in the opening CSI.
fn parse_bracketed_paste(buf: &mut Vec<u8>, start_end: usize) -> Option<Event> {
    const END: &[u8] = b"\x1b[201~";
    let content_at = start_end + 1;
    let Some(rel) = find_bytes(&buf[content_at..], END) else {
        return None; // wait for more bytes; leave buffer intact
    };
    let content = &buf[content_at..content_at + rel];
    let paste = match std::str::from_utf8(content) {
        Ok(s) => s.to_string(),
        Err(_) => String::from_utf8_lossy(content).into_owned(),
    };
    buf.drain(0..content_at + rel + END.len());
    Some(Event::Paste(paste))
}

fn find_bytes(hay: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() || hay.len() < needle.len() {
        return None;
    }
    hay.windows(needle.len()).position(|w| w == needle)
}

/// Kitty keyboard protocol key event. Ignores key-release (`*:3`) so letters
/// aren't inserted twice when event types are reported.
fn parse_csi_u(raw: &[u8]) -> Option<Event> {
    let fields = parse_param_fields(raw);
    let code = *fields.first()?.first()?;
    let mods_field = fields.get(1);
    let mods = mods_from_param(mods_field.and_then(|f| f.first()).copied());
    let event_type = mods_field.and_then(|f| f.get(1)).copied().unwrap_or(1);
    // 1 = press, 2 = repeat, 3 = release
    if event_type == 3 {
        return None;
    }
    keycode_from_number(code).map(|c| key(c, mods))
}

/// `CSI … ~` — paging keys, xterm modifyOtherKeys (`27;mods;key~`).
fn parse_csi_tilde(params: &[u32]) -> Option<Event> {
    // xterm modifyOtherKeys: CSI 27 ; <mods> ; <key> ~
    if params.first() == Some(&27) && params.len() >= 3 {
        let mods = mods_from_param(Some(params[1]));
        return keycode_from_number(params[2]).map(|c| key(c, mods));
    }

    let id = *params.first().unwrap_or(&0);
    let mods = mods_from_csi(params, 0);
    let code = match id {
        1 | 7 => KeyCode::Home,
        2 => KeyCode::Insert,
        4 | 8 => KeyCode::End,
        3 => KeyCode::Delete,
        5 => KeyCode::PageUp,
        6 => KeyCode::PageDown,
        13 => KeyCode::Enter, // rare, but some terminals encode Enter this way
        _ => return None,
    };
    Some(key(code, mods))
}

fn keycode_from_number(n: u32) -> Option<KeyCode> {
    match n {
        9 => Some(KeyCode::Tab),
        13 => Some(KeyCode::Enter),
        27 => Some(KeyCode::Esc),
        127 => Some(KeyCode::Backspace),
        // Printable unicode — ASCII, Cyrillic, etc. (kitty sends the codepoint).
        c if (32..0x110000).contains(&c) => char::from_u32(c).map(KeyCode::Char),
        _ => None,
    }
}

/// xterm modifier param: 1 = none; bits of (param-1) are shift/alt/ctrl.
fn mods_from_param(p: Option<u32>) -> KeyMods {
    let m = p.unwrap_or(1).saturating_sub(1);
    KeyMods {
        shift: m & 1 != 0,
        alt: m & 2 != 0,
        ctrl: m & 4 != 0,
    }
}

/// Modifier is usually the second CSI parameter (`CSI 1;2A` = Shift+Up).
/// `mod_idx` is which param holds the base key number when present.
fn mods_from_csi(params: &[u32], _base_idx: usize) -> KeyMods {
    if params.len() >= 2 {
        mods_from_param(Some(params[1]))
    } else {
        KeyMods::NONE
    }
}

fn parse_params(raw: &[u8]) -> Vec<u32> {
    parse_param_fields(raw)
        .into_iter()
        .map(|f| f.into_iter().next().unwrap_or(0))
        .collect()
}

/// Split CSI params on `;`, then each field on `:` (kitty sub-params).
fn parse_param_fields(raw: &[u8]) -> Vec<Vec<u32>> {
    if raw.is_empty() {
        return Vec::new();
    }
    std::str::from_utf8(raw)
        .unwrap_or("")
        .split(';')
        .map(|p| p.split(':').map(|s| s.parse().unwrap_or(0)).collect())
        .collect()
}

fn parse_sgr_mouse(buf: &mut Vec<u8>) -> Option<Event> {
    // Terminated by 'M' (press/motion) or 'm' (release).
    let mut end = None;
    for (i, &b) in buf.iter().enumerate().skip(3) {
        if b == b'M' || b == b'm' {
            end = Some(i);
            break;
        }
    }
    let end = end?;
    let released = buf[end] == b'm';
    let body = std::str::from_utf8(&buf[3..end]).ok()?;
    let mut it = body.split(';');
    let cb: u16 = it.next()?.parse().ok()?;
    let cx: u16 = it.next()?.parse().ok()?;
    let cy: u16 = it.next()?.parse().ok()?;
    buf.drain(0..=end);

    let col = cx.saturating_sub(1);
    let row = cy.saturating_sub(1);

    let kind = if cb & 0x40 != 0 {
        if cb & 0x1 == 0 {
            MouseKind::ScrollUp
        } else {
            MouseKind::ScrollDown
        }
    } else if released {
        MouseKind::Up
    } else if cb & 0x20 != 0 {
        // Motion: a held button drags; no button (bits == 3) is a hover move.
        if cb & 0x3 == 3 {
            MouseKind::Moved
        } else {
            MouseKind::Drag
        }
    } else {
        match cb & 0x3 {
            0 => MouseKind::Down(MouseButton::Left),
            1 => MouseKind::Down(MouseButton::Middle),
            2 => MouseKind::Down(MouseButton::Right),
            _ => MouseKind::Moved,
        }
    };

    Some(Event::Mouse(Mouse { kind, col, row }))
}

fn utf8_len(b: u8) -> usize {
    if b < 0x80 {
        1
    } else if b >> 5 == 0b110 {
        2
    } else if b >> 4 == 0b1110 {
        3
    } else if b >> 3 == 0b11110 {
        4
    } else {
        1
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn plain_char_and_ctrl() {
        let mut b = b"a".to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Char('a'), KeyMods::NONE)));
        assert!(b.is_empty());

        let mut b = vec![0x03]; // ctrl-c
        assert_eq!(parse(&mut b), Some(key(KeyCode::Char('c'), KeyMods::CTRL)));
    }

    #[test]
    fn parses_ctrl_close_bracket() {
        let mut bytes = vec![0x1d];
        assert_eq!(
            parse(&mut bytes),
            Some(key(KeyCode::Char(']'), KeyMods::CTRL))
        );
        assert!(bytes.is_empty());
    }

    #[test]
    fn arrows_and_enter() {
        let mut b = b"\x1b[A".to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Up, KeyMods::NONE)));
        let mut b = b"\r".to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Enter, KeyMods::NONE)));
    }

    #[test]
    fn newline_is_shift_enter() {
        let mut b = b"\n".to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Enter, KeyMods::SHIFT)));
    }

    #[test]
    fn alt_enter() {
        let mut b = b"\x1b\r".to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Enter, KeyMods::ALT)));
    }

    #[test]
    fn shift_enter_kitty_and_xterm() {
        let mut b = b"\x1b[13;2u".to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Enter, KeyMods::SHIFT)));

        let mut b = b"\x1b[27;2;13~".to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Enter, KeyMods::SHIFT)));

        // CSI ~ form with mods on key 13 (seen on some VTE builds).
        let mut b = b"\x1b[13;2~".to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Enter, KeyMods::SHIFT)));

        // Kitty with event-type sub-param must keep the shift bit.
        let mut b = b"\x1b[13;2:1u".to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Enter, KeyMods::SHIFT)));
    }

    #[test]
    fn kitty_release_is_ignored() {
        // press then release for 'd' — only one Char event.
        let mut b = b"\x1b[100;1:1u\x1b[100;1:3u".to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Char('d'), KeyMods::NONE)));
        assert_eq!(parse(&mut b), None);
        assert!(b.is_empty());
    }

    #[test]
    fn kitty_cyrillic_and_utf8() {
        // 'а' U+0430 = 1072
        let mut b = b"\x1b[1072u".to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Char('а'), KeyMods::NONE)));

        let mut b = "б".as_bytes().to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Char('б'), KeyMods::NONE)));
    }

    #[test]
    fn ctrl_enter_and_ctrl_letter_via_modify_other_keys() {
        let mut b = b"\x1b[27;5;13~".to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Enter, KeyMods::CTRL)));

        // modifyOtherKeys level 2: Ctrl+C as CSI rather than 0x03.
        let mut b = b"\x1b[27;5;99~".to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Char('c'), KeyMods::CTRL)));
    }

    #[test]
    fn shift_arrow() {
        let mut b = b"\x1b[1;2A".to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Up, KeyMods::SHIFT)));
    }

    #[test]
    fn sgr_mouse_click_and_wheel() {
        let mut b = b"\x1b[<0;10;5M".to_vec();
        assert_eq!(
            parse(&mut b),
            Some(Event::Mouse(Mouse {
                kind: MouseKind::Down(MouseButton::Left),
                col: 9,
                row: 4,
            }))
        );
        let mut b = b"\x1b[<64;3;3M".to_vec();
        assert_eq!(
            parse(&mut b),
            Some(Event::Mouse(Mouse {
                kind: MouseKind::ScrollUp,
                col: 2,
                row: 2,
            }))
        );
    }

    #[test]
    fn incomplete_waits() {
        let mut b = b"\x1b[".to_vec();
        assert_eq!(parse(&mut b), None);
        assert_eq!(b, b"\x1b[");
    }

    #[test]
    fn lone_esc_waits_for_disambiguation() {
        let mut b = vec![0x1b];
        assert_eq!(parse(&mut b), None);
        assert_eq!(b, vec![0x1b]);
        // Rest of an SGR mouse event — must not have been consumed as Esc.
        b.extend_from_slice(b"[<0;10;5M");
        assert!(matches!(parse(&mut b), Some(Event::Mouse(_))));
    }

    #[test]
    fn utf8_multibyte() {
        let mut b = "→".as_bytes().to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Char('→'), KeyMods::NONE)));
    }

    #[test]
    fn bracketed_paste() {
        let mut b = b"\x1b[200~sk-abc123\x1b[201~".to_vec();
        assert_eq!(parse(&mut b), Some(Event::Paste("sk-abc123".into())));
        assert!(b.is_empty());
    }

    #[test]
    fn insert_and_shift_insert() {
        let mut b = b"\x1b[2~".to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Insert, KeyMods::NONE)));
        let mut b = b"\x1b[2;2~".to_vec();
        assert_eq!(parse(&mut b), Some(key(KeyCode::Insert, KeyMods::SHIFT)));
    }

    #[test]
    fn bracketed_paste_incomplete_waits() {
        let mut b = b"\x1b[200~partial".to_vec();
        assert_eq!(parse(&mut b), None);
        assert_eq!(b, b"\x1b[200~partial");
    }
}