envision 0.15.1

A ratatui framework for collaborative TUI development with headless testing support
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
//! Envision-owned keyboard input types.
//!
//! These types replace the crossterm re-exports that envision previously
//! used for keyboard events. Letter keys are normalized to lowercase;
//! use [`KeyEvent::raw_char`] for the actual terminal character.

use std::ops::{BitAnd, BitOr, BitOrAssign};

/// A keyboard key, normalized.
///
/// For ASCII letters, the `Char` variant always contains the lowercase
/// form regardless of shift or caps lock state. Check
/// [`KeyEvent::modifiers`] for shift state, and [`KeyEvent::raw_char`]
/// for the character the terminal actually sent.
///
/// # Example
///
/// ```rust
/// use envision::input::key::Key;
///
/// // Pattern-match on normalized keys for keybindings
/// let key = Key::Char('q');
/// assert!(matches!(key, Key::Char('q')));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Key {
    /// A character key. Always lowercase for ASCII letters.
    Char(char),
    /// A function key (F1 through F24).
    F(u8),
    /// The backspace key.
    Backspace,
    /// The enter/return key.
    Enter,
    /// The left arrow key.
    Left,
    /// The right arrow key.
    Right,
    /// The up arrow key.
    Up,
    /// The down arrow key.
    Down,
    /// The home key.
    Home,
    /// The end key.
    End,
    /// The page up key.
    PageUp,
    /// The page down key.
    PageDown,
    /// The tab key.
    Tab,
    /// The delete key.
    Delete,
    /// The insert key.
    Insert,
    /// The escape key.
    Esc,
}

/// A keyboard event with normalization and raw character preservation.
///
/// # Two views of the same keypress
///
/// - **`code`**: normalized for keybindings. ASCII letters are always
///   lowercase. Use this for `match` arms in `handle_event`.
/// - **`raw_char`**: the character the terminal actually sent. Preserves
///   case (uppercase for Shift or Caps Lock). Use this for text input.
///
/// # Example
///
/// ```rust
/// use envision::input::key::{Key, KeyEvent, Modifiers};
///
/// // Constructors normalize automatically
/// let event = KeyEvent::char('A');
/// assert_eq!(event.code, Key::Char('a'));        // normalized
/// assert!(event.modifiers.shift());              // shift inferred
/// assert_eq!(event.raw_char, Some('A'));          // original preserved
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyEvent {
    /// The key, normalized. ASCII letters are always lowercase.
    pub code: Key,
    /// Modifier keys held during the event.
    pub modifiers: Modifiers,
    /// Whether this is a press, release, or repeat.
    pub kind: KeyEventKind,
    /// The character the terminal actually sent, if this was a
    /// character key. `None` for non-character keys.
    pub raw_char: Option<char>,
}

impl KeyEvent {
    /// Creates a key press event with no modifiers.
    ///
    /// For `Key::Char` variants, uppercase ASCII letters are normalized
    /// to lowercase with SHIFT added, matching the behavior of
    /// [`KeyEvent::char`] and the crossterm converter. Non-character keys
    /// have `raw_char = None`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::input::key::{Key, KeyEvent};
    ///
    /// let event = KeyEvent::new(Key::Enter);
    /// assert_eq!(event.code, Key::Enter);
    /// assert!(event.modifiers.is_none());
    /// assert!(event.raw_char.is_none());
    ///
    /// // Char keys set raw_char
    /// let event = KeyEvent::new(Key::Char('a'));
    /// assert_eq!(event.code, Key::Char('a'));
    /// assert_eq!(event.raw_char, Some('a'));
    ///
    /// // Uppercase is normalized
    /// let event = KeyEvent::new(Key::Char('G'));
    /// assert_eq!(event.code, Key::Char('g'));
    /// assert!(event.modifiers.shift());
    /// assert_eq!(event.raw_char, Some('G'));
    /// ```
    pub fn new(key: Key) -> Self {
        match key {
            Key::Char(c) if c.is_ascii_uppercase() => Self {
                code: Key::Char(c.to_ascii_lowercase()),
                modifiers: Modifiers::SHIFT,
                kind: KeyEventKind::Press,
                raw_char: Some(c),
            },
            Key::Char(c) => Self {
                code: Key::Char(c),
                modifiers: Modifiers::NONE,
                kind: KeyEventKind::Press,
                raw_char: Some(c),
            },
            _ => Self {
                code: key,
                modifiers: Modifiers::NONE,
                kind: KeyEventKind::Press,
                raw_char: None,
            },
        }
    }

