tastty-core 0.1.0

Sans-IO core of the tastty terminal session library: VT parser, screen buffer, and byte encoders.
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
//! Keyboard and mouse event types consumed by the encoders.

/// Key code representing a keyboard key.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub enum KeyCode {
    /// Unicode character key.
    Char(char),
    /// Enter/Return.
    Enter,
    /// Backspace.
    Backspace,
    /// Tab.
    Tab,
    /// Shift+Tab.
    BackTab,
    /// Escape.
    Esc,
    /// Arrow up.
    Up,
    /// Arrow down.
    Down,
    /// Arrow right.
    Right,
    /// Arrow left.
    Left,
    /// Home.
    Home,
    /// End.
    End,
    /// Insert.
    Insert,
    /// Delete.
    Delete,
    /// Page up.
    PageUp,
    /// Page down.
    PageDown,
    /// Function key number, such as `F(1)`.
    F(u8),
    /// Caps Lock.
    CapsLock,
    /// Scroll Lock.
    ScrollLock,
    /// Num Lock.
    NumLock,
    /// Print Screen.
    PrintScreen,
    /// Pause/Break.
    Pause,
    /// Menu/Application key.
    Menu,
    /// Keypad begin/center key.
    KeypadBegin,
    /// Physical modifier key.
    Modifier(ModifierKeyCode),
    /// Media key.
    Media(MediaKeyCode),
}

/// Which modifier key was pressed (left/right variants).
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub enum ModifierKeyCode {
    /// Left Shift.
    LeftShift,
    /// Left Control.
    LeftControl,
    /// Left Alt.
    LeftAlt,
    /// Left Super/Windows/Command key.
    LeftSuper,
    /// Left Hyper.
    LeftHyper,
    /// Left Meta.
    LeftMeta,
    /// Right Shift.
    RightShift,
    /// Right Control.
    RightControl,
    /// Right Alt.
    RightAlt,
    /// Right Super/Windows/Command key.
    RightSuper,
    /// Right Hyper.
    RightHyper,
    /// Right Meta.
    RightMeta,
    /// ISO level 3 shift.
    IsoLevel3Shift,
    /// ISO level 5 shift.
    IsoLevel5Shift,
}

/// Media key code.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub enum MediaKeyCode {
    /// Play.
    Play,
    /// Pause.
    Pause,
    /// Toggle play/pause.
    PlayPause,
    /// Reverse playback.
    Reverse,
    /// Stop playback.
    Stop,
    /// Fast forward.
    FastForward,
    /// Rewind.
    Rewind,
    /// Next track.
    TrackNext,
    /// Previous track.
    TrackPrevious,
    /// Record.
    Record,
    /// Lower volume.
    LowerVolume,
    /// Raise volume.
    RaiseVolume,
    /// Mute volume.
    MuteVolume,
}

bitflags::bitflags! {
    /// Key modifier flags.
    #[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash)]
    pub struct KeyModifiers: u8 {
        /// No modifiers.
        const NONE    = 0b0000_0000;
        /// Shift modifier.
        const SHIFT   = 0b0000_0001;
        /// Alt modifier.
        const ALT     = 0b0000_0010;
        /// Control modifier.
        const CONTROL = 0b0000_0100;
        /// Super/Windows/Command modifier.
        const SUPER   = 0b0000_1000;
        /// Hyper modifier.
        const HYPER   = 0b0001_0000;
        /// Meta modifier.
        const META    = 0b0010_0000;
    }
}

/// The kind of key event (press, repeat, release).
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub enum KeyEventKind {
    /// Key press.
    #[default]
    Press,
    /// Auto-repeat key press.
    Repeat,
    /// Key release.
    Release,
}

bitflags::bitflags! {
    /// Additional key event state.
    #[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash)]
    pub struct KeyEventState: u8 {
        /// Caps Lock was active.
        const CAPS_LOCK = 0b0000_0001;
        /// Num Lock was active.
        const NUM_LOCK  = 0b0000_0010;
        /// The key came from the keypad.
        const KEYPAD    = 0b0000_0100;
    }
}

