vt-input-push-parser 0.11.0

A streaming push parser for the VT/xterm input events
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
use vt_push_parser::event::{CSI, DCS, SS2, SS3, VTEvent};
use vt_push_parser::{VTPushParser, capture};

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PasteEvent {
    Start,
    End,
    Continue,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MouseEvent {
    Button(u8, Modifier),
    ButtonRelease(u8, Modifier),
    Motion(u16, u16),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InputEvent<'a> {
    /// A named key on the keyboard
    Key(keys::Key, Modifier),
    /// An unnamed key representable by a single character, but with modifiers
    /// that are more than just "shift".
    KeyChar(char, Modifier),
    /// A single text-producing character.
    Char(char),
    /// A mouse event.
    Mouse(MouseEvent),
    /// A report from the terminal.
    // Report(InputReport),
    /// A bracketed paste event.
    Paste(PasteEvent, &'a [u8]),
    /// A raw VT CSI event.
    Csi(CSI<'a>),
    /// A raw VT OSC event.
    Osc(&'a [u8]),
    /// A raw VT DCS event.
    Dcs(&'a [u8]),
    /// A raw VT SS2 event.
    Ss2(SS2),
    /// A raw VT SS3 event.
    Ss3(SS3),
}

/// Common input reports.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InputReport {
    // CSI Ps1 ; Ps2 R
    CursorPosition(u16, u16),
    // CSI Pl; Pc; Pp R (DECXCPR)
    CursorPositionPage(u16, u16, u16),
    // CSI Pn ; n or CSI ? Pn ; n
    DeviceStatus(bool, u16),
    // CSI ? Pn1 ; Pn2 ; n or CSI ? Pn1 ; Pn2 ; n
    DeviceStatus2(bool, u16, u16),
    // CSI Ps1; ... Psn (if Ps! is 61-64, identifies VT level, others are bitflags)
    DeviceAttributes1(u8, u32),
    // CSI > Pp ; Pv ; Pc c
    DeviceAttributes2(u16, u16, u8),
    // CSI Ps1 ; Ps2 $ y or CSI ? Ps1 ; Ps2 $ y
    ReportMode(bool, u16, u8),
    // CSI 1 t or CSI 2 t
    ReportWindowState(bool),
    // CSI 3 ; x ; y t
    ReportWindowPosition(u16, u16),
    // CSI 4 ; h ; w t
    ReportWindowSizePixel(u16, u16),
    // CSI 5 ; h ; w t
    ReportTextSizeCharacter(u16, u16),
    // CSI 6 ; h ; w t
    ReportScreenSizeCharacter(u16, u16),
    // OSC Ps1 ; rgb:... BEL
    ReportDynamicColor(u8, u16, u16, u16),
    // ESC I
    FocusIn,
    // ESC O
    FocusOut,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
pub struct Modifier(pub(crate) u8);

bitflags::bitflags! {
    impl Modifier: u8 {
        const SHIFT = 1 << 0;
        const ALT = 1 << 1;
        const CTRL = 1 << 2;

        const KEYPAD = 1 << 3;
        const SUN = 1 << 4;
        const VT52 = 1 << 5;
    }
}

mod keys {
    use super::Modifier;

    macro_rules! e {
        ($depth:literal, $c:literal, ($($mod:ident),*)) => {
            MatchResult::Match {
                length: $depth,
                what: pack_mod($c as _, (Modifier::empty() $( | Modifier::$mod )*).0),
            }
        };
        ($depth:literal, $name:ident, ($($mod:ident),*)) => {
            MatchResult::Match {
                length: $depth,
                what: pack_mod(Key::$name as _, 0x80 | (Modifier::empty() $( | Modifier::$mod )*).0),
            }
        };
    }

    // Byte-packed to 8 bytes
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub(crate) enum MatchResult {
        /// We didn't find a match and we know that at least this many bytes
        /// won't match.
        NoMatch {
            length: u8,
        },
        PendingMatch,
        Match {
            length: u8,
            what: u32,
        },
    }

    #[inline(always)]
    const fn pack(char: char, alt: bool) -> u32 {
        char as u32 | (((if alt { Modifier::ALT.0 as _ } else { 0 }) as u32) << 24)
    }

    #[inline(always)]
    const fn pack_mod(char: u32, modifiers: u8) -> u32 {
        char | (modifiers as u32) << 24
    }

    #[inline(always)]
    fn utf8_1(alt: bool, byte: u8) -> MatchResult {
        MatchResult::Match {
            length: 1 + alt as u8,
            what: pack(byte as char, alt),
        }
    }

    #[inline(always)]
    fn utf8_2(alt: bool, bytes: &[u8]) -> MatchResult {
        if bytes.len() < 2 {
            return MatchResult::PendingMatch;
        }
        // 110xxxxx 10xxxxxx
        let Some(char) =
            char::from_u32((bytes[0] & 0b11111) as u32 | ((bytes[1] & 0b111111) as u32) << 6)
        else {
            return MatchResult::Match {
                length: 2 + alt as u8,
                what: pack('\u{FFFD}', false),
            };
        };
        MatchResult::Match {
            length: 2 + alt as u8,
            what: pack(char, alt),
        }
    }

    #[inline(always)]
    fn utf8_3(alt: bool, bytes: &[u8]) -> MatchResult {
        if bytes.len() < 3 {
            return MatchResult::PendingMatch;
        }
        // 1110xxxx 10xxxxxx 10xxxxxx
        let Some(char) = char::from_u32(
            (((bytes[0] & 0b1111) as u32) << 12)
                | (((bytes[1] & 0b111111) as u32) << 6)
                | ((bytes[2] & 0b111111) as u32),
        ) else {
            return MatchResult::Match {
                length: 3 + alt as u8,
                what: pack('\u{FFFD}', false),
            };
        };
        MatchResult::Match {
            length: 3 + alt as u8,
            what: pack(char, alt),
        }
    }

    #[inline(always)]
    fn utf8_4(alt: bool, bytes: &[u8]) -> MatchResult {
        if bytes.len() < 4 {
            return MatchResult::PendingMatch;
        }
        // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
        let Some(char) = char::from_u32(
            (((bytes[0] & 0b111) as u32) << 18)
                | (((bytes[1] & 0b111111) as u32) << 12)
                | (((bytes[2] & 0b111111) as u32) << 6)
                | ((bytes[3] & 0b111111) as u32),
        ) else {
            return MatchResult::Match {
                length: 4 + alt as u8,
                what: pack('\u{FFFD}', false),
            };
        };
        MatchResult::Match {
            length: 4 + alt as u8,
            what: pack(char, alt),
        }
    }

    #[inline(always)]
    fn invalid_utf8(_: u8) -> MatchResult {
        MatchResult::Match {
            length: 1,
            what: pack('\u{FFFD}', false),
        }
    }

    pub fn find_sequence(bytes: &[u8]) -> MatchResult {
        match find_sequence_nonidle_gen(bytes) {
            MatchResult::NoMatch { length } => {
                if matches!(bytes, [0x1b, 0x1b, ..]) {
                    MatchResult::Match {
                        length: 1,
                        what: pack('\x1b', false),
                    }
                } else {
                    MatchResult::NoMatch { length }
                }
            }
            res => res,
        }
    }

    pub fn find_sequence_idle(bytes: &[u8]) -> MatchResult {
        match find_sequence_idle_gen(bytes) {
            MatchResult::NoMatch { length } => match bytes {
                [0x1b] => MatchResult::Match {
                    length: 1,
                    what: pack('\x1b', false),
                },
                [0x1b, 0x1b] => MatchResult::Match {
                    length: 2,
                    what: pack('\x1b', true),
                },
                [0x1b, 0x1b, ..] => MatchResult::Match {
                    length: 1,
                    what: pack('\x1b', false),
                },
                _ => MatchResult::NoMatch { length },
            },
            res => res,
        }
    }

    include!(concat!(env!("OUT_DIR"), "/keys.rs"));
}

#[derive(Debug, Default)]
enum CaptureState {
    #[default]
    None,
    Paste,
    Mouse,
    MouseHilite,
    MouseDrag,
}

/// A push parser for the VT/xterm input protocol.
///
/// This parser enables parsing of key sequences alongside the normal VT/xterm
/// protocol. In addition, most common input control sequences are automatically
/// decoded.
///
/// Unrecognized sequences are emitted as raw [`VTEvent`]s.
pub struct VTPushParserInput {
    key_buffer: [u8; keys::MAX_SEQUENCE_LEN],
    key_buffer_len: usize,
    data_accumulator: Vec<u8>,

    capture: capture::VTCaptureInternal,
    capture_state: CaptureState,
    parser: VTPushParser,
}

fn handle_vt_event(event: VTEvent<'_>, mut cb: impl FnMut(InputEvent)) {
    println!("VTEvent: {:?}", event);
    match &event {
        VTEvent::Csi(csi) => match (csi.private, csi.final_byte) {
            (None, b'u') => match csi.params.len() {
                1 => {}
                2 => {}
                _ => {}
            },
            (None | Some(b'>'), b'~') => match csi.params.len() {
                2 => {}
                3 => {}
                _ => {}
            },
            _ => {}
        },
        _ => {}
    }

    // // Xterm standard mouse events (three utf-8 or three bytes after)
    // _EV_MOUSE: CSI M
    // // Mouse highlight mode. If the start and end coordinates are the same locations
    // // two bytes of data follow (x, y)
    // _EV_MOUSE_HILITE_CLICK: CSI t
    // // ... otherwise six bytes of data follow (startx, starty, endx, endy, mousex, and mousey)
    // _EV_MOUSE_HILITE_DRAG: CSI T

    cb(InputEvent::Csi(event.csi().unwrap()));
}

fn handle_key_event(what: u32, mut cb: impl FnMut(InputEvent)) {
    if what & 0x80000000 != 0 {
        let key = keys::Key::try_from(what as u8).unwrap();
        cb(InputEvent::Key(key, Modifier(((what >> 24) & !0x80) as u8)));
    } else {
        cb(InputEvent::KeyChar(
            char::from_u32(what & 0xffffff).unwrap(),
            Modifier((what >> 24) as u8),
        ));
    }
}

impl VTPushParserInput {
    pub fn new() -> Self {
        Self {
            key_buffer: [0; keys::MAX_SEQUENCE_LEN],
            key_buffer_len: 0,
            capture: capture::VTCaptureInternal::None,
            capture_state: CaptureState::None,
            parser: VTPushParser::new(),
            data_accumulator: Vec::with_capacity(256),
        }
    }

    pub fn feed_with(&mut self, mut bytes: &[u8], mut cb: impl FnMut(InputEvent)) {
        loop {
            // First, check if we have an active capture.
            if let Some(captured) = self.capture.feed(&mut bytes) {
                self.data_accumulator.extend_from_slice(captured);
                match std::mem::take(&mut self.capture_state) {
                    CaptureState::None => {}
                    CaptureState::Paste => {
                        cb(InputEvent::Paste(PasteEvent::End, &self.data_accumulator));
                        self.data_accumulator.clear();
                    }
                    CaptureState::Mouse => {
                        let s = str::from_utf8(&self.data_accumulator);
                        self.data_accumulator.clear();
                        cb(InputEvent::Mouse(MouseEvent::Button(
                            captured[0],
                            Modifier(captured[1]),
                        )));
                    }
                    CaptureState::MouseHilite => {
                        cb(InputEvent::Mouse(MouseEvent::Button(
                            captured[0],
                            Modifier(captured[1]),
                        )));
                    }
                    CaptureState::MouseDrag => {
                        cb(InputEvent::Mouse(MouseEvent::Button(
                            captured[0],
                            Modifier(captured[1]),
                        )));
                    }
                }
                continue;
            }

            // If no active capture, feed the parser if it's not in ground state, otherwise the key buffer.
            if !self.parser.is_ground() {
                let read = self.parser.feed_with_abortable(bytes, |event: VTEvent| {
                    handle_vt_event(event, &mut cb);
                    false
                });
                bytes = &bytes[read..];
                continue;
            }

            // If the key buffer has some bytes, feed more to it
            if self.key_buffer_len > 0 {
                let to_copy_into = &mut self.key_buffer[self.key_buffer_len
                    ..keys::MAX_SEQUENCE_LEN.min(self.key_buffer_len + bytes.len())];
                to_copy_into.copy_from_slice(&bytes[..to_copy_into.len()]);
                self.key_buffer_len += to_copy_into.len();
                bytes = &bytes[to_copy_into.len()..];

                match keys::find_sequence(&self.key_buffer[..self.key_buffer_len]) {
                    keys::MatchResult::Match { length, what } => {
                        self.key_buffer.rotate_left(length as _);
                        self.key_buffer_len -= length as usize;
                        handle_key_event(what, &mut cb);
                    }
                    keys::MatchResult::NoMatch { length } => {
                        // We don't have a match and we know that at least this many bytes
                        // won't match.
                        self.key_buffer.rotate_left(length as _);
                        // Feed them unconditionally to the parser
                        self.parser.feed_with(
                            &self.key_buffer[keys::MAX_SEQUENCE_LEN - length as usize..],
                            |event: VTEvent<'_>| {
                                handle_vt_event(event, &mut cb);
                            },
                        );
                    }
                    keys::MatchResult::PendingMatch => {
                        // We need more bytes to complete the match, which means we need another
                        // feed call.
                        return;
                    }
                }
            }

            // If we get this far, we're in the ground state for everything...

            if self.key_buffer_len == 0 {
                match keys::find_sequence(bytes) {
                    keys::MatchResult::Match { length, what } => {
                        bytes = &bytes[length as usize..];
                        handle_key_event(what, &mut cb);
                    }
                    keys::MatchResult::NoMatch { length } => {
                        // We don't have a match and we know that at least this many bytes
                        // won't match.
                        self.parser
                            .feed_with(&bytes[..length as usize], |event: VTEvent<'_>| {
                                handle_vt_event(event, &mut cb);
                            });
                        bytes = &bytes[length as usize..];
                    }
                    keys::MatchResult::PendingMatch => {
                        // We need more bytes to complete the match, which means we need another
                        // feed call.
                        return;
                    }
                }
            }
        }
    }
}

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

    #[test]
    fn test_codegen() {
        use keys::{find_sequence, find_sequence_idle};

        macro_rules! m {
            ($bytes:literal, $length:literal) => {
                let seq = find_sequence($bytes);
                assert!(
                    matches!(
                        seq,
                        keys::MatchResult::Match {
                            length: $length,
                            what: _
                        }
                    ),
                    "{:?} => {seq:?}, expected match when not idle",
                    $bytes
                );
                let seq = find_sequence_idle($bytes);
                assert!(
                    matches!(
                        seq,
                        keys::MatchResult::Match {
                            length: $length,
                            what: _
                        }
                    ),
                    "{:?} => {seq:?}, expected match when idle",
                    $bytes
                );
            };
            ($bytes:literal, no) => {
                let seq = find_sequence($bytes);
                assert!(
                    matches!(seq, keys::MatchResult::NoMatch { length: _ }),
                    "{:?} => {seq:?}, expected no match",
                    $bytes
                );
            };
            ($bytes:literal, no, $length:literal) => {
                let seq = find_sequence($bytes);
                assert!(
                    matches!(seq, keys::MatchResult::PendingMatch),
                    "{:?} => {seq:?}, expected pending match when not idle",
                    $bytes
                );
                let seq = find_sequence_idle($bytes);
                assert!(
                    matches!(
                        seq,
                        keys::MatchResult::Match {
                            length: $length,
                            what: _
                        }
                    ),
                    "{:?} => {seq:?}, expected match when idle",
                    $bytes
                );
            };
        }

        // Unambiguous, same matches regardless of more data
        m!(b"\x1b[A", 3);
        m!(b"\x1bA", 2);
        m!(b"\x1bOA", 3);
        m!(b"\x1b\x01", 2);
        m!(b"\x1b\x1b[Z", 4);
        m!(b"\x1b1", 2); // ESC + 1

        // Ambiguous
        m!(b"\x1b", no, 1); // could be ESC or ESC ...
        m!(b"\x1b\x1b", no, 2); // could be ESC ESC or ESC CSI Z, for example
        m!(b"\x1bO", no, 2); // could be ESC O or ESC O A (SS3)
        m!(b"\x1b?", no, 2); // could be ESC ? or ESC ? . (VT52 keypad)

        // Super ambiguous escape chains
        m!(b"\x1b\x1b\x1b", 1); // could be a series of escapes, alt escapes, or whatever. yield one escape to be safe
        m!(b"\x1b\x1b\x1b\x1b", 1); // could be a series of escapes, alt escapes, or whatever. yield one escape to be safe

        // Shorter matches w/more data
        m!(b"\x1b!\x1b", 2); // ESC + ! (ALT + SHIFT + 1)
        m!(b"\x1b\x1b1", 1); // ESC
        m!(b"\x1b1\x1b", 2); // ESC + 1
        m!(b"\x1b1m", 2); // ESC + 1

        // Weak matches
        m!(b"\x1b\x1b[I", 1); // ESC + FocusIn (ESC is a weak match)
        m!(b"\x1b\x1bON", 1); // ESC + SS3 (ESC)
        m!(b"\x1b[", no, 2); // ESC + [ if idle, otherwise wait for more
        m!(b"\x1b\x1b[", no, 1); // ESC if idle, otherwise wait for more

        // No match
        m!(b"\x1b[I", no); // valid CSI
        m!(b"\x1b=", no);
        m!(b"\x1b<", no);
        m!(b"\x1b>", no);

        // Maybe re-visit
        m!(b"\x1bO\x1b", no); // disambiguation must end a string, but we might be able to do a lookahead here
    }

    #[test]
    fn test_find_sequence() {
        let mut bytes = b"\x1ba\x1b[Aa\xf0\x9f\x9b\x9c\x1b[B".as_slice();
        let mut input_parser = VTPushParserInput::new();
        input_parser.feed_with(bytes, |event| {
            println!("Event: {:?}", event);
            // assert_eq!(event, InputEvent::Key(keys::KeyCode::UP, Modifier::empty()));
        });
    }
}