Skip to main content

hjkl_keymap/
key.rs

1//! Backend-agnostic key event and modifier types.
2
3use bitflags::bitflags;
4
5/// A single key press, backend-agnostic.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7pub struct KeyEvent {
8    pub code: KeyCode,
9    pub modifiers: KeyModifiers,
10}
11
12impl KeyEvent {
13    pub fn new(code: KeyCode, modifiers: KeyModifiers) -> Self {
14        Self { code, modifiers }
15    }
16
17    /// Convenience: plain character with no modifiers.
18    pub fn char(c: char) -> Self {
19        Self::new(KeyCode::Char(c), KeyModifiers::NONE)
20    }
21
22    /// Convenience: character with CTRL modifier.
23    pub fn ctrl(c: char) -> Self {
24        Self::new(KeyCode::Char(c), KeyModifiers::CTRL)
25    }
26}
27
28/// The logical key that was pressed, independent of modifiers.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum KeyCode {
31    Char(char),
32    Enter,
33    Esc,
34    Tab,
35    Backspace,
36    Delete,
37    Insert,
38    Up,
39    Down,
40    Left,
41    Right,
42    Home,
43    End,
44    PageUp,
45    PageDown,
46    F(u8),
47}
48
49bitflags! {
50    /// Modifier keys held during a key press.
51    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52    pub struct KeyModifiers: u8 {
53        const NONE  = 0;
54        const SHIFT = 1 << 0;
55        const CTRL  = 1 << 1;
56        const ALT   = 1 << 2;
57    }
58}