Skip to main content

eternal_ui/
shortcut.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Keyboard shortcuts, written the way they are shown in menus.
6
7use std::fmt;
8
9use crate::event::{Key, Modifiers};
10
11/// A key with modifiers, such as `Ctrl+Shift+S`.
12///
13/// Parsed from and displayed as text so that shortcuts can live in
14/// configuration and in the `shortcut` attribute of an element.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
16pub struct Shortcut {
17    pub modifiers: Modifiers,
18    pub key: Key,
19}
20
21impl Shortcut {
22    pub const fn new(modifiers: Modifiers, key: Key) -> Self {
23        Self { modifiers, key }
24    }
25
26    /// Parses `Ctrl+S`, `Cmd+Shift+Z`, `F5`, `Escape` and the like. Parts are
27    /// separated by `+`, in any order, ignoring case. `Ctrl`, `Control`,
28    /// `Shift`, `Alt`, `Option`, `Cmd`, `Meta`, `Super` and `Win` are the
29    /// modifiers; a single character or a key name is the key.
30    pub fn parse(text: &str) -> Result<Self, ShortcutParseError> {
31        let mut modifiers = Modifiers::empty();
32        let mut key = None;
33        for part in text.split('+').map(str::trim) {
34            if part.is_empty() {
35                return Err(ShortcutParseError(text.to_owned()));
36            }
37            match part.to_ascii_lowercase().as_str() {
38                "ctrl" | "control" => modifiers |= Modifiers::CTRL,
39                "shift" => modifiers |= Modifiers::SHIFT,
40                "alt" | "option" => modifiers |= Modifiers::ALT,
41                "cmd" | "meta" | "super" | "win" => modifiers |= Modifiers::META,
42                name => {
43                    if key
44                        .replace(
45                            parse_key(name).ok_or_else(|| ShortcutParseError(text.to_owned()))?,
46                        )
47                        .is_some()
48                    {
49                        return Err(ShortcutParseError(text.to_owned()));
50                    }
51                }
52            }
53        }
54        let key = key.ok_or_else(|| ShortcutParseError(text.to_owned()))?;
55        Ok(Self { modifiers, key })
56    }
57
58    /// Whether a key press with these modifiers triggers the shortcut.
59    pub fn matches(&self, key: Key, modifiers: Modifiers) -> bool {
60        self.key == key && self.modifiers == modifiers
61    }
62}
63
64fn parse_key(name: &str) -> Option<Key> {
65    let mut chars = name.chars();
66    if let (Some(c), None) = (chars.next(), chars.next()) {
67        return Some(Key::Char(c.to_ascii_lowercase()));
68    }
69    Some(match name {
70        "enter" | "return" => Key::Enter,
71        "esc" | "escape" => Key::Escape,
72        "tab" => Key::Tab,
73        "backspace" => Key::Backspace,
74        "delete" | "del" => Key::Delete,
75        "space" => Key::Space,
76        "left" | "arrowleft" => Key::ArrowLeft,
77        "right" | "arrowright" => Key::ArrowRight,
78        "up" | "arrowup" => Key::ArrowUp,
79        "down" | "arrowdown" => Key::ArrowDown,
80        "home" => Key::Home,
81        "end" => Key::End,
82        "pageup" => Key::PageUp,
83        "pagedown" => Key::PageDown,
84        _ => {
85            let number: u8 = name.strip_prefix('f')?.parse().ok()?;
86            if (1..=24).contains(&number) {
87                Key::F(number)
88            } else {
89                return None;
90            }
91        }
92    })
93}
94
95impl fmt::Display for Shortcut {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        for (flag, name) in [
98            (Modifiers::CTRL, "Ctrl"),
99            (Modifiers::ALT, "Alt"),
100            (Modifiers::SHIFT, "Shift"),
101            (Modifiers::META, "Cmd"),
102        ] {
103            if self.modifiers.contains(flag) {
104                f.write_str(name)?;
105                f.write_str("+")?;
106            }
107        }
108        match self.key {
109            Key::Char(c) => write!(f, "{}", c.to_ascii_uppercase()),
110            Key::Enter => f.write_str("Enter"),
111            Key::Escape => f.write_str("Escape"),
112            Key::Tab => f.write_str("Tab"),
113            Key::Backspace => f.write_str("Backspace"),
114            Key::Delete => f.write_str("Delete"),
115            Key::Space => f.write_str("Space"),
116            Key::ArrowLeft => f.write_str("Left"),
117            Key::ArrowRight => f.write_str("Right"),
118            Key::ArrowUp => f.write_str("Up"),
119            Key::ArrowDown => f.write_str("Down"),
120            Key::Home => f.write_str("Home"),
121            Key::End => f.write_str("End"),
122            Key::PageUp => f.write_str("PageUp"),
123            Key::PageDown => f.write_str("PageDown"),
124            Key::F(n) => write!(f, "F{n}"),
125        }
126    }
127}
128
129/// The text was not a shortcut.
130#[derive(Clone, Debug, PartialEq, Eq)]
131pub struct ShortcutParseError(String);
132
133impl fmt::Display for ShortcutParseError {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        write!(f, "not a shortcut: '{}'", self.0)
136    }
137}
138
139impl std::error::Error for ShortcutParseError {}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    #[test]
146    fn parses_and_displays() {
147        let save = Shortcut::parse("ctrl+s").unwrap();
148        assert_eq!(save, Shortcut::new(Modifiers::CTRL, Key::Char('s')));
149        assert_eq!(save.to_string(), "Ctrl+S");
150        assert_eq!(
151            Shortcut::parse("Shift + Cmd + Z").unwrap(),
152            Shortcut::new(Modifiers::SHIFT | Modifiers::META, Key::Char('z'))
153        );
154        assert_eq!(Shortcut::parse("F5").unwrap().key, Key::F(5));
155        assert_eq!(Shortcut::parse("Escape").unwrap().key, Key::Escape);
156        assert_eq!(
157            Shortcut::parse("Alt+Return").unwrap().to_string(),
158            "Alt+Enter"
159        );
160        assert!(Shortcut::parse("Ctrl+").is_err());
161        assert!(Shortcut::parse("Ctrl").is_err());
162        assert!(Shortcut::parse("A+B").is_err());
163        assert!(Shortcut::parse("F25").is_err());
164        assert!(Shortcut::parse("").is_err());
165    }
166
167    #[test]
168    fn matching_is_exact_on_modifiers() {
169        let save = Shortcut::parse("Ctrl+S").unwrap();
170        assert!(save.matches(Key::Char('s'), Modifiers::CTRL));
171        assert!(!save.matches(Key::Char('s'), Modifiers::CTRL | Modifiers::SHIFT));
172        assert!(!save.matches(Key::Char('s'), Modifiers::empty()));
173    }
174}