Skip to main content

nsh_core/
keymap.rs

1//! App-level keyboard shortcuts (`nsh/keymap`): keystrokes parsed from
2//! their text (`"mod+k"`, `"ctrl+shift+p"`, `"escape"`, `"f5"`) and the
3//! table of a surface's bindings.
4//!
5//! The syntax is the one `nsh_core::desktop::Shortcut` (menus, `nsh/desktop`)
6//! is moving to; the two will share this parser ([`Keystroke::parse`]).
7//!
8//! The main thread never waits for JS: JS sends the whole table to the
9//! platform ([`crate::Prop::Keymap`] on the root, mounted as
10//! [`crate::MountItem::Keymap`]), the platform matches each key against it
11//! on the spot ([`Keymap::find`]) and consumes the keys it binds, then
12//! tells JS which binding matched ([`crate::EventKind::KeyCommand`]).
13//!
14//! Keys are named by the character they type on the US layout without
15//! Shift (`"/"`, `"["`, `"1"`); Shift is a modifier (`"shift+/"` is `?`).
16//! Platforms match a key by the character it types without modifiers, and
17//! on a layout that types no ASCII there (Cyrillic, Greek, ...) by the US
18//! layout's character of the same key, as menus do, so shortcuts work on
19//! any layout.
20
21use std::fmt;
22
23use crate::platform::Os;
24
25/// The modifiers of a keystroke.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
27pub struct Modifiers {
28    /// Control.
29    pub ctrl: bool,
30    /// Option on Apple platforms, Alt elsewhere.
31    pub alt: bool,
32    /// Shift.
33    pub shift: bool,
34    /// Command on Apple platforms; the Super (Windows) key elsewhere.
35    pub cmd: bool,
36    /// AltGr (the DOM's `getModifierState("AltGraph")`): the key's
37    /// character came from the layout's AltGr level, so Control and Alt are
38    /// held to type text rather than for a shortcut. Only key events set
39    /// it; shortcuts never name or match it.
40    pub alt_graph: bool,
41}
42
43/// A key, by what it is on the US layout.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
45pub enum Key {
46    /// A key typing a printable ASCII character without Shift: a lower
47    /// case letter, a digit, punctuation, or `' '` (space).
48    Char(char),
49    /// Return / Enter (the keypad's too).
50    Enter,
51    /// Escape.
52    Escape,
53    /// Tab.
54    Tab,
55    /// Backspace (the Mac's Delete).
56    Backspace,
57    /// Forward delete.
58    Delete,
59    /// Insert (Help on Apple keyboards).
60    Insert,
61    /// Up arrow.
62    Up,
63    /// Down arrow.
64    Down,
65    /// Left arrow.
66    Left,
67    /// Right arrow.
68    Right,
69    /// Home.
70    Home,
71    /// End.
72    End,
73    /// Page Up.
74    PageUp,
75    /// Page Down.
76    PageDown,
77    /// A function key, F1 to F24.
78    F(u8),
79}
80
81/// The US layout's punctuation keys' Windows virtual-key codes
82/// (`VK_OEM_*`).
83const OEM_KEYS: &[(u16, char)] = &[
84    (0xBA, ';'),
85    (0xBB, '='),
86    (0xBC, ','),
87    (0xBD, '-'),
88    (0xBE, '.'),
89    (0xBF, '/'),
90    (0xC0, '`'),
91    (0xDB, '['),
92    (0xDC, '\\'),
93    (0xDD, ']'),
94    (0xDE, '\''),
95];
96
97impl Key {
98    /// The key of Windows virtual-key code `vk` (`VK_*`, which the Windows
99    /// and GPUI backends get); punctuation by the US layout's keys.
100    pub fn from_virtual_key(vk: u16) -> Option<Key> {
101        Some(match vk {
102            0x08 => Key::Backspace,
103            0x09 => Key::Tab,
104            0x0D => Key::Enter,
105            0x1B => Key::Escape,
106            0x20 => Key::Char(' '),
107            0x21 => Key::PageUp,
108            0x22 => Key::PageDown,
109            0x23 => Key::End,
110            0x24 => Key::Home,
111            0x25 => Key::Left,
112            0x26 => Key::Up,
113            0x27 => Key::Right,
114            0x28 => Key::Down,
115            0x2D => Key::Insert,
116            0x2E => Key::Delete,
117            // `0`-`9`, `A`-`Z`.
118            0x30..=0x39 => Key::Char(char::from(vk as u8)),
119            0x41..=0x5A => Key::Char(char::from(vk as u8).to_ascii_lowercase()),
120            // The keypad's digits.
121            0x60..=0x69 => Key::Char(char::from(b'0' + (vk - 0x60) as u8)),
122            // F1 to F24.
123            0x70..=0x87 => Key::F((vk - 0x6F) as u8),
124            _ => {
125                return OEM_KEYS
126                    .iter()
127                    .find(|(k, _)| *k == vk)
128                    .map(|&(_, c)| Key::Char(c));
129            }
130        })
131    }
132
133    /// The Windows virtual-key code of this key (the main keyboard's, not
134    /// the keypad's): what a key event for it carries.
135    pub fn virtual_key(self) -> Option<u16> {
136        Some(match self {
137            Key::Backspace => 0x08,
138            Key::Tab => 0x09,
139            Key::Enter => 0x0D,
140            Key::Escape => 0x1B,
141            Key::Char(' ') => 0x20,
142            Key::PageUp => 0x21,
143            Key::PageDown => 0x22,
144            Key::End => 0x23,
145            Key::Home => 0x24,
146            Key::Left => 0x25,
147            Key::Up => 0x26,
148            Key::Right => 0x27,
149            Key::Down => 0x28,
150            Key::Insert => 0x2D,
151            Key::Delete => 0x2E,
152            Key::Char(c @ '0'..='9') => c as u16,
153            Key::Char(c @ 'a'..='z') => c.to_ascii_uppercase() as u16,
154            Key::F(n @ 1..=24) => 0x6F + u16::from(n),
155            Key::Char(c) => return OEM_KEYS.iter().find(|(_, k)| *k == c).map(|&(vk, _)| vk),
156            Key::F(_) => return None,
157        })
158    }
159
160    /// The key of USB HID keyboard usage `usage` (usage page 7, which
161    /// UIKit's `UIKey.keyCode` is): the key's place on the US layout,
162    /// whatever layout types on it; the keypad's digits and Enter too.
163    pub fn from_hid_usage(usage: u16) -> Option<Key> {
164        Some(match usage {
165            4..=29 => Key::Char(char::from(b'a' + (usage - 4) as u8)),
166            30..=38 => Key::Char(char::from(b'1' + (usage - 30) as u8)),
167            39 => Key::Char('0'),
168            40 | 88 => Key::Enter,
169            41 => Key::Escape,
170            42 => Key::Backspace,
171            43 => Key::Tab,
172            44 => Key::Char(' '),
173            58..=69 => Key::F((usage - 57) as u8),
174            73 => Key::Insert,
175            74 => Key::Home,
176            75 => Key::PageUp,
177            76 => Key::Delete,
178            77 => Key::End,
179            78 => Key::PageDown,
180            79 => Key::Right,
181            80 => Key::Left,
182            81 => Key::Down,
183            82 => Key::Up,
184            89..=97 => Key::Char(char::from(b'1' + (usage - 89) as u8)),
185            98 => Key::Char('0'),
186            104..=115 => Key::F((usage - 91) as u8),
187            _ => {
188                return HID_KEYS
189                    .iter()
190                    .find(|(u, _)| *u == usage)
191                    .map(|&(_, c)| Key::Char(c));
192            }
193        })
194    }
195
196    /// The USB HID keyboard usage of this key (the main keyboard's, not
197    /// the keypad's): what a hardware keyboard sends for it.
198    pub fn hid_usage(self) -> Option<u16> {
199        Some(match self {
200            Key::Char(c @ 'a'..='z') => 4 + u16::from(c as u8 - b'a'),
201            Key::Char(c @ '1'..='9') => 30 + u16::from(c as u8 - b'1'),
202            Key::Char('0') => 39,
203            Key::Enter => 40,
204            Key::Escape => 41,
205            Key::Backspace => 42,
206            Key::Tab => 43,
207            Key::Char(' ') => 44,
208            Key::F(n @ 1..=12) => 57 + u16::from(n),
209            Key::F(n @ 13..=24) => 91 + u16::from(n),
210            Key::Insert => 73,
211            Key::Home => 74,
212            Key::PageUp => 75,
213            Key::Delete => 76,
214            Key::End => 77,
215            Key::PageDown => 78,
216            Key::Right => 79,
217            Key::Left => 80,
218            Key::Down => 81,
219            Key::Up => 82,
220            Key::Char(c) => return HID_KEYS.iter().find(|(_, k)| *k == c).map(|&(u, _)| u),
221            Key::F(_) => return None,
222        })
223    }
224
225    /// The key of Android key code `code` (`KeyEvent.KEYCODE_*`); the
226    /// keypad's digits and Enter, and the D-pad's center (Enter), too.
227    pub fn from_android_keycode(code: i32) -> Option<Key> {
228        Some(match code {
229            7..=16 => Key::Char(char::from(b'0' + (code - 7) as u8)),
230            29..=54 => Key::Char(char::from(b'a' + (code - 29) as u8)),
231            19 => Key::Up,
232            20 => Key::Down,
233            21 => Key::Left,
234            22 => Key::Right,
235            61 => Key::Tab,
236            62 => Key::Char(' '),
237            23 | 66 | 160 => Key::Enter,
238            67 => Key::Backspace,
239            92 => Key::PageUp,
240            93 => Key::PageDown,
241            111 => Key::Escape,
242            112 => Key::Delete,
243            122 => Key::Home,
244            123 => Key::End,
245            124 => Key::Insert,
246            131..=142 => Key::F((code - 130) as u8),
247            144..=153 => Key::Char(char::from(b'0' + (code - 144) as u8)),
248            _ => {
249                return ANDROID_KEYS
250                    .iter()
251                    .find(|(k, _)| *k == code)
252                    .map(|&(_, c)| Key::Char(c));
253            }
254        })
255    }
256
257    /// The Android key code of this key (`KeyEvent.KEYCODE_*`, the main
258    /// keyboard's): what a key event for it carries.
259    pub fn android_keycode(self) -> Option<i32> {
260        Some(match self {
261            Key::Char(c @ '0'..='9') => 7 + i32::from(c as u8 - b'0'),
262            Key::Char(c @ 'a'..='z') => 29 + i32::from(c as u8 - b'a'),
263            Key::Up => 19,
264            Key::Down => 20,
265            Key::Left => 21,
266            Key::Right => 22,
267            Key::Tab => 61,
268            Key::Char(' ') => 62,
269            Key::Enter => 66,
270            Key::Backspace => 67,
271            Key::PageUp => 92,
272            Key::PageDown => 93,
273            Key::Escape => 111,
274            Key::Delete => 112,
275            Key::Home => 122,
276            Key::End => 123,
277            Key::Insert => 124,
278            Key::F(n @ 1..=12) => 130 + i32::from(n),
279            Key::Char(c) => return ANDROID_KEYS.iter().find(|(_, k)| *k == c).map(|&(k, _)| k),
280            Key::F(_) => return None,
281        })
282    }
283}
284
285/// The US layout's punctuation keys' USB HID usages.
286const HID_KEYS: &[(u16, char)] = &[
287    (45, '-'),
288    (46, '='),
289    (47, '['),
290    (48, ']'),
291    (49, '\\'),
292    (51, ';'),
293    (52, '\''),
294    (53, '`'),
295    (54, ','),
296    (55, '.'),
297    (56, '/'),
298];
299
300/// The US layout's punctuation keys' Android key codes.
301const ANDROID_KEYS: &[(i32, char)] = &[
302    (55, ','),
303    (56, '.'),
304    (68, '`'),
305    (69, '-'),
306    (70, '='),
307    (71, '['),
308    (72, ']'),
309    (73, '\\'),
310    (74, ';'),
311    (75, '\''),
312    (76, '/'),
313];
314
315/// One key with its modifiers.
316#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
317pub struct Keystroke {
318    /// Modifiers held.
319    pub modifiers: Modifiers,
320    /// The key.
321    pub key: Key,
322}
323
324/// Why a keystroke's text is not one.
325#[derive(Debug, Clone, PartialEq, Eq)]
326pub struct KeystrokeError(pub String);
327
328impl fmt::Display for KeystrokeError {
329    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
330        f.write_str(&self.0)
331    }
332}
333
334impl std::error::Error for KeystrokeError {}
335
336/// Characters typed with Shift on the US layout, and the key typing them.
337const SHIFTED: &[(char, char)] = &[
338    ('~', '`'),
339    ('!', '1'),
340    ('@', '2'),
341    ('#', '3'),
342    ('$', '4'),
343    ('%', '5'),
344    ('^', '6'),
345    ('&', '7'),
346    ('*', '8'),
347    ('(', '9'),
348    (')', '0'),
349    ('_', '-'),
350    ('+', '='),
351    ('{', '['),
352    ('}', ']'),
353    ('|', '\\'),
354    (':', ';'),
355    ('"', '\''),
356    ('<', ','),
357    ('>', '.'),
358    ('?', '/'),
359];
360
361/// Named keys, by their names (lower case).
362const NAMED: &[(&str, Key)] = &[
363    ("enter", Key::Enter),
364    ("return", Key::Enter),
365    ("escape", Key::Escape),
366    ("esc", Key::Escape),
367    ("tab", Key::Tab),
368    ("space", Key::Char(' ')),
369    ("backspace", Key::Backspace),
370    ("delete", Key::Delete),
371    ("del", Key::Delete),
372    ("insert", Key::Insert),
373    ("up", Key::Up),
374    ("arrowup", Key::Up),
375    ("down", Key::Down),
376    ("arrowdown", Key::Down),
377    ("left", Key::Left),
378    ("arrowleft", Key::Left),
379    ("right", Key::Right),
380    ("arrowright", Key::Right),
381    ("home", Key::Home),
382    ("end", Key::End),
383    ("pageup", Key::PageUp),
384    ("pagedown", Key::PageDown),
385    // The plus key is the one typing `=`, as on the US layout.
386    ("plus", Key::Char('=')),
387    ("minus", Key::Char('-')),
388];
389
390fn error(text: &str, reason: impl fmt::Display) -> KeystrokeError {
391    KeystrokeError(format!("invalid keystroke {text:?}: {reason}"))
392}
393
394impl Keystroke {
395    /// Parses `text`: modifiers and a key joined by `+` (`"mod+shift+k"`,
396    /// `"mod+-"` for Command and minus), in any case (lowercase is the
397    /// style; a capital letter is the same key, not Shift). Modifiers:
398    /// `ctrl`, `alt` (`option`), `shift`, `cmd` (`super`, `win`) and `mod`,
399    /// which is Command on Apple platforms (`os`, [`apple_keys`]) and
400    /// Control elsewhere. Keys: a character of the US layout typed without Shift (`k`, `1`,
401    /// `/`, `[`, `=`: the plus key is `=`, `shift+=` with Shift), `space`,
402    /// `enter`, `escape`, `tab`, `backspace`, `delete`, the arrows `up` /
403    /// `down` / `left` / `right`, `home`, `end`, `pageup`, `pagedown`, `f1`
404    /// to `f24`.
405    pub fn parse(text: &str, os: Os) -> Result<Keystroke, KeystrokeError> {
406        Keystroke::parse_with(text, apple_keys(os, false))
407    }
408
409    /// Parses `text` as [`Keystroke::parse`] does, with Apple's conventions
410    /// (`mod` is Command) or not: a browser decides by the platform it runs
411    /// on ([`apple_keys`]).
412    pub fn parse_with(text: &str, apple: bool) -> Result<Keystroke, KeystrokeError> {
413        // Case does not matter (lowercase is the style); messages quote
414        // the text as written and suggest lowercase.
415        let lower = text.to_ascii_lowercase();
416        let (mods, key) = split(text, &lower)?;
417        let mut modifiers = Modifiers::default();
418        for name in mods {
419            let flag = modifier(&mut modifiers, name, apple).map_err(|why| error(text, why))?;
420            if *flag {
421                return Err(error(text, format_args!("{name:?} twice")));
422            }
423            *flag = true;
424        }
425        Ok(Keystroke {
426            modifiers,
427            key: parse_key(text, key)?,
428        })
429    }
430
431    /// Why the platform keeps this keystroke for itself on `os` (quitting,
432    /// hiding, minimizing the app or making it full screen), if it does:
433    /// such keystrokes cannot be bound.
434    pub fn reserved(&self, os: Os) -> Option<&'static str> {
435        let m = self.modifiers;
436        let only = |ctrl, alt, cmd| m.ctrl == ctrl && m.alt == alt && m.cmd == cmd && !m.shift;
437        match os {
438            Os::MacOs | Os::Ios => match self.key {
439                Key::Char('q') if only(false, false, true) => Some("it quits the app"),
440                Key::Char('h') if only(false, false, true) => Some("it hides the app"),
441                Key::Char('h') if only(false, true, true) => Some("it hides the other apps"),
442                Key::Char('m') if only(false, false, true) => Some("it minimizes the window"),
443                Key::Char('f') if only(true, false, true) => Some("it toggles full screen"),
444                _ => None,
445            },
446            Os::Linux | Os::Windows | Os::Android => match self.key {
447                Key::Char('q') if only(true, false, false) => Some("it quits the app"),
448                Key::F(4) if only(false, true, false) => Some("it closes the window"),
449                Key::F(11) if m == Modifiers::default() => Some("it toggles full screen"),
450                _ => None,
451            },
452            // The browser keeps its own keys: the page never sees them.
453            Os::Web => None,
454        }
455    }
456
457    /// Whether this is the development hosts' reload key on `os` (`mod+r`:
458    /// Cmd+R, Ctrl+R): built with their `dev` feature, platforms leave it
459    /// to the dev server client, whatever the app binds.
460    pub fn reloads(&self, os: Os) -> bool {
461        let m = self.modifiers;
462        let apple = apple_keys(os, false);
463        self.key == Key::Char('r') && !m.shift && !m.alt && m.cmd == apple && m.ctrl != apple
464    }
465
466    /// Whether a text input that has the keyboard focus uses this
467    /// keystroke itself: keys that type, move the caret or delete, and the
468    /// editing shortcuts (select all, cut, copy, paste, undo, redo).
469    /// Bindings of these keystrokes do not fire while text is edited,
470    /// unless they ask to ([`When::Always`]).
471    pub fn edits_text(&self) -> bool {
472        let m = self.modifiers;
473        match self.key {
474            Key::F(_) => false,
475            Key::Char(c) => !(m.cmd || m.ctrl) || matches!(c, 'a' | 'c' | 'v' | 'x' | 'y' | 'z'),
476            _ => true,
477        }
478    }
479}
480
481/// The modifiers and the key of `text` (`"mod+shift+k"`).
482fn split<'a>(text: &str, lower: &'a str) -> Result<(Vec<&'a str>, &'a str), KeystrokeError> {
483    if text.is_empty() {
484        return Err(error(text, "empty"));
485    }
486    if text.contains(char::is_whitespace) {
487        return Err(error(
488            text,
489            "one keystroke per binding (key sequences such as \"mod+k mod+s\" are not supported)",
490        ));
491    }
492    if lower == "+" || lower.ends_with("++") {
493        let mods = lower.strip_suffix("++").unwrap_or("");
494        let plus = if mods.is_empty() {
495            "plus".to_owned()
496        } else {
497            format!("{mods}+plus")
498        };
499        return Err(error(
500            text,
501            format_args!("write the plus key as \"plus\": {plus:?}"),
502        ));
503    }
504    let (mods, key) = match lower.rsplit_once('+') {
505        Some((mods, key)) => (mods.split('+').collect(), key),
506        None => (Vec::new(), lower),
507    };
508    if key.is_empty() {
509        return Err(error(text, "no key after the modifiers"));
510    }
511    Ok((mods, key))
512}
513
514/// The flag of modifier `name` in `modifiers`, or why it is none.
515fn modifier<'a>(
516    modifiers: &'a mut Modifiers,
517    name: &str,
518    apple: bool,
519) -> Result<&'a mut bool, String> {
520    Ok(match name {
521        "ctrl" | "control" => &mut modifiers.ctrl,
522        "alt" | "option" | "opt" => &mut modifiers.alt,
523        "shift" => &mut modifiers.shift,
524        "cmd" | "command" | "meta" | "super" | "win" => &mut modifiers.cmd,
525        "mod" | "cmdorctrl" | "commandorcontrol" if apple => &mut modifiers.cmd,
526        "mod" | "cmdorctrl" | "commandorcontrol" => &mut modifiers.ctrl,
527        "" => return Err("an empty modifier".into()),
528        other => {
529            return Err(format!(
530                "unknown modifier {other:?} (ctrl, alt, shift, cmd or mod)"
531            ));
532        }
533    })
534}
535
536fn parse_key(text: &str, key: &str) -> Result<Key, KeystrokeError> {
537    if let Some(&(_, named)) = NAMED.iter().find(|(name, _)| *name == key) {
538        return Ok(named);
539    }
540    if let Some(n) = key
541        .strip_prefix('f')
542        .filter(|n| !n.starts_with('0'))
543        .and_then(|n| n.parse::<u8>().ok())
544        && (1..=24).contains(&n)
545    {
546        return Ok(Key::F(n));
547    }
548    let mut chars = key.chars();
549    let (Some(c), None) = (chars.next(), chars.next()) else {
550        let hint = if let Some((first, _)) = key.split_once('-')
551            && modifier(&mut Modifiers::default(), first, false).is_ok()
552        {
553            // `mod--` is `mod+-`.
554            let joined = match key.strip_suffix("--") {
555                Some(mods) => format!("{}+-", mods.replace('-', "+")),
556                None => key.replace('-', "+"),
557            };
558            format!(" (join modifiers and the key with \"+\": {joined:?})")
559        } else {
560            String::new()
561        };
562        return Err(error(text, format_args!("unknown key {key:?}{hint}")));
563    };
564    if let Some(&(_, base)) = SHIFTED.iter().find(|(shifted, _)| *shifted == c) {
565        return Err(error(
566            text,
567            format_args!("{c:?} is typed with Shift: write \"shift+{base}\""),
568        ));
569    }
570    if !c.is_ascii_graphic() {
571        return Err(error(
572            text,
573            "keys are named by the US layout's characters (they match on any layout)",
574        ));
575    }
576    Ok(Key::Char(c))
577}
578
579/// The character the key typing `c` types with Shift on the US layout
580/// (`8` a `*`, `a` an `A`): what `shift+8` types.
581pub fn shifted(c: char) -> char {
582    SHIFTED
583        .iter()
584        .find(|(_, base)| *base == c)
585        .map_or(c.to_ascii_uppercase(), |(shifted, _)| *shifted)
586}
587
588/// Whether keyboard shortcuts on `os` follow Apple's conventions: `mod` is
589/// Command and labels use ⌘ ([`Keystroke::label`]). macOS and iOS do; a
590/// browser does when it runs on an Apple platform (`apple_keyboard`,
591/// [`crate::platform::Environment::apple_keyboard`]).
592pub fn apple_keys(os: Os, apple_keyboard: bool) -> bool {
593    match os {
594        Os::MacOs | Os::Ios => true,
595        Os::Web => apple_keyboard,
596        Os::Android | Os::Windows | Os::Linux => false,
597    }
598}
599
600impl Keystroke {
601    /// The keys pressed for this keystroke: where Ctrl stands in for
602    /// Command (`ctrl_for_command`, a terminal on macOS that cannot report
603    /// Command: [`crate::platform::Environment::ctrl_for_command`]), its
604    /// Command is Ctrl, so a label shows the key to press (`⌃O` for
605    /// `mod+o`). A keystroke with both keeps them.
606    pub fn pressed(mut self, ctrl_for_command: bool) -> Keystroke {
607        if ctrl_for_command && self.modifiers.cmd && !self.modifiers.ctrl {
608            self.modifiers.cmd = false;
609            self.modifiers.ctrl = true;
610        }
611        self
612    }
613
614    /// The keystroke as menus and hints show it: `⌃⌥⇧⌘K` with Apple's
615    /// conventions ([`apple_keys`]), else `Ctrl+Alt+Shift+K` (the Command
616    /// modifier is `Win` on Windows, `Meta` in a browser, `Super`
617    /// elsewhere).
618    pub fn label(&self, os: Os, apple: bool) -> String {
619        let m = self.modifiers;
620        let mut s = String::new();
621        if apple {
622            for (on, glyph) in [(m.ctrl, '⌃'), (m.alt, '⌥'), (m.shift, '⇧'), (m.cmd, '⌘')] {
623                if on {
624                    s.push(glyph);
625                }
626            }
627        } else {
628            let cmd = match os {
629                Os::Windows => "Win+",
630                Os::Web => "Meta+",
631                _ => "Super+",
632            };
633            for (on, name) in [
634                (m.ctrl, "Ctrl+"),
635                (m.alt, "Alt+"),
636                (m.shift, "Shift+"),
637                (m.cmd, cmd),
638            ] {
639                if on {
640                    s.push_str(name);
641                }
642            }
643        }
644        let named = |mac: &'static str, other: &'static str| if apple { mac } else { other };
645        match self.key {
646            Key::Char(' ') => s.push_str("Space"),
647            Key::Char(c) => s.push(c.to_ascii_uppercase()),
648            Key::F(n) => {
649                let _ = fmt::Write::write_fmt(&mut s, format_args!("F{n}"));
650            }
651            Key::Enter => s.push_str(named("↩", "Enter")),
652            Key::Escape => s.push_str(named("⎋", "Esc")),
653            Key::Tab => s.push_str(named("⇥", "Tab")),
654            Key::Backspace => s.push_str(named("⌫", "Backspace")),
655            Key::Delete => s.push_str(named("⌦", "Del")),
656            Key::Insert => s.push_str(named("Help", "Ins")),
657            Key::Up => s.push('↑'),
658            Key::Down => s.push('↓'),
659            Key::Left => s.push('←'),
660            Key::Right => s.push('→'),
661            Key::Home => s.push_str(named("↖", "Home")),
662            Key::End => s.push_str(named("↘", "End")),
663            Key::PageUp => s.push_str(named("⇞", "PgUp")),
664            Key::PageDown => s.push_str(named("⇟", "PgDn")),
665        }
666        s
667    }
668}
669
670impl fmt::Display for Keystroke {
671    /// The canonical text: `ctrl+alt+shift+cmd+<key>`.
672    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
673        let m = self.modifiers;
674        for (on, name) in [
675            (m.ctrl, "ctrl+"),
676            (m.alt, "alt+"),
677            (m.shift, "shift+"),
678            (m.cmd, "cmd+"),
679        ] {
680            if on {
681                f.write_str(name)?;
682            }
683        }
684        match self.key {
685            Key::Char(' ') => f.write_str("space"),
686            Key::Char(c) => write!(f, "{c}"),
687            Key::F(n) => write!(f, "f{n}"),
688            key => {
689                let name = NAMED.iter().find(|(_, k)| *k == key).map(|(n, _)| *n);
690                f.write_str(name.unwrap_or("?"))
691            }
692        }
693    }
694}
695
696/// When a binding fires.
697#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
698pub enum When {
699    /// Unless a text input (or a hosted native view, such as a web view)
700    /// has the keyboard focus and the keystroke is one it uses
701    /// ([`Keystroke::edits_text`]): the default.
702    #[default]
703    Auto,
704    /// Wherever the keyboard focus is, in text inputs too.
705    Always,
706    /// Only while no text input or hosted native view has the keyboard
707    /// focus.
708    NotEditing,
709}
710
711/// What a binding takes from the control with the keyboard focus
712/// ([`KeyBinding::over_focused`]; TS: `keymap.bind`'s `overFocused`).
713#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
714#[non_exhaustive]
715pub enum OverFocused {
716    /// Nothing: Return and Space press a focused control, and the
717    /// focus' own bindings take its keys first (default).
718    #[default]
719    Never,
720    /// A key a focused component binds itself (a query editor's mod+enter
721    /// over the editor's own), for as long as the app keeps the binding:
722    /// the binding comes before the views' bindings of its keystroke, not
723    /// after them. The root's table puts such bindings after the others
724    /// (`Core::keymap`), where the newest that may fire wins.
725    Always,
726    /// Return and Space, from a focused control that a pointer gave the
727    /// focus (`Keymap::pointer_focus`): a press, or a popup a press used
728    /// giving the focus back to its trigger. A control the keyboard
729    /// focused (Tab, the arrows) keeps them. A media player's Space plays
730    /// after a click on Mute.
731    Pointer,
732}
733
734impl From<bool> for OverFocused {
735    /// `true` is [`OverFocused::Always`], `false` [`OverFocused::Never`].
736    fn from(over: bool) -> OverFocused {
737        if over {
738            OverFocused::Always
739        } else {
740            OverFocused::Never
741        }
742    }
743}
744
745/// One binding of a [`Keymap`].
746#[derive(Debug, Clone, Copy, PartialEq, Eq)]
747pub struct KeyBinding {
748    /// What the platform reports when it fires
749    /// ([`crate::EventKind::KeyCommand`]'s payload).
750    pub id: u32,
751    /// The keystroke.
752    pub keystroke: Keystroke,
753    /// It fires while a text input or hosted native view has the keyboard
754    /// focus ([`When`], resolved).
755    pub in_text: bool,
756    /// It fires again on the auto-repeats of a held key; else once until
757    /// the key is released.
758    pub repeat: bool,
759    /// It fires and lets the key go on as if there were no binding
760    /// ([`KeyMatch::Notify`]): Tab still moves the focus, a text input
761    /// still types. Else the platform consumes the key.
762    pub pass_through: bool,
763    /// The window it belongs to, as its root node (a dialog root for a
764    /// window of the app's own): it fires only for keys pressed there.
765    /// `None`: in any window. [`crate::ROOT_ID`] is the app root, which is
766    /// app-wide in window model v2 (it is not a user window).
767    pub window: Option<crate::NodeId>,
768    /// It is the keys of the view with the keyboard focus (a component's,
769    /// bound while its part has the focus or its popup is open): Return
770    /// and Space reach it while the focus is on a control they press
771    /// ([`Keymap::find_at`]). Other bindings of those keys give way to the
772    /// focused control.
773    pub for_focus: bool,
774    /// What it takes from the control with the keyboard focus
775    /// ([`OverFocused`]).
776    pub over_focused: OverFocused,
777}
778
779impl KeyBinding {
780    /// A binding of `keystroke` firing as `when` says, on auto-repeats
781    /// too when `repeat`.
782    pub fn new(id: u32, keystroke: Keystroke, when: When, repeat: bool) -> KeyBinding {
783        let in_text = match when {
784            When::Auto => !keystroke.edits_text(),
785            When::Always => true,
786            When::NotEditing => false,
787        };
788        KeyBinding {
789            id,
790            keystroke,
791            in_text,
792            repeat,
793            pass_through: false,
794            window: None,
795            for_focus: false,
796            over_focused: OverFocused::Never,
797        }
798    }
799
800    /// The binding firing only in the window of root node `window`
801    /// ([`Self::window`]).
802    pub fn in_window(mut self, window: crate::NodeId) -> KeyBinding {
803        self.window = Some(window);
804        self
805    }
806
807    /// The binding firing without consuming the key when `pass_through`
808    /// ([`Self::pass_through`]).
809    pub fn passing_through(mut self, pass_through: bool) -> KeyBinding {
810        self.pass_through = pass_through;
811        self
812    }
813
814    /// The binding being the keys of the view with the keyboard focus when
815    /// `for_focus` ([`Self::for_focus`]).
816    pub fn focus_keys(mut self, for_focus: bool) -> KeyBinding {
817        self.for_focus = for_focus;
818        self
819    }
820
821    /// The binding taking from the control with the keyboard focus what
822    /// `over` says ([`Self::over_focused`]; `true` is
823    /// [`OverFocused::Always`], `false` [`OverFocused::Never`]).
824    pub fn over_focused(mut self, over: impl Into<OverFocused>) -> KeyBinding {
825        self.over_focused = over.into();
826        self
827    }
828
829    /// It comes after the views' bindings in the root's table
830    /// ([`OverFocused::Always`]).
831    pub(crate) fn comes_after_views(&self) -> bool {
832        self.over_focused == OverFocused::Always
833    }
834
835    /// It takes Return and Space from a control a pointer gave the focus
836    /// ([`OverFocused::Pointer`]).
837    fn over_pointer_focus(&self) -> bool {
838        self.over_focused == OverFocused::Pointer
839    }
840}
841
842/// Where the keyboard focus is as a key comes ([`Keymap::find_with`]).
843#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
844#[non_exhaustive]
845pub struct KeyFocus {
846    /// A text input or hosted native view has it.
847    pub editing: bool,
848    /// It is on a control (a view that takes presses, not a text input)
849    /// in the focus scope: the newest modal over its window, else the
850    /// window. Return and Space are the control's
851    /// ([`Keymap::find_at`]).
852    pub control: bool,
853    /// It is on a view the newest modal over its window covers: a focus
854    /// the app left there (a popup closing gave it back to its trigger as
855    /// a dialog opened). The keys are not that view's.
856    pub covered: bool,
857}
858
859/// What a key does with a [`Keymap`] ([`Keymap::find`]).
860#[derive(Debug, Clone, Copy, PartialEq, Eq)]
861pub enum KeyMatch {
862    /// No binding: the key goes on as if there were no keymap.
863    None,
864    /// It fires binding `id`: the platform consumes the key and reports it
865    /// ([`crate::EventKind::KeyCommand`]).
866    Fire(u32),
867    /// An auto-repeat of a held key whose binding fires once: the platform
868    /// consumes it and reports nothing.
869    Held,
870    /// It fires binding `id`, which passes the key through
871    /// ([`KeyBinding::pass_through`]): the platform reports it
872    /// ([`crate::EventKind::KeyCommand`]) and lets the key go on as if there
873    /// were no keymap (Tab moves the focus after the report).
874    Notify(u32),
875}
876
877impl KeyMatch {
878    /// The platform consumes the key.
879    pub fn consumed(self) -> bool {
880        matches!(self, KeyMatch::Fire(_) | KeyMatch::Held)
881    }
882
883    /// The binding the key fires, which the platform reports
884    /// ([`crate::EventKind::KeyCommand`]): a consumed one's or a passing
885    /// one's.
886    pub fn fired(self) -> Option<u32> {
887        match self {
888            KeyMatch::Fire(id) | KeyMatch::Notify(id) => Some(id),
889            KeyMatch::None | KeyMatch::Held => None,
890        }
891    }
892}
893
894/// The bindings of a surface, oldest first.
895#[derive(Debug, Clone, PartialEq, Eq, Default)]
896pub struct Keymap {
897    bindings: Vec<KeyBinding>,
898    pointer_focus: bool,
899}
900
901impl Keymap {
902    /// A table of `bindings`, oldest first.
903    pub fn new(bindings: Vec<KeyBinding>) -> Keymap {
904        Keymap {
905            bindings,
906            pointer_focus: false,
907        }
908    }
909
910    /// The table with the keyboard focus given by a pointer when
911    /// `pointer_focus` (`Keymap::pointer_focus`).
912    pub(crate) fn with_pointer_focus(mut self, pointer_focus: bool) -> Keymap {
913        self.pointer_focus = pointer_focus;
914        self
915    }
916
917    /// Whether a pointer gave the keyboard focus where it is: a press, or
918    /// a popup a press used giving it back to its trigger. The core keeps
919    /// it as the focus moves, in the table it mounts, while a binding
920    /// asks for it ([`OverFocused::Pointer`]); the keys that
921    /// follow are matched with it on the spot.
922    #[cfg(test)]
923    pub(crate) fn pointer_focus(&self) -> bool {
924        self.pointer_focus
925    }
926
927    /// Whether a binding asks how the focus came
928    /// ([`OverFocused::Pointer`]): the core keeps
929    /// `Keymap::pointer_focus` in the table only then.
930    pub(crate) fn takes_over_pointer_focus(&self) -> bool {
931        self.bindings.iter().any(KeyBinding::over_pointer_focus)
932    }
933
934    /// Whether `binding` gives way while the keyboard focus is on a
935    /// control its key presses (Return, Space;
936    /// [`crate::input::presses_focused_control`]). The focus' own bindings
937    /// ([`KeyBinding::for_focus`]) take such a key, the others give way to
938    /// the control. When a pointer gave the focus
939    /// (`Keymap::pointer_focus`) and an eligible binding of the key takes it over
940    /// such a focus ([`OverFocused::Pointer`]), only those take
941    /// it: the focus' own give way to them too (a `Select` trigger's Space
942    /// opening its list). A platform that matches keys itself (GTK's
943    /// shortcuts) passes the bindings eligible in the current window and focus.
944    pub fn gives_way(&self, binding: &KeyBinding, eligible: impl Fn(&KeyBinding) -> bool) -> bool {
945        let key = binding.keystroke;
946        if !crate::input::presses_focused_control(key.key, key.modifiers) {
947            return false;
948        }
949        if self.overrides_control(binding) {
950            return false;
951        }
952        !binding.for_focus
953            || (self.pointer_focus
954                && self
955                    .bindings
956                    .iter()
957                    .any(|b| b.keystroke == key && self.overrides_control(b) && eligible(b)))
958    }
959
960    fn overrides_control(&self, binding: &KeyBinding) -> bool {
961        self.pointer_focus && binding.over_pointer_focus()
962    }
963
964    /// No bindings: the platform need not look at keys.
965    pub fn is_empty(&self) -> bool {
966        self.bindings.is_empty()
967    }
968
969    /// The bindings, oldest first.
970    pub fn bindings(&self) -> &[KeyBinding] {
971        &self.bindings
972    }
973
974    /// What a key does: the newest binding of `keystroke` that fires while
975    /// `editing` (a text input or hosted native view has the keyboard
976    /// focus) takes it; `repeat` is an auto-repeat of a held key, which only
977    /// fires bindings that ask for it. A binding that passes the key
978    /// through gives [`KeyMatch::Notify`], and its held key's auto-repeats
979    /// go on ([`KeyMatch::None`]) unless it repeats.
980    /// The key is pressed with the app root as the window ([`Self::find_in`]).
981    pub fn find(&self, keystroke: Keystroke, editing: bool, repeat: bool) -> KeyMatch {
982        self.find_in(crate::ROOT_ID, keystroke, editing, repeat)
983    }
984
985    /// [`Self::find`] for a key pressed in the window of root node
986    /// `window`: only that window's bindings and those of no window
987    /// ([`KeyBinding::window`]) take it.
988    pub fn find_in(
989        &self,
990        window: crate::NodeId,
991        keystroke: Keystroke,
992        editing: bool,
993        repeat: bool,
994    ) -> KeyMatch {
995        self.find_at(window, keystroke, editing, false, repeat)
996    }
997
998    /// [`Self::find_in`] where the keyboard focus may be on a control
999    /// (`control`: a view that takes presses, not a text input). The keys
1000    /// that press it ([`crate::input::presses_focused_control`]: Return
1001    /// and Space) are its own: only the bindings of the focus
1002    /// ([`KeyBinding::for_focus`], a menu button's Return opening its
1003    /// menu) take them first; with none, the key goes on and the platform
1004    /// presses the control. A binding of Return elsewhere (a dialog's main
1005    /// action) does not act instead of the control the user moved the
1006    /// focus to; one that takes them over a pointer's focus
1007    /// ([`OverFocused::Pointer`]) does when a pointer gave it
1008    /// (`Keymap::pointer_focus`).
1009    pub fn find_at(
1010        &self,
1011        window: crate::NodeId,
1012        keystroke: Keystroke,
1013        editing: bool,
1014        control: bool,
1015        repeat: bool,
1016    ) -> KeyMatch {
1017        let focus = KeyFocus {
1018            editing,
1019            control,
1020            ..KeyFocus::default()
1021        };
1022        self.find_with(window, keystroke, focus, repeat)
1023    }
1024
1025    /// [`Self::find_at`] with where the keyboard focus is as one value. A
1026    /// focus the newest modal over its window covers ([`KeyFocus::covered`])
1027    /// has no keys of its own: the bindings of the focus
1028    /// ([`KeyBinding::for_focus`], a menu button's Return opening its menu
1029    /// under a dialog) do not take the key, so the dialog's do.
1030    pub fn find_with(
1031        &self,
1032        window: crate::NodeId,
1033        keystroke: Keystroke,
1034        focus: KeyFocus,
1035        repeat: bool,
1036    ) -> KeyMatch {
1037        let KeyFocus {
1038            editing,
1039            control,
1040            covered,
1041        } = focus;
1042        let pressing = control
1043            && !editing
1044            && crate::input::presses_focused_control(keystroke.key, keystroke.modifiers);
1045        let mut found = None;
1046        for binding in self.bindings.iter().rev() {
1047            if binding.keystroke != keystroke
1048                || (editing && !binding.in_text)
1049                || binding.window.is_some_and(|w| w != window)
1050                || (binding.for_focus && covered)
1051            {
1052                continue;
1053            }
1054            if !pressing || self.overrides_control(binding) {
1055                found = Some(binding);
1056                break;
1057            }
1058            if found.is_none() && binding.for_focus {
1059                found = Some(binding);
1060                // An older eligible pointer override can still take the key.
1061                if !self.pointer_focus {
1062                    break;
1063                }
1064            }
1065        }
1066        match found {
1067            None => KeyMatch::None,
1068            Some(b) if repeat && !b.repeat && b.pass_through => KeyMatch::None,
1069            Some(b) if repeat && !b.repeat => KeyMatch::Held,
1070            Some(b) if b.pass_through => KeyMatch::Notify(b.id),
1071            Some(b) => KeyMatch::Fire(b.id),
1072        }
1073    }
1074}
1075
1076#[cfg(test)]
1077mod tests {
1078    use super::*;
1079
1080    #[test]
1081    fn a_windows_binding_takes_only_its_windows_keys() {
1082        let escape = Keystroke::parse_with("escape", true).unwrap();
1083        let k = |id| KeyBinding::new(id, escape, When::Always, false);
1084        // JS's (any window), the app root's, then window 7's.
1085        let table = Keymap::new(vec![
1086            k(1),
1087            k(2).in_window(crate::ROOT_ID),
1088            k(3).in_window(7),
1089        ]);
1090        assert_eq!(table.find_in(7, escape, false, false), KeyMatch::Fire(3));
1091        assert_eq!(
1092            table.find_in(crate::ROOT_ID, escape, false, false),
1093            KeyMatch::Fire(2)
1094        );
1095        assert_eq!(table.find(escape, false, false), KeyMatch::Fire(2));
1096        // A window with none of its own: the one of no window.
1097        assert_eq!(table.find_in(9, escape, false, false), KeyMatch::Fire(1));
1098        let only = Keymap::new(vec![k(3).in_window(7)]);
1099        assert_eq!(only.find_in(9, escape, false, false), KeyMatch::None);
1100    }
1101
1102    #[test]
1103    fn return_and_space_on_a_control_fire_only_the_focus_bindings() {
1104        let key = |s| Keystroke::parse_with(s, true).unwrap();
1105        let (enter, space, cmd_enter) = (key("enter"), key("space"), key("cmd+enter"));
1106        // A dialog's Return, Space and Command+Return, then a menu button's
1107        // Return while it has the focus.
1108        let mut bindings = vec![
1109            KeyBinding::new(1, enter, When::NotEditing, false),
1110            KeyBinding::new(2, space, When::NotEditing, false),
1111            KeyBinding::new(3, cmd_enter, When::Always, false),
1112        ];
1113        let table = Keymap::new(bindings.clone());
1114        let at = |t: &Keymap, k, control| t.find_at(crate::ROOT_ID, k, false, control, false);
1115        // The focus on no control: they fire.
1116        assert_eq!(at(&table, enter, false), KeyMatch::Fire(1));
1117        assert_eq!(at(&table, space, false), KeyMatch::Fire(2));
1118        // On a control: they are its, but with Command held.
1119        assert_eq!(at(&table, enter, true), KeyMatch::None);
1120        assert_eq!(at(&table, space, true), KeyMatch::None);
1121        assert_eq!(at(&table, key("shift+enter"), true), KeyMatch::None);
1122        assert_eq!(at(&table, cmd_enter, true), KeyMatch::Fire(3));
1123        // The focus' own binding takes Return first.
1124        bindings.push(KeyBinding::new(4, enter, When::NotEditing, false).focus_keys(true));
1125        let table = Keymap::new(bindings);
1126        assert_eq!(at(&table, enter, true), KeyMatch::Fire(4));
1127        assert_eq!(at(&table, space, true), KeyMatch::None);
1128        // In a text field the control is not focused: as before.
1129        assert_eq!(
1130            table.find_at(crate::ROOT_ID, cmd_enter, true, true, false),
1131            KeyMatch::Fire(3)
1132        );
1133    }
1134
1135    #[test]
1136    fn a_binding_over_a_pointers_focus_takes_space_from_a_control_a_pointer_focused() {
1137        let key = |s| Keystroke::parse_with(s, false).unwrap();
1138        let (space, enter) = (key("space"), key("enter"));
1139        // A media player's Space and Return, then a Select trigger's own
1140        // Space (newer), bound while it has the focus.
1141        let table = Keymap::new(vec![
1142            KeyBinding::new(1, space, When::NotEditing, false).over_focused(OverFocused::Pointer),
1143            KeyBinding::new(2, enter, When::NotEditing, false),
1144            KeyBinding::new(3, space, When::NotEditing, false).focus_keys(true),
1145        ]);
1146        assert!(table.takes_over_pointer_focus());
1147        let at =
1148            |t: &Keymap, k, editing, control| t.find_at(crate::ROOT_ID, k, editing, control, false);
1149        // The keyboard focused the control: its own Space opens it, and
1150        // Return presses it, as without the option.
1151        assert_eq!(at(&table, space, false, true), KeyMatch::Fire(3));
1152        assert_eq!(at(&table, enter, false, true), KeyMatch::None);
1153        // A pointer focused it: the app's Space takes the key, over the
1154        // focus' own; Return, which does not ask, still presses it.
1155        let pointer = table.clone().with_pointer_focus(true);
1156        assert!(pointer.pointer_focus());
1157        assert_eq!(at(&pointer, space, false, true), KeyMatch::Fire(1));
1158        assert_eq!(at(&pointer, enter, false, true), KeyMatch::None);
1159        // No control focused, or a text field: as before.
1160        assert_eq!(at(&pointer, space, false, false), KeyMatch::Fire(3));
1161        assert_eq!(at(&pointer, space, true, true), KeyMatch::None);
1162        // `true` is the binding that comes after the views', which does
1163        // not ask how the focus came.
1164        let always = KeyBinding::new(4, space, When::NotEditing, false).over_focused(true);
1165        assert_eq!(always.over_focused, OverFocused::Always);
1166        assert!(always.comes_after_views());
1167        assert!(!Keymap::new(vec![always]).takes_over_pointer_focus());
1168        // A table where no binding asks.
1169        assert!(
1170            !Keymap::new(vec![KeyBinding::new(1, space, When::NotEditing, false)])
1171                .takes_over_pointer_focus()
1172        );
1173    }
1174
1175    #[test]
1176    fn an_ineligible_pointer_override_leaves_space_to_the_focused_control() {
1177        let space = Keystroke::parse_with("space", false).unwrap();
1178        let focus = KeyBinding::new(1, space, When::Always, false)
1179            .in_window(7)
1180            .focus_keys(true);
1181        let pointer = KeyBinding::new(2, space, When::Always, false)
1182            .in_window(8)
1183            .over_focused(OverFocused::Pointer);
1184        let table = Keymap::new(vec![focus, pointer]).with_pointer_focus(true);
1185        assert_eq!(
1186            table.find_at(7, space, false, true, false),
1187            KeyMatch::Fire(1)
1188        );
1189        assert_eq!(
1190            table.find_at(8, space, false, true, false),
1191            KeyMatch::Fire(2)
1192        );
1193
1194        assert!(!table.gives_way(&focus, |b| b.window.is_none_or(|w| w == 7)));
1195        assert!(table.gives_way(&focus, |_| true));
1196    }
1197
1198    #[test]
1199    fn a_covered_focus_leaves_return_to_the_other_bindings() {
1200        let enter = Keystroke::parse_with("enter", true).unwrap();
1201        // A dialog's Return, then a menu button's under it, bound while
1202        // it has the focus.
1203        let table = Keymap::new(vec![
1204            KeyBinding::new(1, enter, When::NotEditing, false),
1205            KeyBinding::new(2, enter, When::NotEditing, false).focus_keys(true),
1206        ]);
1207        let find = |covered| {
1208            let focus = KeyFocus {
1209                covered,
1210                ..KeyFocus::default()
1211            };
1212            table.find_with(crate::ROOT_ID, enter, focus, false)
1213        };
1214        assert_eq!(find(false), KeyMatch::Fire(2));
1215        assert_eq!(find(true), KeyMatch::Fire(1));
1216    }
1217
1218    #[test]
1219    fn shift_types_the_us_layouts_characters() {
1220        assert_eq!(shifted('8'), '*');
1221        assert_eq!(shifted('2'), '@');
1222        assert_eq!(shifted('/'), '?');
1223        assert_eq!(shifted('a'), 'A');
1224        assert_eq!(shifted('*'), '*');
1225    }
1226
1227    #[test]
1228    fn keys_have_windows_virtual_key_codes_both_ways() {
1229        assert_eq!(Key::from_virtual_key(0x4B), Some(Key::Char('k')));
1230        assert_eq!(Key::from_virtual_key(0x31), Some(Key::Char('1')));
1231        assert_eq!(Key::from_virtual_key(0x74), Some(Key::F(5)));
1232        assert_eq!(Key::from_virtual_key(0xBF), Some(Key::Char('/')));
1233        assert_eq!(Key::from_virtual_key(0x62), Some(Key::Char('2')));
1234        assert_eq!(Key::from_virtual_key(0x10), None);
1235        for vk in (0..=0xFF).filter(|vk| !(0x60..=0x69).contains(vk)) {
1236            if let Some(key) = Key::from_virtual_key(vk) {
1237                assert_eq!(key.virtual_key(), Some(vk), "{key:?}");
1238            }
1239        }
1240        assert_eq!(Key::Char('?').virtual_key(), None);
1241        assert_eq!(Key::F(25).virtual_key(), None);
1242    }
1243
1244    #[test]
1245    fn keys_have_hid_usages_and_android_key_codes_both_ways() {
1246        assert_eq!(Key::from_hid_usage(4), Some(Key::Char('a')));
1247        assert_eq!(Key::from_hid_usage(39), Some(Key::Char('0')));
1248        assert_eq!(Key::from_hid_usage(81), Some(Key::Down));
1249        assert_eq!(Key::from_hid_usage(56), Some(Key::Char('/')));
1250        assert_eq!(Key::from_hid_usage(88), Some(Key::Enter));
1251        assert_eq!(Key::from_hid_usage(104), Some(Key::F(13)));
1252        assert_eq!(Key::from_hid_usage(225), None);
1253        // The keypad's keys have the main keyboard's usages back.
1254        for usage in (0..=0xFF).filter(|u| !(88..=98).contains(u)) {
1255            if let Some(key) = Key::from_hid_usage(usage) {
1256                assert_eq!(key.hid_usage(), Some(usage), "{key:?}");
1257            }
1258        }
1259        assert_eq!(Key::from_android_keycode(29), Some(Key::Char('a')));
1260        assert_eq!(Key::from_android_keycode(7), Some(Key::Char('0')));
1261        assert_eq!(Key::from_android_keycode(20), Some(Key::Down));
1262        assert_eq!(Key::from_android_keycode(76), Some(Key::Char('/')));
1263        assert_eq!(Key::from_android_keycode(160), Some(Key::Enter));
1264        assert_eq!(Key::from_android_keycode(23), Some(Key::Enter));
1265        assert_eq!(Key::from_android_keycode(59), None);
1266        for code in (0..=300).filter(|c| *c != 23 && *c != 160 && !(144..=153).contains(c)) {
1267            if let Some(key) = Key::from_android_keycode(code) {
1268                assert_eq!(key.android_keycode(), Some(code), "{key:?}");
1269            }
1270        }
1271    }
1272
1273    fn parse(text: &str) -> Result<Keystroke, KeystrokeError> {
1274        Keystroke::parse(text, Os::MacOs)
1275    }
1276
1277    fn stroke(ctrl: bool, alt: bool, shift: bool, cmd: bool, key: Key) -> Keystroke {
1278        Keystroke {
1279            modifiers: Modifiers {
1280                ctrl,
1281                alt,
1282                shift,
1283                cmd,
1284                alt_graph: false,
1285            },
1286            key,
1287        }
1288    }
1289
1290    #[test]
1291    fn parses_keystrokes() {
1292        let c = |c| Key::Char(c);
1293        assert_eq!(parse("k"), Ok(stroke(false, false, false, false, c('k'))));
1294        assert_eq!(
1295            parse("cmd+shift+k"),
1296            Ok(stroke(false, false, true, true, c('k')))
1297        );
1298        assert_eq!(
1299            parse("ctrl+alt+enter"),
1300            Ok(stroke(true, true, false, false, Key::Enter))
1301        );
1302        assert_eq!(
1303            parse("cmd+-"),
1304            Ok(stroke(false, false, false, true, c('-')))
1305        );
1306        assert_eq!(parse("-"), Ok(stroke(false, false, false, false, c('-'))));
1307        assert_eq!(
1308            parse("cmd+="),
1309            Ok(stroke(false, false, false, true, c('=')))
1310        );
1311        assert_eq!(
1312            parse("space"),
1313            Ok(stroke(false, false, false, false, c(' ')))
1314        );
1315        assert_eq!(
1316            parse("f5"),
1317            Ok(stroke(false, false, false, false, Key::F(5)))
1318        );
1319        assert_eq!(
1320            parse("shift+/"),
1321            Ok(stroke(false, false, true, false, c('/')))
1322        );
1323        assert_eq!(
1324            parse("option+escape"),
1325            Ok(stroke(false, true, false, false, Key::Escape))
1326        );
1327        // `mod` is Command on Apple platforms, Control elsewhere.
1328        assert_eq!(parse("mod+k"), parse("cmd+k"));
1329        // Case does not matter, and a capital letter is not Shift.
1330        assert_eq!(parse("Mod+Shift+N"), parse("mod+shift+n"));
1331        assert_eq!(parse("CMD+K"), parse("cmd+k"));
1332        assert_eq!(parse("mod+K"), parse("mod+k"));
1333        assert_eq!(parse("Escape"), parse("escape"));
1334        assert_eq!(parse("F5"), parse("f5"));
1335        assert_eq!(parse("Ctrl+Plus"), parse("ctrl+="));
1336        assert_eq!(parse("cmdorctrl+k"), parse("meta+k"));
1337        assert_eq!(parse("mod+plus"), parse("mod+="));
1338        assert_eq!(parse("ctrl+minus"), parse("ctrl+-"));
1339        assert_eq!(parse("arrowup"), parse("up"));
1340        assert_eq!(parse("insert").unwrap().key, Key::Insert);
1341        assert_eq!(
1342            Keystroke::parse("mod+k", Os::Linux),
1343            Keystroke::parse("ctrl+k", Os::Linux)
1344        );
1345        assert_eq!(parse("mod+k").unwrap().to_string(), "cmd+k");
1346        assert_eq!(
1347            parse("shift+cmd+alt+ctrl+pagedown").unwrap().to_string(),
1348            "ctrl+alt+shift+cmd+pagedown"
1349        );
1350    }
1351
1352    #[test]
1353    fn follows_the_browsers_platform() {
1354        // A browser resolves `mod` by the platform it runs on.
1355        assert!(apple_keys(Os::Web, true));
1356        assert!(!apple_keys(Os::Web, false));
1357        assert!(apple_keys(Os::MacOs, false));
1358        assert_eq!(
1359            Keystroke::parse_with("mod+k", true),
1360            Keystroke::parse("cmd+k", Os::MacOs)
1361        );
1362        assert_eq!(
1363            Keystroke::parse("mod+k", Os::Web),
1364            Keystroke::parse("ctrl+k", Os::Web)
1365        );
1366        // Literal modifiers stay what they say.
1367        assert_eq!(
1368            Keystroke::parse_with("ctrl+k", true),
1369            Keystroke::parse("ctrl+k", Os::Linux)
1370        );
1371    }
1372
1373    #[test]
1374    fn labels_keystrokes() {
1375        let label = |t, os, apple| Keystroke::parse_with(t, apple).unwrap().label(os, apple);
1376        assert_eq!(label("mod+shift+l", Os::Web, true), "⇧⌘L");
1377        assert_eq!(label("mod+shift+l", Os::Web, false), "Ctrl+Shift+L");
1378        assert_eq!(label("mod+backspace", Os::MacOs, true), "⌘⌫");
1379        assert_eq!(label("ctrl+alt+enter", Os::Linux, false), "Ctrl+Alt+Enter");
1380        assert_eq!(label("cmd+space", Os::Windows, false), "Win+Space");
1381        assert_eq!(label("f5", Os::Web, true), "F5");
1382        assert_eq!(label("mod+/", Os::Web, false), "Ctrl+/");
1383        // Where Ctrl stands in for Command, the label shows Ctrl.
1384        let pressed = |t| {
1385            Keystroke::parse_with(t, true)
1386                .unwrap()
1387                .pressed(true)
1388                .label(Os::MacOs, true)
1389        };
1390        assert_eq!(pressed("mod+o"), "⌃O");
1391        assert_eq!(pressed("mod+shift+t"), "⌃⇧T");
1392        assert_eq!(pressed("ctrl+cmd+f"), "⌃⌘F");
1393    }
1394
1395    #[test]
1396    fn explains_invalid_keystrokes() {
1397        let err = |t| parse(t).unwrap_err().0;
1398        assert_eq!(err(""), "invalid keystroke \"\": empty");
1399        assert!(err("mod+k mod+s").contains("one keystroke per binding"));
1400        assert!(err("cmd+").contains("no key after the modifiers"));
1401        assert!(err("hyper+k").contains("unknown modifier \"hyper\""));
1402        assert!(err("cmd+cmd+k").contains("\"cmd\" twice"));
1403        assert!(err("cmd+kk").contains("unknown key \"kk\""));
1404        assert!(err("mod-k").contains("join modifiers and the key with \"+\": \"mod+k\""));
1405        assert!(err("ctrl-shift-p").contains("\"ctrl+shift+p\""));
1406        assert!(err("mod--").contains("\"mod+-\""));
1407        // Hints suggest lowercase, whatever case the text was written in.
1408        assert!(err("Mod-K").contains("join modifiers and the key with \"+\": \"mod+k\""));
1409        assert!(err("CTRL++").contains("\"ctrl+plus\""));
1410        assert!(err("cmd+?").contains("write \"shift+/\""));
1411        assert!(err("mod++").contains("write the plus key as \"plus\": \"mod+plus\""));
1412        assert!(err("+").contains("\"plus\""));
1413        assert!(err("cmd+é").contains("US layout"));
1414        assert!(err("f25").contains("unknown key"));
1415        assert!(err("f05").contains("unknown key"));
1416        assert!(err("cmd++k").contains("an empty modifier"));
1417    }
1418
1419    #[test]
1420    fn reserves_what_the_platform_keeps() {
1421        let reserved = |t, os| Keystroke::parse(t, os).unwrap().reserved(os).is_some();
1422        assert!(reserved("mod+q", Os::MacOs));
1423        assert!(reserved("cmd+alt+h", Os::MacOs));
1424        assert!(reserved("ctrl+cmd+f", Os::MacOs));
1425        assert!(!reserved("cmd+shift+q", Os::MacOs));
1426        assert!(!reserved("ctrl+q", Os::MacOs));
1427        assert!(!reserved("cmd+w", Os::MacOs));
1428        assert!(reserved("mod+q", Os::Linux));
1429        assert!(reserved("f11", Os::Linux));
1430        assert!(reserved("alt+f4", Os::Windows));
1431        assert!(!reserved("cmd+q", Os::Linux));
1432    }
1433
1434    #[test]
1435    fn the_dev_reload_key() {
1436        let reloads = |t, os| Keystroke::parse(t, os).unwrap().reloads(os);
1437        assert!(reloads("mod+r", Os::MacOs));
1438        assert!(reloads("ctrl+r", Os::Windows));
1439        assert!(!reloads("ctrl+r", Os::MacOs));
1440        assert!(!reloads("mod+shift+r", Os::Linux));
1441    }
1442
1443    #[test]
1444    fn text_inputs_keep_their_keys() {
1445        let edits = |t| parse(t).unwrap().edits_text();
1446        assert!(edits("k"));
1447        assert!(edits("shift+k"));
1448        assert!(edits("alt+k"));
1449        assert!(edits("escape"));
1450        assert!(edits("cmd+left"));
1451        assert!(edits("cmd+c"));
1452        assert!(edits("cmd+shift+z"));
1453        assert!(edits("ctrl+y"));
1454        assert!(edits("cmd+y"));
1455        assert!(!edits("cmd+k"));
1456        assert!(!edits("ctrl+shift+p"));
1457        assert!(!edits("f5"));
1458    }
1459
1460    #[test]
1461    fn the_newest_binding_that_fires_wins() {
1462        let k = parse("cmd+k").unwrap();
1463        let e = parse("escape").unwrap();
1464        let map = Keymap::new(vec![
1465            KeyBinding::new(1, k, When::Auto, false),
1466            KeyBinding::new(2, e, When::Auto, true),
1467            KeyBinding::new(3, k, When::NotEditing, false),
1468        ]);
1469        assert_eq!(map.find(k, false, false), KeyMatch::Fire(3));
1470        assert_eq!(map.find(k, true, false), KeyMatch::Fire(1));
1471        assert_eq!(map.find(e, false, false), KeyMatch::Fire(2));
1472        assert_eq!(map.find(e, true, false), KeyMatch::None);
1473        assert_eq!(
1474            map.find(parse("cmd+j").unwrap(), false, false),
1475            KeyMatch::None
1476        );
1477        // A held key fires once, unless its binding repeats.
1478        assert_eq!(map.find(k, false, true), KeyMatch::Held);
1479        assert_eq!(map.find(e, false, true), KeyMatch::Fire(2));
1480        let always = Keymap::new(vec![KeyBinding::new(4, e, When::Always, false)]);
1481        assert_eq!(always.find(e, true, false), KeyMatch::Fire(4));
1482    }
1483
1484    #[test]
1485    fn a_passing_binding_fires_and_leaves_the_key() {
1486        let tab = parse("tab").unwrap();
1487        let map = Keymap::new(vec![
1488            KeyBinding::new(1, tab, When::Auto, false).passing_through(true),
1489        ]);
1490        let found = map.find(tab, false, false);
1491        assert_eq!(found, KeyMatch::Notify(1));
1492        assert_eq!(found.fired(), Some(1));
1493        assert!(!found.consumed());
1494        // Its held key's repeats go on, unreported.
1495        assert_eq!(map.find(tab, false, true), KeyMatch::None);
1496        let repeating = Keymap::new(vec![
1497            KeyBinding::new(2, tab, When::Auto, true).passing_through(true),
1498        ]);
1499        assert_eq!(repeating.find(tab, false, true), KeyMatch::Notify(2));
1500        assert_eq!(KeyMatch::Fire(3).fired(), Some(3));
1501        assert!(KeyMatch::Fire(3).consumed() && KeyMatch::Held.consumed());
1502        assert_eq!(KeyMatch::Held.fired(), None);
1503    }
1504}