/// A keyboard event.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub struct KeyEvent {
    /// Logical key code.
    pub code: KeyCode,
    /// Active modifiers.
    pub modifiers: KeyModifiers,
    /// Press/repeat/release kind.
    pub kind: KeyEventKind,
    /// Additional key state.
    pub state: KeyEventState,
    /// The key that would have been produced without Shift (or other layout
    /// transforms). For example, if the user presses Shift+1 producing '!',
    /// this field would hold '1'. When `None`, the encoder infers the
    /// unshifted codepoint from the key code using ASCII heuristics.
    pub unshifted_codepoint: Option<char>,
    /// Modifiers that were consumed by the input system to produce the
    /// reported key code. For example, if Shift+a produces 'A', the SHIFT
    /// modifier was consumed. Consumed modifiers are excluded from the
    /// modifier parameter in the [Kitty keyboard protocol][kitty-kbd].
    ///
    /// [kitty-kbd]: https://sw.kovidgoyal.net/kitty/keyboard-protocol/
    pub consumed_modifiers: KeyModifiers,
}

impl KeyEvent {
    /// Create a key press event with no extra state.
    pub fn new(code: KeyCode, modifiers: KeyModifiers) -> Self {
        Self {
            code,
            modifiers,
            kind: KeyEventKind::Press,
            state: KeyEventState::empty(),
            unshifted_codepoint: None,
            consumed_modifiers: KeyModifiers::empty(),
        }
    }

    /// Set the key event kind.
    pub fn with_kind(mut self, kind: KeyEventKind) -> Self {
        self.kind = kind;
        self
    }

    /// Set additional key event state.
    pub fn with_state(mut self, state: KeyEventState) -> Self {
        self.state = state;
        self
    }

    /// Set the unshifted codepoint used by [Kitty keyboard][kitty-kbd] encoding.
    ///
    /// [kitty-kbd]: https://sw.kovidgoyal.net/kitty/keyboard-protocol/
    pub fn with_unshifted_codepoint(mut self, codepoint: char) -> Self {
        self.unshifted_codepoint = Some(codepoint);
        self
    }

    /// Set modifiers consumed while producing the reported key code.
    pub fn with_consumed_modifiers(mut self, modifiers: KeyModifiers) -> Self {
        self.consumed_modifiers = modifiers;
        self
    }
}

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

/// Mouse event kind.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum MouseEventKind {
    /// Button press.
    Down(MouseButton),
    /// Button release.
    Up(MouseButton),
    /// Button drag.
    Drag(MouseButton),
    /// Mouse moved without a button press.
    Moved,
    /// Vertical wheel up.
    ScrollUp,
    /// Vertical wheel down.
    ScrollDown,
    /// Horizontal wheel left.
    ScrollLeft,
    /// Horizontal wheel right.
    ScrollRight,
}

/// A mouse event.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct MouseEvent {
    /// Mouse event kind.
    pub kind: MouseEventKind,
    /// Zero-based terminal row.
    pub row: u16,
    /// Zero-based terminal column.
    pub col: u16,
    /// Active keyboard modifiers.
    pub modifiers: KeyModifiers,
}

impl MouseEvent {
    /// Build a mouse event at a zero-based `(row, col)` terminal cell.
    ///
    /// The parameter order matches the workspace row-then-column
    /// addressing convention used by [`Position`](crate::Position) and
    /// every other coordinate type in the public API.
    #[must_use]
    pub const fn new(kind: MouseEventKind, row: u16, col: u16, modifiers: KeyModifiers) -> Self {
        Self {
            kind,
            row,
            col,
            modifiers,
        }
    }
}

#[cfg(feature = "crossterm")]
mod crossterm_conv {
    use super::*;