    /// Creates a normalized character key press.
    ///
    /// Uppercase letters are normalized: `char('A')` produces
    /// `key=Char('a')`, `modifiers=SHIFT`, `raw_char=Some('A')`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::input::key::{Key, KeyEvent, Modifiers};
    ///
    /// let lower = KeyEvent::char('a');
    /// assert_eq!(lower.code, Key::Char('a'));
    /// assert!(lower.modifiers.is_none());
    /// assert_eq!(lower.raw_char, Some('a'));
    ///
    /// let upper = KeyEvent::char('A');
    /// assert_eq!(upper.code, Key::Char('a'));
    /// assert!(upper.modifiers.shift());
    /// assert_eq!(upper.raw_char, Some('A'));
    /// ```
    pub fn char(c: char) -> Self {
        if c.is_ascii_uppercase() {
            Self {
                code: Key::Char(c.to_ascii_lowercase()),
                modifiers: Modifiers::SHIFT,
                kind: KeyEventKind::Press,
                raw_char: Some(c),
            }
        } else {
            Self {
                code: Key::Char(c),
                modifiers: Modifiers::NONE,
                kind: KeyEventKind::Press,
                raw_char: Some(c),
            }
        }
    }

    /// Creates a Ctrl+character key press.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::input::key::{Key, KeyEvent, Modifiers};
    ///
    /// let event = KeyEvent::ctrl('c');
    /// assert_eq!(event.code, Key::Char('c'));
    /// assert!(event.modifiers.ctrl());
    /// ```
    pub fn ctrl(c: char) -> Self {
        Self {
            code: Key::Char(c.to_ascii_lowercase()),
            modifiers: Modifiers::CONTROL,
            kind: KeyEventKind::Press,
            raw_char: Some(c),
        }
    }

    /// Returns true if this is a press event.
    pub fn is_press(&self) -> bool {
        self.kind == KeyEventKind::Press
    }

    /// Returns true if this is a release event.
    pub fn is_release(&self) -> bool {
        self.kind == KeyEventKind::Release
    }
}

/// The kind of key event.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum KeyEventKind {
    /// A key was pressed.
    Press,
    /// A key was released (not supported by all terminals).
    Release,
    /// A key is being held and is repeating.
    Repeat,
}

/// Modifier keys held during an input event.
///
/// # Example
///
/// ```rust
/// use envision::input::key::Modifiers;
///
/// let mods = Modifiers::CONTROL | Modifiers::SHIFT;
/// assert!(mods.ctrl());
/// assert!(mods.shift());
/// assert!(!mods.alt());
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Modifiers(u8);

impl Modifiers {
    /// No modifier keys held.
    pub const NONE: Self = Self(0);
    /// Shift key held.
    pub const SHIFT: Self = Self(1 << 0);
    /// Control key held.
    pub const CONTROL: Self = Self(1 << 1);
    /// Alt/Option key held.
    pub const ALT: Self = Self(1 << 2);
    /// Super/Cmd/Win key held.
    pub const SUPER: Self = Self(1 << 3);

    /// Returns true if the shift key is held.
    pub fn shift(self) -> bool {
        self.0 & Self::SHIFT.0 != 0
    }

    /// Returns true if the control key is held.
    pub fn ctrl(self) -> bool {
        self.0 & Self::CONTROL.0 != 0
    }

    /// Returns true if the alt/option key is held.
    pub fn alt(self) -> bool {
        self.0 & Self::ALT.0 != 0
    }

    /// Returns true if the super/cmd/win key is held.
    pub fn super_key(self) -> bool {
        self.0 & Self::SUPER.0 != 0
    }

    /// Returns true if no modifier keys are held.
    pub fn is_none(self) -> bool {
        self.0 == 0
    }
}

impl BitOr for Modifiers {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
    }
}

impl BitOrAssign for Modifiers {
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 |= rhs.0;
    }
}

