Skip to main content

tilo_ui_graph/
keys.rs

1//! The spelling of a key and of a chord: what an app declares (`key: "Ctrl+Enter"`), what the
2//! person presses, and what a menu or a palette shows.
3//!
4//! The compiler checks a declaration with it and the toolkit matches a press with it, so one table
5//! says what a key is called: `Esc` and the Escape key are one key, on any keyboard layout.
6
7/// The token of the key `name` names: `enter`, `escape`, `space`, `tab`, the arrows,
8/// `pageup`/`pagedown`, `home`/`end`, `delete`/`insert`, `f1`–`f12`, or one character in lowercase
9/// (`e`, `/`, `ä`). `None` when no key goes by that name.
10#[must_use]
11pub fn key(name: &str) -> Option<String> {
12    if name == " " {
13        return Some("space".to_owned());
14    }
15    let name = name.trim();
16    if name.chars().count() == 1 {
17        return Some(name.to_lowercase());
18    }
19    // A key painted the way a keyboard spells it (`Page Up`) names the same key as the token a press
20    // reports (`pageup`).
21    let canonical = match name.to_ascii_lowercase().replace([' ', '_'], "").as_str() {
22        "return" | "enter" => "enter",
23        "esc" | "escape" => "escape",
24        "spacebar" | "space" => "space",
25        "tab" => "tab",
26        "backspace" | "back" => "backspace",
27        "del" | "delete" => "delete",
28        "ins" | "insert" => "insert",
29        "arrowup" | "up" => "up",
30        "arrowdown" | "down" => "down",
31        "arrowleft" | "left" => "left",
32        "arrowright" | "right" => "right",
33        "home" => "home",
34        "end" => "end",
35        "pgup" | "pageup" => "pageup",
36        "pgdn" | "pgdown" | "pagedown" => "pagedown",
37        "f1" => "f1",
38        "f2" => "f2",
39        "f3" => "f3",
40        "f4" => "f4",
41        "f5" => "f5",
42        "f6" => "f6",
43        "f7" => "f7",
44        "f8" => "f8",
45        "f9" => "f9",
46        "f10" => "f10",
47        "f11" => "f11",
48        "f12" => "f12",
49        _ => return None,
50    };
51    Some(canonical.to_owned())
52}
53
54/// The keys a chord can name, for a message that teaches the spelling.
55pub const KEY_NAMES: &str = "`Enter`, `Esc`, `Space`, `Tab`, `Backspace`, `Delete`, `Home`, `End`, `PageUp`, `PageDown`, the arrows, `F1`–`F12`, or one character";
56
57/// Which modifier `name` is, the way a chord writes it.
58fn modifier(name: &str) -> Option<Modifier> {
59    match name.trim().to_ascii_lowercase().as_str() {
60        "ctrl" | "control" | "cmd" | "command" | "⌘" | "⌃" => Some(Modifier::Command),
61        "shift" | "⇧" => Some(Modifier::Shift),
62        "alt" | "option" | "⌥" => Some(Modifier::Alt),
63        "super" | "meta" | "win" | "logo" => Some(Modifier::System),
64        _ => None,
65    }
66}
67
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
69enum Modifier {
70    /// The platform's command modifier: Command on macOS, Control elsewhere.
71    Command,
72    Shift,
73    Alt,
74    /// The desktop's own modifier (Super).
75    System,
76}
77
78/// The chord's parts as it is written: each modifier name, then the key, each trimmed.
79fn parts_of(text: &str) -> Vec<&str> {
80    let text = text.trim();
81    // `Ctrl+=` and `Ctrl+-` name the equals and minus keys, which a split on `+` would read
82    // as no key at all: a key that is the separator's neighbour is the chord's last
83    // character.
84    let (modifiers, own) = match text.strip_suffix(['=', '-']) {
85        // Only after a modifier: a chord of the equals key alone is a part split on `+`
86        // reads as the key it is.
87        Some(rest) if rest.contains('+') => (rest.trim_end_matches('+'), text.get(rest.len()..)),
88        _ => (text, None),
89    };
90    let mut parts: Vec<&str> = modifiers.split('+').map(str::trim).collect();
91    if let Some(own) = own {
92        parts.push(own);
93    }
94    parts
95}
96
97/// The chord as it is written, with the modifiers in the names every chord uses
98/// (`Ctrl+Shift+Down` for `control+shift+Down`): the text a control's `key:` shows, so a menu row
99/// reads as the app wrote it. A press parses it as [`Chord::parse`] does, so a spelling and a
100/// modifier order never change which press it answers.
101///
102/// # Errors
103///
104/// What [`Chord::parse`] refuses.
105pub fn written(text: &str) -> Result<String, String> {
106    let _ = Chord::parse(text)?;
107    let parts = parts_of(text);
108    let last = parts.len().saturating_sub(1);
109    let shown: Vec<&str> = parts
110        .iter()
111        .enumerate()
112        .map(|(at, part)| match (at == last, modifier(part)) {
113            (true, _) | (false, None) => *part,
114            (false, Some(Modifier::Command)) => "Ctrl",
115            (false, Some(Modifier::System)) => "Super",
116            (false, Some(Modifier::Shift)) => "Shift",
117            (false, Some(Modifier::Alt)) => "Alt",
118        })
119        .collect();
120    Ok(shown.join("+"))
121}
122
123/// A key with the modifiers held with it, as a shortcut is written: `Ctrl+Enter`, `Ctrl+Shift+K`,
124/// `Alt+Up`, `F2`, `e`.
125// A key press reports each modifier as a flag of its own, so a chord holds four of them.
126#[allow(
127    clippy::struct_excessive_bools,
128    reason = "a press reports the four modifiers as independent flags; a chord mirrors them"
129)]
130#[derive(Clone, Debug, PartialEq, Eq)]
131pub struct Chord {
132    /// Held: the platform's command modifier (Command on macOS, Control elsewhere).
133    pub command: bool,
134    /// Held: the desktop's own modifier (Super).
135    pub system: bool,
136    pub shift: bool,
137    pub alt: bool,
138    /// The key's [`key`] token.
139    pub key: String,
140}
141
142impl Chord {
143    /// The chord `text` writes: modifiers, each with `+` after it, and then one key.
144    ///
145    /// # Errors
146    ///
147    /// What is not a chord: no key, a part that is neither a modifier nor a key, a modifier given
148    /// twice, a key before a modifier, or an empty part.
149    pub fn parse(text: &str) -> Result<Self, String> {
150        let text = text.trim();
151        let mut parts = parts_of(text);
152        if text.is_empty() || parts.iter().any(|part| part.is_empty()) {
153            return Err(format!(
154                "`{text}` is no shortcut: it is modifiers and one key, such as `Ctrl+Enter`"
155            ));
156        }
157        let mut key_seen: Option<&str> = None;
158        for part in &parts {
159            match (modifier(part), key_seen) {
160                (None, None) => key_seen = Some(*part),
161                (None, Some(_)) => {
162                    return Err(format!(
163                        "`{text}` names more than one key: it is modifiers and one key, such as `Ctrl+Enter`"
164                    ));
165                }
166                (Some(_), Some(key)) => {
167                    return Err(format!(
168                        "`{text}` holds one key: `{key}` comes before `{part}`, which is a modifier"
169                    ));
170                }
171                (Some(_), None) => {}
172            }
173        }
174        let Some(part) = parts.pop() else {
175            return Err(format!("`{text}` names no key: {KEY_NAMES}"));
176        };
177        if modifier(part).is_some() {
178            return Err(format!(
179                "`{part}` is a modifier, not a key: `{part}+Enter` holds it with a key"
180            ));
181        }
182        let Some(key) = key(part) else {
183            return Err(format!("`{part}` is no key: {KEY_NAMES}"));
184        };
185        let mut chord = Self {
186            command: false,
187            system: false,
188            shift: false,
189            alt: false,
190            key,
191        };
192        for part in parts {
193            match modifier(part) {
194                Some(Modifier::Command) if !chord.command => chord.command = true,
195                Some(Modifier::System) if !chord.system => chord.system = true,
196                Some(Modifier::Shift) if !chord.shift => chord.shift = true,
197                Some(Modifier::Alt) if !chord.alt => chord.alt = true,
198                Some(_) => return Err(format!("`{part}` is given twice in `{text}`")),
199                None => {
200                    return Err(format!(
201                        "`{part}` is no modifier: `Ctrl`, `Shift`, `Alt` or `Super`"
202                    ));
203                }
204            }
205        }
206        Ok(chord)
207    }
208
209    /// The chord as declared and shown: the modifiers in one order, then the key, each as the
210    /// keyboard in use spells it (`Ctrl+Shift+enter`, or a Mac reader's `⌘⇧↩`).
211    #[must_use]
212    pub fn text(&self) -> String {
213        let mut parts = Vec::with_capacity(5);
214        for (held, name) in [
215            (self.system, "Super"),
216            (self.command, "Ctrl"),
217            (self.alt, "Alt"),
218            (self.shift, "Shift"),
219        ] {
220            if held {
221                parts.push(name.to_owned());
222            }
223        }
224        parts.push(self.key.clone());
225        parts.join("+")
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    /// Every way of writing a key names it, and nothing else does.
234    #[test]
235    fn one_table_names_the_keys_a_shortcut_can_use() {
236        assert_eq!(key("Enter").as_deref(), Some("enter"));
237        assert_eq!(key("Return").as_deref(), Some("enter"));
238        assert_eq!(key("Esc").as_deref(), Some("escape"));
239        assert_eq!(key("PgDn").as_deref(), Some("pagedown"));
240        assert_eq!(key("F5").as_deref(), Some("f5"));
241        assert_eq!(key("E").as_deref(), Some("e"));
242        assert_eq!(key(" ").as_deref(), Some("space"));
243        assert_eq!(key("Page Up").as_deref(), Some("pageup"));
244        assert_eq!(key("Shift"), None);
245        assert_eq!(key("Entr"), None);
246    }
247
248    /// A chord reads the modifiers in any order, and says what a wrong one misses.
249    #[test]
250    fn a_chord_is_modifiers_and_one_key() {
251        let chord = Chord::parse("Shift+cTrL+Enter").expect("a chord");
252        assert!(chord.command && chord.shift && !chord.alt && !chord.system);
253        assert_eq!(chord.key, "enter");
254        assert_eq!(chord.text(), "Ctrl+Shift+enter");
255        assert_eq!(Chord::parse("e").expect("a key on its own").text(), "e");
256        assert_eq!(
257            Chord::parse("Super+Space").expect("a desktop chord").text(),
258            "Super+space"
259        );
260        assert_eq!(
261            Chord::parse("Ctrl+Enter").unwrap(),
262            Chord::parse("Control+Return").unwrap()
263        );
264        // The equals and minus keys are written with the separator beside them.
265        assert_eq!(
266            Chord::parse("Ctrl+=").expect("the equals key").text(),
267            "Ctrl+="
268        );
269        assert_eq!(
270            Chord::parse("Ctrl+-").expect("the minus key").text(),
271            "Ctrl+-"
272        );
273        for (wrong, said) in [
274            ("", "no shortcut"),
275            ("Ctrl", "is a modifier, not a key"),
276            ("Ctrl++Enter", "no shortcut"),
277            ("Ctrl+Entr", "is no key"),
278            ("Ctrl+Shift+Shift+K", "given twice"),
279            ("Ctrl+K+Shift", "comes before"),
280            ("Ctrl+K+Enter", "more than one key"),
281        ] {
282            let error = Chord::parse(wrong).expect_err(wrong);
283            assert!(error.contains(said), "`{wrong}`: {error}");
284        }
285    }
286
287    /// A chord is written with the modifiers in the names every chord uses, and the key as its app
288    /// wrote it: what a control's `key:` shows, whatever spelling of the press its app chose.
289    #[test]
290    fn a_chord_is_written_as_its_app_wrote_the_key() {
291        assert_eq!(written("Ctrl+S").expect("a chord"), "Ctrl+S");
292        assert_eq!(
293            written("control+shift+Down").expect("a chord"),
294            "Ctrl+Shift+Down"
295        );
296        assert_eq!(written("Super+/").expect("a chord"), "Super+/");
297        assert_eq!(written("Ctrl+=").expect("a chord"), "Ctrl+=");
298        for spelling in ["Ctrl+Enter", "control+Return", "shift+cTrL+ENTER"] {
299            assert_eq!(
300                Chord::parse(&written(spelling).expect("a chord")).expect("the written chord"),
301                Chord::parse(spelling).expect("the press"),
302                "{spelling} writes the press it names"
303            );
304        }
305        assert!(written("Ctrl+").is_err(), "what is no chord is not written");
306    }
307}