1
use std::fmt;
2
use std::str::FromStr;
3

            
4
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
5

            
6
/// One key press with its modifiers, as written in a keymap file: `C-x`, `M-x`,
7
/// `S-Tab`, `Enter`, `q`, `N`.
8
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9
pub struct Chord {
10
    pub code: KeyCode,
11
    pub modifiers: KeyModifiers,
12
}
13

            
14
/// `;` separates entries and `=` the action, so they are written by name.
15
const NAMED: [(&str, KeyCode); 17] = [
16
    ("Enter", KeyCode::Enter),
17
    ("Esc", KeyCode::Esc),
18
    ("Tab", KeyCode::Tab),
19
    ("Backspace", KeyCode::Backspace),
20
    ("Delete", KeyCode::Delete),
21
    ("Insert", KeyCode::Insert),
22
    ("Up", KeyCode::Up),
23
    ("Down", KeyCode::Down),
24
    ("Left", KeyCode::Left),
25
    ("Right", KeyCode::Right),
26
    ("Home", KeyCode::Home),
27
    ("End", KeyCode::End),
28
    ("PageUp", KeyCode::PageUp),
29
    ("PageDown", KeyCode::PageDown),
30
    ("Space", KeyCode::Char(' ')),
31
    ("Semicolon", KeyCode::Char(';')),
32
    ("Equals", KeyCode::Char('=')),
33
];
34

            
35
const MODIFIERS: [(char, KeyModifiers); 3] = [
36
    ('C', KeyModifiers::CONTROL),
37
    ('M', KeyModifiers::ALT),
38
    ('S', KeyModifiers::SHIFT),
39
];
40

            
41
impl Chord {
42
    /// A character typed with no modifier: text, unless a binding claims it.
43
    #[must_use]
44
1999768
    pub fn is_printable(self) -> bool {
45
1999768
        matches!(self.code, KeyCode::Char(c) if !c.is_control()) && self.modifiers.is_empty()
46
1999768
    }
47

            
48
    /// The chord of a key event: the case of a character carries Shift (a Ctrl
49
    /// letter is always lower case), and BackTab is Shift-Tab.
50
    #[must_use]
51
9641
    pub fn from_event(event: KeyEvent) -> Chord {
52
9641
        match event.code {
53
37
            KeyCode::BackTab => Chord {
54
37
                code: KeyCode::Tab,
55
37
                modifiers: event.modifiers | KeyModifiers::SHIFT,
56
37
            },
57
            KeyCode::Char(c) => Chord {
58
5845
                code: KeyCode::Char(match event.modifiers.contains(KeyModifiers::CONTROL) {
59
363
                    true => c.to_ascii_lowercase(),
60
5482
                    false => c,
61
                }),
62
5845
                modifiers: event.modifiers - KeyModifiers::SHIFT,
63
            },
64
3759
            code => Chord {
65
3759
                code,
66
3759
                modifiers: event.modifiers,
67
3759
            },
68
        }
69
9641
    }
70
}
71

            
72
/// The modifier of a leading `C-`, `M-` or `S-` that is followed by a key.
73
5105095
fn prefix_modifier(text: &str) -> Option<KeyModifiers> {
74
5105095
    let mut chars = text.chars();
75
5105095
    let (letter, dash) = (chars.next()?, chars.next()?);
76
3674024
    if dash != '-' || chars.as_str().is_empty() {
77
2786001
        return None;
78
888023
    }
79
888023
    MODIFIERS
80
888023
        .iter()
81
1549002
        .find(|(l, _)| *l == letter)
82
888022
        .map(|(_, flag)| *flag)
83
5105095
}
84

            
85
4217073
fn parse_key(word: &str) -> Result<KeyCode, String> {
86
49194466
    if let Some((_, code)) = NAMED.iter().find(|(name, _)| *name == word) {
87
2326257
        return Ok(*code);
88
1890816
    }
89
1890816
    if let Some(number) = word.strip_prefix('F').and_then(|n| n.parse::<u8>().ok())
90
234230
        && (1..=12).contains(&number)
91
    {
92
234228
        return Ok(KeyCode::F(number));
93
1656588
    }
94
1656588
    let mut chars = word.chars();
95
1656588
    match (chars.next(), chars.next()) {
96
1431070
        (Some(c), None) => Ok(KeyCode::Char(c)),
97
225518
        _ => Err(format!("unknown key `{word}`")),
98
    }
99
4217073
}
100

            
101
impl FromStr for Chord {
102
    type Err = String;
103

            
104
4217073
    fn from_str(text: &str) -> Result<Chord, String> {
105
4217073
        let mut rest = text;
106
4217073
        let mut modifiers = KeyModifiers::NONE;
107
5105095
        while let Some(flag) = prefix_modifier(rest) {
108
888022
            modifiers |= flag;
109
888022
            rest = &rest[2..];
110
        }
111
4217073
        let code = parse_key(rest)?;
112
3991555
        if matches!(code, KeyCode::Char(_)) && modifiers.contains(KeyModifiers::SHIFT) {
113
3
            return Err(format!(
114
3
                "`{text}`: write the shifted character itself, not `S-`"
115
3
            ));
116
3991552
        }
117
3991552
        if matches!(code, KeyCode::Char(c) if c.is_ascii_uppercase())
118
41940
            && modifiers.contains(KeyModifiers::CONTROL)
119
        {
120
1
            return Err(format!("`{text}`: Ctrl letters are written in lower case"));
121
3991551
        }
122
3991551
        Ok(Chord { code, modifiers })
123
4217073
    }
124
}
125

            
126
69489
fn key_name(code: KeyCode) -> String {
127
69489
    if let KeyCode::F(number) = code {
128
10262
        return format!("F{number}");
129
59227
    }
130
743936
    let named = NAMED.iter().find(|(_, known)| *known == code);
131
59227
    match (named, code) {
132
24521
        (Some((name, _)), _) => (*name).to_string(),
133
34706
        (None, KeyCode::Char(c)) => c.to_string(),
134
        (None, other) => format!("{other:?}"),
135
    }
136
69489
}
137

            
138
impl fmt::Display for Chord {
139
69489
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140
69489
        for (letter, flag) in MODIFIERS {
141
208467
            if self.modifiers.contains(flag) {
142
17548
                write!(f, "{letter}-")?;
143
190919
            }
144
        }
145
69489
        f.write_str(&key_name(self.code))
146
69489
    }
147
}