impl BitAnd for Modifiers {
    type Output = Self;
    fn bitand(self, rhs: Self) -> Self {
        Self(self.0 & rhs.0)
    }
}

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

    #[test]
    fn test_key_equality() {
        assert_eq!(Key::Char('a'), Key::Char('a'));
        assert_ne!(Key::Char('a'), Key::Char('b'));
        assert_ne!(Key::Char('a'), Key::Enter);
        assert_eq!(Key::F(5), Key::F(5));
        assert_ne!(Key::F(5), Key::F(6));
    }

    #[test]
    fn test_key_event_new_non_char() {
        let event = KeyEvent::new(Key::Enter);
        assert_eq!(event.code, Key::Enter);
        assert!(event.modifiers.is_none());
        assert_eq!(event.kind, KeyEventKind::Press);
        assert!(event.raw_char.is_none());
    }

    #[test]
    fn test_key_event_new_lowercase_char() {
        let event = KeyEvent::new(Key::Char('a'));
        assert_eq!(event.code, Key::Char('a'));
        assert!(event.modifiers.is_none());
        assert_eq!(event.raw_char, Some('a'));
    }

    #[test]
    fn test_key_event_new_uppercase_normalizes() {
        let event = KeyEvent::new(Key::Char('G'));
        assert_eq!(event.code, Key::Char('g'));
        assert!(event.modifiers.shift());
        assert_eq!(event.raw_char, Some('G'));
    }

    #[test]
    fn test_key_event_new_non_letter_char() {
        let event = KeyEvent::new(Key::Char('!'));
        assert_eq!(event.code, Key::Char('!'));
        assert!(event.modifiers.is_none());
        assert_eq!(event.raw_char, Some('!'));
    }

    #[test]
    fn test_key_event_char_lowercase() {
        let event = KeyEvent::char('a');
        assert_eq!(event.code, Key::Char('a'));
        assert!(event.modifiers.is_none());
        assert_eq!(event.raw_char, Some('a'));
    }

    #[test]
    fn test_key_event_char_uppercase_normalizes() {
        let event = KeyEvent::char('A');
        assert_eq!(event.code, Key::Char('a'));
        assert!(event.modifiers.shift());
        assert_eq!(event.raw_char, Some('A'));
    }

    #[test]
    fn test_key_event_ctrl() {
        let event = KeyEvent::ctrl('c');
        assert_eq!(event.code, Key::Char('c'));
        assert!(event.modifiers.ctrl());
        assert!(!event.modifiers.shift());
        assert_eq!(event.raw_char, Some('c'));
    }

    #[test]
    fn test_key_event_is_press_release() {
        let press = KeyEvent::new(Key::Enter);
        assert!(press.is_press());
        assert!(!press.is_release());

        let release = KeyEvent {
            kind: KeyEventKind::Release,
            ..KeyEvent::new(Key::Enter)
        };
        assert!(!release.is_press());
        assert!(release.is_release());
    }

    #[test]
    fn test_modifiers_default() {
        let m = Modifiers::default();
        assert!(m.is_none());
        assert!(!m.shift());
        assert!(!m.ctrl());
        assert!(!m.alt());
        assert!(!m.super_key());
    }

    #[test]
    fn test_modifiers_individual() {
        assert!(Modifiers::SHIFT.shift());
        assert!(!Modifiers::SHIFT.ctrl());
        assert!(Modifiers::CONTROL.ctrl());
        assert!(!Modifiers::CONTROL.shift());
        assert!(Modifiers::ALT.alt());
        assert!(Modifiers::SUPER.super_key());
    }

    #[test]
    fn test_modifiers_bitor() {
        let mods = Modifiers::CONTROL | Modifiers::SHIFT;
        assert!(mods.ctrl());
        assert!(mods.shift());
        assert!(!mods.alt());
    }

    #[test]
    fn test_modifiers_bitor_assign() {
        let mut mods = Modifiers::NONE;
        mods |= Modifiers::ALT;
        assert!(mods.alt());
        assert!(!mods.ctrl());
    }

    #[test]
    fn test_modifiers_bitand() {
        let mods = Modifiers::CONTROL | Modifiers::SHIFT;
        let masked = mods & Modifiers::CONTROL;
        assert!(masked.ctrl());
        assert!(!masked.shift());
    }

    #[test]
    fn test_key_event_kind_equality() {
        assert_eq!(KeyEventKind::Press, KeyEventKind::Press);
        assert_ne!(KeyEventKind::Press, KeyEventKind::Release);
    }
}