    impl From<crossterm::event::KeyCode> for KeyCode {
        fn from(code: crossterm::event::KeyCode) -> Self {
            use crossterm::event::KeyCode as CK;
            match code {
                CK::Char(c) => KeyCode::Char(c),
                CK::Enter => KeyCode::Enter,
                CK::Backspace => KeyCode::Backspace,
                CK::Tab => KeyCode::Tab,
                CK::BackTab => KeyCode::BackTab,
                CK::Esc => KeyCode::Esc,
                CK::Up => KeyCode::Up,
                CK::Down => KeyCode::Down,
                CK::Right => KeyCode::Right,
                CK::Left => KeyCode::Left,
                CK::Home => KeyCode::Home,
                CK::End => KeyCode::End,
                CK::Insert => KeyCode::Insert,
                CK::Delete => KeyCode::Delete,
                CK::PageUp => KeyCode::PageUp,
                CK::PageDown => KeyCode::PageDown,
                CK::F(n) => KeyCode::F(n),
                CK::CapsLock => KeyCode::CapsLock,
                CK::ScrollLock => KeyCode::ScrollLock,
                CK::NumLock => KeyCode::NumLock,
                CK::PrintScreen => KeyCode::PrintScreen,
                CK::Pause => KeyCode::Pause,
                CK::Menu => KeyCode::Menu,
                CK::KeypadBegin => KeyCode::KeypadBegin,
                CK::Modifier(m) => KeyCode::Modifier(m.into()),
                CK::Media(m) => KeyCode::Media(m.into()),
                CK::Null => KeyCode::Char('\0'),
            }
        }
    }

    impl From<crossterm::event::ModifierKeyCode> for ModifierKeyCode {
        fn from(m: crossterm::event::ModifierKeyCode) -> Self {
            use crossterm::event::ModifierKeyCode as CM;
            match m {
                CM::LeftShift => ModifierKeyCode::LeftShift,
                CM::LeftControl => ModifierKeyCode::LeftControl,
                CM::LeftAlt => ModifierKeyCode::LeftAlt,
                CM::LeftSuper => ModifierKeyCode::LeftSuper,
                CM::LeftHyper => ModifierKeyCode::LeftHyper,
                CM::LeftMeta => ModifierKeyCode::LeftMeta,
                CM::RightShift => ModifierKeyCode::RightShift,
                CM::RightControl => ModifierKeyCode::RightControl,
                CM::RightAlt => ModifierKeyCode::RightAlt,
                CM::RightSuper => ModifierKeyCode::RightSuper,
                CM::RightHyper => ModifierKeyCode::RightHyper,
                CM::RightMeta => ModifierKeyCode::RightMeta,
                CM::IsoLevel3Shift => ModifierKeyCode::IsoLevel3Shift,
                CM::IsoLevel5Shift => ModifierKeyCode::IsoLevel5Shift,
            }
        }
    }

    impl From<crossterm::event::MediaKeyCode> for MediaKeyCode {
        fn from(m: crossterm::event::MediaKeyCode) -> Self {
            use crossterm::event::MediaKeyCode as CM;
            match m {
                CM::Play => MediaKeyCode::Play,
                CM::Pause => MediaKeyCode::Pause,
                CM::PlayPause => MediaKeyCode::PlayPause,
                CM::Reverse => MediaKeyCode::Reverse,
                CM::Stop => MediaKeyCode::Stop,
                CM::FastForward => MediaKeyCode::FastForward,
                CM::Rewind => MediaKeyCode::Rewind,
                CM::TrackNext => MediaKeyCode::TrackNext,
                CM::TrackPrevious => MediaKeyCode::TrackPrevious,
                CM::Record => MediaKeyCode::Record,
                CM::LowerVolume => MediaKeyCode::LowerVolume,
                CM::RaiseVolume => MediaKeyCode::RaiseVolume,
                CM::MuteVolume => MediaKeyCode::MuteVolume,
            }
        }
    }

