1use std::fmt;
22
23use crate::platform::Os;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
27pub struct Modifiers {
28 pub ctrl: bool,
30 pub alt: bool,
32 pub shift: bool,
34 pub cmd: bool,
36 pub alt_graph: bool,
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
45pub enum Key {
46 Char(char),
49 Enter,
51 Escape,
53 Tab,
55 Backspace,
57 Delete,
59 Insert,
61 Up,
63 Down,
65 Left,
67 Right,
69 Home,
71 End,
73 PageUp,
75 PageDown,
77 F(u8),
79}
80
81const 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 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 0x30..=0x39 => Key::Char(char::from(vk as u8)),
119 0x41..=0x5A => Key::Char(char::from(vk as u8).to_ascii_lowercase()),
120 0x60..=0x69 => Key::Char(char::from(b'0' + (vk - 0x60) as u8)),
122 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 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 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 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 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 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
285const 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
300const 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
317pub struct Keystroke {
318 pub modifiers: Modifiers,
320 pub key: Key,
322}
323
324#[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
336const 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
361const 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 ("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 pub fn parse(text: &str, os: Os) -> Result<Keystroke, KeystrokeError> {
406 Keystroke::parse_with(text, apple_keys(os, false))
407 }
408
409 pub fn parse_with(text: &str, apple: bool) -> Result<Keystroke, KeystrokeError> {
413 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 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 Os::Web => None,
454 }
455 }
456
457 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 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
481fn 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
514fn 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 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
579pub 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
588pub 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
698pub enum When {
699 #[default]
703 Auto,
704 Always,
706 NotEditing,
709}
710
711#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
714#[non_exhaustive]
715pub enum OverFocused {
716 #[default]
719 Never,
720 Always,
726 Pointer,
732}
733
734impl From<bool> for OverFocused {
735 fn from(over: bool) -> OverFocused {
737 if over {
738 OverFocused::Always
739 } else {
740 OverFocused::Never
741 }
742 }
743}
744
745#[derive(Debug, Clone, Copy, PartialEq, Eq)]
747pub struct KeyBinding {
748 pub id: u32,
751 pub keystroke: Keystroke,
753 pub in_text: bool,
756 pub repeat: bool,
759 pub pass_through: bool,
763 pub window: Option<crate::NodeId>,
768 pub for_focus: bool,
774 pub over_focused: OverFocused,
777}
778
779impl KeyBinding {
780 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 pub fn in_window(mut self, window: crate::NodeId) -> KeyBinding {
803 self.window = Some(window);
804 self
805 }
806
807 pub fn passing_through(mut self, pass_through: bool) -> KeyBinding {
810 self.pass_through = pass_through;
811 self
812 }
813
814 pub fn focus_keys(mut self, for_focus: bool) -> KeyBinding {
817 self.for_focus = for_focus;
818 self
819 }
820
821 pub fn over_focused(mut self, over: impl Into<OverFocused>) -> KeyBinding {
825 self.over_focused = over.into();
826 self
827 }
828
829 pub(crate) fn comes_after_views(&self) -> bool {
832 self.over_focused == OverFocused::Always
833 }
834
835 fn over_pointer_focus(&self) -> bool {
838 self.over_focused == OverFocused::Pointer
839 }
840}
841
842#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
844#[non_exhaustive]
845pub struct KeyFocus {
846 pub editing: bool,
848 pub control: bool,
853 pub covered: bool,
857}
858
859#[derive(Debug, Clone, Copy, PartialEq, Eq)]
861pub enum KeyMatch {
862 None,
864 Fire(u32),
867 Held,
870 Notify(u32),
875}
876
877impl KeyMatch {
878 pub fn consumed(self) -> bool {
880 matches!(self, KeyMatch::Fire(_) | KeyMatch::Held)
881 }
882
883 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#[derive(Debug, Clone, PartialEq, Eq, Default)]
896pub struct Keymap {
897 bindings: Vec<KeyBinding>,
898 pointer_focus: bool,
899}
900
901impl Keymap {
902 pub fn new(bindings: Vec<KeyBinding>) -> Keymap {
904 Keymap {
905 bindings,
906 pointer_focus: false,
907 }
908 }
909
910 pub(crate) fn with_pointer_focus(mut self, pointer_focus: bool) -> Keymap {
913 self.pointer_focus = pointer_focus;
914 self
915 }
916
917 #[cfg(test)]
923 pub(crate) fn pointer_focus(&self) -> bool {
924 self.pointer_focus
925 }
926
927 pub(crate) fn takes_over_pointer_focus(&self) -> bool {
931 self.bindings.iter().any(KeyBinding::over_pointer_focus)
932 }
933
934 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 pub fn is_empty(&self) -> bool {
966 self.bindings.is_empty()
967 }
968
969 pub fn bindings(&self) -> &[KeyBinding] {
971 &self.bindings
972 }
973
974 pub fn find(&self, keystroke: Keystroke, editing: bool, repeat: bool) -> KeyMatch {
982 self.find_in(crate::ROOT_ID, keystroke, editing, repeat)
983 }
984
985 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 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 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 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 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 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 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 assert_eq!(at(&table, enter, false), KeyMatch::Fire(1));
1117 assert_eq!(at(&table, space, false), KeyMatch::Fire(2));
1118 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 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 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 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 assert_eq!(at(&table, space, false, true), KeyMatch::Fire(3));
1152 assert_eq!(at(&table, enter, false, true), KeyMatch::None);
1153 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 assert_eq!(at(&pointer, space, false, false), KeyMatch::Fire(3));
1161 assert_eq!(at(&pointer, space, true, true), KeyMatch::None);
1162 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 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 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 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 assert_eq!(parse("mod+k"), parse("cmd+k"));
1329 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 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 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 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 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 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 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}