    impl From<crossterm::event::KeyModifiers> for KeyModifiers {
        fn from(m: crossterm::event::KeyModifiers) -> Self {
            let mut out = KeyModifiers::empty();
            if m.contains(crossterm::event::KeyModifiers::SHIFT) {
                out |= KeyModifiers::SHIFT;
            }
            if m.contains(crossterm::event::KeyModifiers::ALT) {
                out |= KeyModifiers::ALT;
            }
            if m.contains(crossterm::event::KeyModifiers::CONTROL) {
                out |= KeyModifiers::CONTROL;
            }
            if m.contains(crossterm::event::KeyModifiers::SUPER) {
                out |= KeyModifiers::SUPER;
            }
            if m.contains(crossterm::event::KeyModifiers::HYPER) {
                out |= KeyModifiers::HYPER;
            }
            if m.contains(crossterm::event::KeyModifiers::META) {
                out |= KeyModifiers::META;
            }
            out
        }
    }

    impl From<crossterm::event::KeyEventKind> for KeyEventKind {
        fn from(k: crossterm::event::KeyEventKind) -> Self {
            match k {
                crossterm::event::KeyEventKind::Press => KeyEventKind::Press,
                crossterm::event::KeyEventKind::Repeat => KeyEventKind::Repeat,
                crossterm::event::KeyEventKind::Release => KeyEventKind::Release,
            }
        }
    }

    impl From<crossterm::event::KeyEventState> for KeyEventState {
        fn from(s: crossterm::event::KeyEventState) -> Self {
            let mut out = KeyEventState::empty();
            if s.contains(crossterm::event::KeyEventState::CAPS_LOCK) {
                out |= KeyEventState::CAPS_LOCK;
            }
            if s.contains(crossterm::event::KeyEventState::NUM_LOCK) {
                out |= KeyEventState::NUM_LOCK;
            }
            if s.contains(crossterm::event::KeyEventState::KEYPAD) {
                out |= KeyEventState::KEYPAD;
            }
            out
        }
    }

    /// US-QWERTY reverse map from shifted ASCII character to the key that
    /// would produce it with Shift released. Used only when crossterm
    /// delivers a `Char` event with `SHIFT` set; non-US layouts will
    /// produce imprecise (but not broken) Kitty keyboard CSI-u encodings.
    fn us_unshift(c: char) -> Option<char> {
        Some(match c {
            '!' => '1',
            '@' => '2',
            '#' => '3',
            '$' => '4',
            '%' => '5',
            '^' => '6',
            '&' => '7',
            '*' => '8',
            '(' => '9',
            ')' => '0',
            '_' => '-',
            '+' => '=',
            '~' => '`',
            '{' => '[',
            '}' => ']',
            '|' => '\\',
            ':' => ';',
            '"' => '\'',
            '<' => ',',
            '>' => '.',
            '?' => '/',
            'A'..='Z' => (c as u8 - b'A' + b'a') as char,
            _ => return None,
        })
    }

    impl From<crossterm::event::KeyEvent> for KeyEvent {
        fn from(e: crossterm::event::KeyEvent) -> Self {
            let modifiers: KeyModifiers = e.modifiers.into();
            let unshifted_codepoint = match e.code {
                crossterm::event::KeyCode::Char(c) if modifiers.contains(KeyModifiers::SHIFT) => {
                    us_unshift(c)
                }
                _ => None,
            };
            Self {
                code: e.code.into(),
                modifiers,
                kind: e.kind.into(),
                state: e.state.into(),
                unshifted_codepoint,
                consumed_modifiers: KeyModifiers::empty(),
            }
        }
    }

    impl From<&crossterm::event::KeyEvent> for KeyEvent {
        fn from(e: &crossterm::event::KeyEvent) -> Self {
            (*e).into()
        }
    }

    impl From<crossterm::event::MouseButton> for MouseButton {
        fn from(b: crossterm::event::MouseButton) -> Self {
            match b {
                crossterm::event::MouseButton::Left => MouseButton::Left,
                crossterm::event::MouseButton::Middle => MouseButton::Middle,
                crossterm::event::MouseButton::Right => MouseButton::Right,
            }
        }
    }

    impl From<crossterm::event::MouseEventKind> for MouseEventKind {
        fn from(k: crossterm::event::MouseEventKind) -> Self {
            use crossterm::event::MouseEventKind as CK;
            match k {
                CK::Down(b) => MouseEventKind::Down(b.into()),
                CK::Up(b) => MouseEventKind::Up(b.into()),
                CK::Drag(b) => MouseEventKind::Drag(b.into()),
                CK::Moved => MouseEventKind::Moved,
                CK::ScrollUp => MouseEventKind::ScrollUp,
                CK::ScrollDown => MouseEventKind::ScrollDown,
                CK::ScrollLeft => MouseEventKind::ScrollLeft,
                CK::ScrollRight => MouseEventKind::ScrollRight,
            }
        }
    }

    impl From<crossterm::event::MouseEvent> for MouseEvent {
        fn from(e: crossterm::event::MouseEvent) -> Self {
            Self {
                kind: e.kind.into(),
                row: e.row,
                col: e.column,
                modifiers: e.modifiers.into(),
            }
        }
    }

    impl From<&crossterm::event::MouseEvent> for MouseEvent {
        fn from(e: &crossterm::event::MouseEvent) -> Self {
            (*e).into()
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use crossterm::event::{
            KeyCode as CK, KeyEvent as CKE, KeyEventKind as CKK, KeyEventState as CKS,
            KeyModifiers as CKM,
        };

        fn ct_key(code: CK, modifiers: CKM) -> CKE {
            CKE {
                code,
                modifiers,
                kind: CKK::Press,
                state: CKS::empty(),
            }
        }

        #[test]
        fn from_crossterm_shift_digit_recovers_unshifted() {
            let key: KeyEvent = ct_key(CK::Char('!'), CKM::SHIFT).into();
            assert_eq!(key.code, KeyCode::Char('!'));
            assert_eq!(key.unshifted_codepoint, Some('1'));
            assert_eq!(key.consumed_modifiers, KeyModifiers::empty());
        }

        #[test]
        fn from_crossterm_shift_punctuation_recovers_unshifted() {
            let key: KeyEvent = ct_key(CK::Char(':'), CKM::SHIFT).into();
            assert_eq!(key.unshifted_codepoint, Some(';'));
        }

        #[test]
        fn from_crossterm_shift_letter_recovers_lowercase() {
            let key: KeyEvent = ct_key(CK::Char('A'), CKM::SHIFT).into();
            assert_eq!(key.unshifted_codepoint, Some('a'));
        }

        #[test]
        fn from_crossterm_no_shift_leaves_unshifted_none() {
            let key: KeyEvent = ct_key(CK::Char('!'), CKM::empty()).into();
            assert_eq!(key.unshifted_codepoint, None);
        }

        #[test]
        fn from_crossterm_shift_unknown_char_leaves_unshifted_none() {
            let key: KeyEvent = ct_key(CK::Char('é'), CKM::SHIFT).into();
            assert_eq!(key.unshifted_codepoint, None);
        }

        #[test]
        fn from_crossterm_non_char_leaves_unshifted_none() {
            let key: KeyEvent = ct_key(CK::F(5), CKM::SHIFT).into();
            assert_eq!(key.unshifted_codepoint, None);
        }
    }
}

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

    #[test]
    fn new_takes_kind_then_row_then_col_then_modifiers() {
        let ev = MouseEvent::new(
            MouseEventKind::Down(MouseButton::Left),
            7,
            3,
            KeyModifiers::SHIFT,
        );
        assert_eq!(ev.kind, MouseEventKind::Down(MouseButton::Left));
        assert_eq!(ev.row, 7);
        assert_eq!(ev.col, 3);
        assert_eq!(ev.modifiers, KeyModifiers::SHIFT);
    }
}