1use bitflags::bitflags;
45use std::fmt;
46
47bitflags! {
48 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
66 pub struct KeyModifiers: u16 {
67 const SHIFT = 0b0000_0000_0000_0001;
69 const ALT = 0b0000_0000_0000_0010;
71 const CTRL = 0b0000_0000_0000_0100;
73 const SUPER = 0b0000_0000_0000_1000;
75 const HYPER = 0b0000_0000_0001_0000;
77 const META = 0b0000_0000_0010_0000;
79 const CAPS_LOCK = 0b0000_0000_0100_0000;
81 const NUM_LOCK = 0b0000_0000_1000_0000;
83 const SCROLL_LOCK = 0b0000_0001_0000_0000;
85
86 const LOCK_MASK = Self::CAPS_LOCK.bits()
94 | Self::NUM_LOCK.bits()
95 | Self::SCROLL_LOCK.bits();
96 }
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
104pub enum KeyLocation {
105 #[default]
109 Standard,
110 Left,
112 Right,
114 Keypad,
116}
117
118#[derive(Debug, Clone)]
129pub struct Key {
130 pub code: KeyCode,
132 pub location: KeyLocation,
134 pub modifiers: KeyModifiers,
136 pub repeat: bool,
145 pub text: Option<String>,
152 pub shifted_key: Option<char>,
156 pub base_key: Option<char>,
160}
161
162impl PartialEq for Key {
163 fn eq(&self, other: &Self) -> bool {
164 self.code == other.code
165 && self.location == other.location
166 && self.modifiers.difference(KeyModifiers::LOCK_MASK)
167 == other.modifiers.difference(KeyModifiers::LOCK_MASK)
168 }
169}
170
171impl Eq for Key {}
172
173impl std::hash::Hash for Key {
174 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
175 self.code.hash(state);
176 self.location.hash(state);
177 self.modifiers
178 .difference(KeyModifiers::LOCK_MASK)
179 .hash(state);
180 }
181}
182
183impl Key {
184 pub fn new(code: KeyCode, modifiers: KeyModifiers) -> Self {
196 Self {
197 code,
198 location: KeyLocation::Standard,
199 modifiers,
200 repeat: false,
201 text: None,
202 shifted_key: None,
203 base_key: None,
204 }
205 }
206
207 pub fn normalized(mut self) -> Self {
212 self.normalize();
213 self
214 }
215
216 pub fn char(&self) -> Option<char> {
219 match self.code {
220 KeyCode::Char(c) => Some(c),
221 KeyCode::Space => Some(' '),
222 _ => None,
223 }
224 }
225
226 pub fn matches(&self, pattern: &str) -> bool {
272 let parsed = parse_key(pattern);
273 if let Ok((key, Some(_))) = &parsed {
274 return self == key;
275 }
276 if let Some(text) = self.text.as_deref()
277 && text == pattern
278 {
279 return true;
280 }
281 parsed.is_ok_and(|(mut key, _)| {
282 key.location = self.location;
283 *self == key
284 })
285 }
286
287 pub fn matches_any<I, S>(&self, patterns: I) -> bool
304 where
305 I: IntoIterator<Item = S>,
306 S: AsRef<str>,
307 {
308 patterns.into_iter().any(|p| self.matches(p.as_ref()))
309 }
310
311 pub fn normalize(&mut self) {
329 if let KeyCode::Char(c) = self.code {
331 if c.is_uppercase() {
332 let mut iter = c.to_lowercase();
333 if let Some(lower) = iter.next()
334 && iter.next().is_none()
335 && lower != c
336 {
337 self.code = KeyCode::Char(lower);
338 if self.shifted_key.is_none() {
339 self.shifted_key = Some(c);
340 }
341 if !self.modifiers.contains(KeyModifiers::CAPS_LOCK) {
342 self.modifiers |= KeyModifiers::SHIFT;
343 }
344 }
345 } else if c.is_lowercase()
346 && self
347 .modifiers
348 .intersects(KeyModifiers::SHIFT | KeyModifiers::CAPS_LOCK)
349 && self.shifted_key.is_none()
350 {
351 let mut iter = c.to_uppercase();
352 if let Some(upper) = iter.next()
353 && iter.next().is_none()
354 && upper != c
355 {
356 self.shifted_key = Some(upper);
357 }
358 }
359 }
360
361 if self.text.is_none() {
363 const PRINTABLE_ALLOWED: KeyModifiers = KeyModifiers::SHIFT
364 .union(KeyModifiers::CAPS_LOCK)
365 .union(KeyModifiers::NUM_LOCK);
366 if (self.modifiers - PRINTABLE_ALLOWED).is_empty() {
367 let glyph: Option<char> = match self.code {
387 KeyCode::Char(c) if !c.is_control() => {
388 let shifted = if c.is_lowercase() {
389 self.modifiers
390 .intersects(KeyModifiers::SHIFT | KeyModifiers::CAPS_LOCK)
391 } else {
392 self.modifiers.contains(KeyModifiers::SHIFT)
393 };
394 Some(if shifted {
395 self.shifted_key.unwrap_or(c)
396 } else {
397 c
398 })
399 }
400 KeyCode::Space => Some(' '),
401 _ => None,
402 };
403 if let Some(g) = glyph {
404 self.text = Some(g.to_string());
405 }
406 }
407 }
408 }
409}
410
411#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
422pub enum KeyCode {
423 Char(char),
429 F(u8),
435 Find,
438 Select,
441 Up,
444 Down,
446 Left,
448 Right,
450 Home,
452 End,
454 Begin,
456 PageUp,
458 PageDown,
460 Backspace,
463 Delete,
465 Insert,
467 Tab,
469 Enter,
471 Space,
482 Escape,
485 CapsLock,
487 ScrollLock,
489 NumLock,
491 PrintScreen,
493 Pause,
495 Menu,
497 MediaPlay,
500 MediaPause,
502 MediaPlayPause,
504 MediaReverse,
506 MediaStop,
508 MediaRewind,
510 MediaFastForward,
512 MediaNext,
514 MediaPrev,
516 MediaRecord,
518 VolumeUp,
520 VolumeDown,
522 VolumeMute,
524 Shift,
527 Ctrl,
529 Alt,
531 Super,
533 Hyper,
535 Meta,
537 IsoLevel3Shift,
539 IsoLevel5Shift,
541}
542
543impl KeyCode {
544 pub const FUNCTION_KEY_MAX: u8 = 35;
549
550 pub fn function(n: u8) -> Option<KeyCode> {
558 if (1..=Self::FUNCTION_KEY_MAX).contains(&n) {
559 Some(KeyCode::F(n))
560 } else {
561 None
562 }
563 }
564}
565
566impl fmt::Display for Key {
587 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
588 let mods = self.modifiers;
589 if mods.contains(KeyModifiers::CTRL) {
593 f.write_str("ctrl+")?;
594 }
595 if mods.contains(KeyModifiers::ALT) {
596 f.write_str("alt+")?;
597 }
598 if mods.contains(KeyModifiers::SHIFT) {
599 f.write_str("shift+")?;
600 }
601 if mods.contains(KeyModifiers::SUPER) {
602 f.write_str("super+")?;
603 }
604 if mods.contains(KeyModifiers::HYPER) {
605 f.write_str("hyper+")?;
606 }
607 if mods.contains(KeyModifiers::META) {
608 f.write_str("meta+")?;
609 }
610
611 if self.location == KeyLocation::Keypad
612 && let Some(name) = keypad_name(self.code)
613 {
614 return f.write_str(name);
615 }
616 match self.location {
617 KeyLocation::Standard => {}
618 KeyLocation::Left => f.write_str("left")?,
619 KeyLocation::Right => f.write_str("right")?,
620 KeyLocation::Keypad => f.write_str("kp")?,
621 }
622 self.code.fmt(f)
623 }
624}
625
626fn keypad_name(code: KeyCode) -> Option<&'static str> {
627 Some(match code {
628 KeyCode::Enter => "kpenter",
629 KeyCode::Char('+') => "kpadd",
630 KeyCode::Char('-') => "kpsubtract",
631 KeyCode::Char('*') => "kpmultiply",
632 KeyCode::Char('/') => "kpdivide",
633 KeyCode::Char('.') => "kpdecimal",
634 KeyCode::Char('=') => "kpequal",
635 KeyCode::Char(',') => "kpseparator",
636 KeyCode::Left => "kpleft",
637 KeyCode::Right => "kpright",
638 KeyCode::Up => "kpup",
639 KeyCode::Down => "kpdown",
640 KeyCode::PageUp => "kppageup",
641 KeyCode::PageDown => "kppagedown",
642 KeyCode::Home => "kphome",
643 KeyCode::End => "kpend",
644 KeyCode::Insert => "kpinsert",
645 KeyCode::Delete => "kpdelete",
646 KeyCode::Begin => "kpbegin",
647 KeyCode::Char('0') => "kp0",
648 KeyCode::Char('1') => "kp1",
649 KeyCode::Char('2') => "kp2",
650 KeyCode::Char('3') => "kp3",
651 KeyCode::Char('4') => "kp4",
652 KeyCode::Char('5') => "kp5",
653 KeyCode::Char('6') => "kp6",
654 KeyCode::Char('7') => "kp7",
655 KeyCode::Char('8') => "kp8",
656 KeyCode::Char('9') => "kp9",
657 _ => return None,
658 })
659}
660
661impl fmt::Display for KeyCode {
662 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
663 match *self {
664 KeyCode::Char('+') => f.write_str("plus"),
665 KeyCode::Char('-') => f.write_str("minus"),
666 KeyCode::Char('=') => f.write_str("equals"),
667 KeyCode::Char(c) => write!(f, "{c}"),
668 KeyCode::F(n) => write!(f, "f{n}"),
669 KeyCode::Up => f.write_str("up"),
670 KeyCode::Down => f.write_str("down"),
671 KeyCode::Left => f.write_str("left"),
672 KeyCode::Right => f.write_str("right"),
673 KeyCode::Home => f.write_str("home"),
674 KeyCode::End => f.write_str("end"),
675 KeyCode::Begin => f.write_str("begin"),
676 KeyCode::Find => f.write_str("find"),
677 KeyCode::Select => f.write_str("select"),
678 KeyCode::PageUp => f.write_str("pageup"),
679 KeyCode::PageDown => f.write_str("pagedown"),
680 KeyCode::Backspace => f.write_str("backspace"),
681 KeyCode::Delete => f.write_str("delete"),
682 KeyCode::Insert => f.write_str("insert"),
683 KeyCode::Tab => f.write_str("tab"),
684 KeyCode::Enter => f.write_str("enter"),
685 KeyCode::Space => f.write_str("space"),
686 KeyCode::Escape => f.write_str("escape"),
687 KeyCode::CapsLock => f.write_str("capslock"),
688 KeyCode::ScrollLock => f.write_str("scrolllock"),
689 KeyCode::NumLock => f.write_str("numlock"),
690 KeyCode::PrintScreen => f.write_str("printscreen"),
691 KeyCode::Pause => f.write_str("pause"),
692 KeyCode::Menu => f.write_str("menu"),
693 KeyCode::MediaPlay => f.write_str("mediaplay"),
695 KeyCode::MediaPause => f.write_str("mediapause"),
696 KeyCode::MediaPlayPause => f.write_str("mediaplaypause"),
697 KeyCode::MediaReverse => f.write_str("mediareverse"),
698 KeyCode::MediaStop => f.write_str("mediastop"),
699 KeyCode::MediaRewind => f.write_str("mediarewind"),
700 KeyCode::MediaFastForward => f.write_str("mediafastforward"),
701 KeyCode::MediaNext => f.write_str("medianext"),
702 KeyCode::MediaPrev => f.write_str("mediaprev"),
703 KeyCode::MediaRecord => f.write_str("mediarecord"),
704 KeyCode::VolumeUp => f.write_str("volumeup"),
705 KeyCode::VolumeDown => f.write_str("volumedown"),
706 KeyCode::VolumeMute => f.write_str("volumemute"),
707 KeyCode::Shift => f.write_str("shift"),
709 KeyCode::Ctrl => f.write_str("ctrl"),
710 KeyCode::Alt => f.write_str("alt"),
711 KeyCode::Super => f.write_str("super"),
712 KeyCode::Hyper => f.write_str("hyper"),
713 KeyCode::Meta => f.write_str("meta"),
714 KeyCode::IsoLevel3Shift => f.write_str("isolevel3shift"),
715 KeyCode::IsoLevel5Shift => f.write_str("isolevel5shift"),
716 }
717 }
718}
719
720#[derive(Debug, Clone, PartialEq, Eq)]
726pub enum ParseKeyError {
727 Empty,
729 EmptyComponent,
734 UnknownModifier(String),
739 UnknownKey(String),
745 InvalidFunctionKey(String),
750}
751
752impl fmt::Display for ParseKeyError {
753 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
754 match self {
755 Self::Empty => f.write_str("empty key string"),
756 Self::EmptyComponent => f.write_str("empty `+`-separated component"),
757 Self::UnknownModifier(s) => write!(f, "unknown modifier: {s:?}"),
758 Self::UnknownKey(s) => write!(f, "unknown key name: {s:?}"),
759 Self::InvalidFunctionKey(s) => write!(f, "invalid function key: {s:?}"),
760 }
761 }
762}
763
764impl std::error::Error for ParseKeyError {}
765
766fn parse_modifier(token: &str) -> Result<KeyModifiers, ParseKeyError> {
767 let mods = if token.eq_ignore_ascii_case("ctrl") || token.eq_ignore_ascii_case("control") {
768 KeyModifiers::CTRL
769 } else if token.eq_ignore_ascii_case("alt")
770 || token.eq_ignore_ascii_case("opt")
771 || token.eq_ignore_ascii_case("option")
772 {
773 KeyModifiers::ALT
774 } else if token.eq_ignore_ascii_case("shift") {
775 KeyModifiers::SHIFT
776 } else if token.eq_ignore_ascii_case("super")
777 || token.eq_ignore_ascii_case("win")
778 || token.eq_ignore_ascii_case("cmd")
779 || token.eq_ignore_ascii_case("command")
780 {
781 KeyModifiers::SUPER
782 } else if token.eq_ignore_ascii_case("hyper") {
783 KeyModifiers::HYPER
784 } else if token.eq_ignore_ascii_case("meta") {
785 KeyModifiers::META
786 } else {
787 return Err(ParseKeyError::UnknownModifier(token.to_string()));
788 };
789 Ok(mods)
790}
791
792const KEY_KEYWORD_MAX_LEN: usize = 16;
799
800fn parse_key_code(token: &str) -> Result<KeyCode, ParseKeyError> {
801 let mut chars = token.chars();
807 if let Some(first) = chars.next()
808 && chars.next().is_none()
809 {
810 return Ok(KeyCode::Char(first));
811 }
812
813 if token.len() > KEY_KEYWORD_MAX_LEN || !token.is_ascii() {
819 return Err(ParseKeyError::UnknownKey(token.to_string()));
820 }
821 let mut buf = [0u8; KEY_KEYWORD_MAX_LEN];
822 for (i, b) in token.as_bytes().iter().enumerate() {
823 buf[i] = b.to_ascii_lowercase();
824 }
825 let lower = std::str::from_utf8(&buf[..token.len()])
826 .expect("ASCII lowercase of ASCII input is valid UTF-8");
827
828 if let Some(rest) = lower.strip_prefix('f')
830 && !rest.is_empty()
831 && rest.bytes().all(|c| c.is_ascii_digit())
832 {
833 let n: u8 = rest
834 .parse()
835 .map_err(|_| ParseKeyError::InvalidFunctionKey(token.to_string()))?;
836 return KeyCode::function(n)
837 .ok_or_else(|| ParseKeyError::InvalidFunctionKey(token.to_string()));
838 }
839
840 Ok(match lower {
841 "up" => KeyCode::Up,
843 "down" => KeyCode::Down,
844 "left" => KeyCode::Left,
845 "right" => KeyCode::Right,
846 "home" => KeyCode::Home,
847 "end" => KeyCode::End,
848 "begin" => KeyCode::Begin,
849 "find" => KeyCode::Find,
850 "select" => KeyCode::Select,
851 "pgup" | "pageup" => KeyCode::PageUp,
852 "pgdn" | "pgdown" | "pagedown" => KeyCode::PageDown,
853 "backspace" | "bs" => KeyCode::Backspace,
855 "delete" | "del" => KeyCode::Delete,
856 "insert" | "ins" => KeyCode::Insert,
857 "tab" => KeyCode::Tab,
858 "enter" | "return" | "ret" => KeyCode::Enter,
859 "space" | "spc" => KeyCode::Space,
861 "esc" | "escape" => KeyCode::Escape,
862 "capslock" => KeyCode::CapsLock,
863 "scrolllock" => KeyCode::ScrollLock,
864 "numlock" => KeyCode::NumLock,
865 "printscreen" | "prtsc" => KeyCode::PrintScreen,
866 "pause" => KeyCode::Pause,
867 "menu" => KeyCode::Menu,
868 "plus" => KeyCode::Char('+'),
874 "minus" | "dash" | "hyphen" => KeyCode::Char('-'),
875 "equals" | "equal" => KeyCode::Char('='),
876 "mediaplay" => KeyCode::MediaPlay,
878 "mediapause" => KeyCode::MediaPause,
879 "mediaplaypause" => KeyCode::MediaPlayPause,
880 "mediareverse" => KeyCode::MediaReverse,
881 "mediastop" => KeyCode::MediaStop,
882 "mediarewind" => KeyCode::MediaRewind,
883 "mediafastforward" => KeyCode::MediaFastForward,
884 "medianext" => KeyCode::MediaNext,
885 "mediaprev" => KeyCode::MediaPrev,
886 "mediarecord" => KeyCode::MediaRecord,
887 "volumeup" => KeyCode::VolumeUp,
888 "volumedown" => KeyCode::VolumeDown,
889 "volumemute" => KeyCode::VolumeMute,
890 "shift" => KeyCode::Shift,
892 "ctrl" | "control" => KeyCode::Ctrl,
893 "alt" | "opt" | "option" => KeyCode::Alt,
894 "super" | "win" | "cmd" | "command" => KeyCode::Super,
895 "hyper" => KeyCode::Hyper,
896 "meta" => KeyCode::Meta,
897 "isolevel3shift" => KeyCode::IsoLevel3Shift,
898 "isolevel5shift" => KeyCode::IsoLevel5Shift,
899 _ => return Err(ParseKeyError::UnknownKey(token.to_string())),
900 })
901}
902
903fn parse_key_identity(token: &str) -> Result<(KeyCode, Option<KeyLocation>), ParseKeyError> {
904 for (prefix, location) in [
905 ("kp", KeyLocation::Keypad),
906 ("left", KeyLocation::Left),
907 ("right", KeyLocation::Right),
908 ] {
909 if token
910 .get(..prefix.len())
911 .is_some_and(|s| s.eq_ignore_ascii_case(prefix))
912 {
913 let suffix = &token[prefix.len()..];
914 let code = if location == KeyLocation::Keypad {
915 match suffix.to_ascii_lowercase().as_str() {
916 "add" => Ok(KeyCode::Char('+')),
917 "subtract" => Ok(KeyCode::Char('-')),
918 "multiply" => Ok(KeyCode::Char('*')),
919 "divide" => Ok(KeyCode::Char('/')),
920 "decimal" => Ok(KeyCode::Char('.')),
921 "separator" => Ok(KeyCode::Char(',')),
922 _ => parse_key_code(suffix),
923 }
924 } else {
925 parse_key_code(suffix)
926 };
927 if let Ok(code) = code {
928 return Ok((code, Some(location)));
929 }
930 }
931 }
932 parse_key_code(token).map(|code| (code, None))
933}
934
935fn parse_key(s: &str) -> Result<(Key, Option<KeyLocation>), ParseKeyError> {
937 let s = s.trim();
938 if s.is_empty() {
939 return Err(ParseKeyError::Empty);
940 }
941
942 if s.chars().nth(1).is_none() {
946 let code = parse_key_code(s)?;
947 return Ok((Key::new(code, KeyModifiers::empty()).normalized(), None));
948 }
949
950 let (mod_part, key_part) = if let Some(head) = s.strip_suffix('+') {
958 match head.strip_suffix('+') {
959 Some(mods) => (mods, "+"),
960 None => return Err(ParseKeyError::EmptyComponent),
961 }
962 } else {
963 match s.rsplit_once('+') {
964 Some(("", _)) => return Err(ParseKeyError::EmptyComponent),
965 Some(parts) => parts,
966 None => ("", s),
967 }
968 };
969
970 if key_part.is_empty() {
971 return Err(ParseKeyError::EmptyComponent);
972 }
973
974 let mut modifiers = KeyModifiers::empty();
975 if !mod_part.is_empty() {
976 for tok in mod_part.split('+') {
977 if tok.is_empty() {
978 return Err(ParseKeyError::EmptyComponent);
979 }
980 modifiers |= parse_modifier(tok)?;
981 }
982 }
983
984 if key_part.eq_ignore_ascii_case("backtab") {
990 return Ok((
991 Key::new(KeyCode::Tab, modifiers | KeyModifiers::SHIFT).normalized(),
992 None,
993 ));
994 }
995
996 let (code, location) = parse_key_identity(key_part)?;
997 Ok((
998 Key {
999 location: location.unwrap_or_default(),
1000 ..Key::new(code, modifiers)
1001 }
1002 .normalized(),
1003 location,
1004 ))
1005}
1006
1007impl std::str::FromStr for Key {
1008 type Err = ParseKeyError;
1009
1010 fn from_str(s: &str) -> Result<Self, Self::Err> {
1011 parse_key(s).map(|(key, _)| key)
1012 }
1013}
1014
1015impl std::str::FromStr for KeyCode {
1016 type Err = ParseKeyError;
1017
1018 fn from_str(s: &str) -> Result<Self, Self::Err> {
1019 let s = s.trim();
1020 if s.is_empty() {
1021 return Err(ParseKeyError::Empty);
1022 }
1023 parse_key_code(s)
1024 }
1025}
1026
1027#[cfg(test)]
1028mod tests {
1029 use super::*;
1030
1031 #[test]
1032 fn test_key_display() {
1033 let k = Key::new(KeyCode::Char('a'), KeyModifiers::CTRL).normalized();
1034 assert_eq!(k.to_string(), "ctrl+a");
1035 }
1036
1037 #[test]
1038 fn test_key_display_function() {
1039 let k = Key::new(KeyCode::F(12), KeyModifiers::empty()).normalized();
1040 assert_eq!(k.to_string(), "f12");
1041 }
1042
1043 #[test]
1044 fn test_key_char() {
1045 let k = Key::new(KeyCode::Char('x'), KeyModifiers::empty()).normalized();
1046 assert_eq!(k.char(), Some('x'));
1047 }
1048
1049 #[test]
1050 fn test_key_char_special() {
1051 let k = Key::new(KeyCode::Enter, KeyModifiers::empty()).normalized();
1052 assert_eq!(k.char(), None);
1053 }
1054
1055 #[test]
1056 fn new_uppercase_ascii_lowers_code_and_adds_shift() {
1057 let k = Key::new(KeyCode::Char('A'), KeyModifiers::empty()).normalized();
1058 assert_eq!(k.code, KeyCode::Char('a'));
1059 assert_eq!(k.shifted_key, Some('A'));
1060 assert!(k.modifiers.contains(KeyModifiers::SHIFT));
1061 assert_eq!(k.text.as_deref(), Some("A"));
1062 }
1063
1064 #[test]
1065 fn new_uppercase_with_caps_lock_does_not_add_shift() {
1066 let k = Key::new(KeyCode::Char('A'), KeyModifiers::CAPS_LOCK).normalized();
1067 assert_eq!(k.code, KeyCode::Char('a'));
1068 assert_eq!(k.shifted_key, Some('A'));
1069 assert!(!k.modifiers.contains(KeyModifiers::SHIFT));
1070 assert!(k.modifiers.contains(KeyModifiers::CAPS_LOCK));
1071 assert_eq!(k.text.as_deref(), Some("A"));
1072 }
1073
1074 #[test]
1075 fn new_lowercase_with_shift_populates_shifted_key() {
1076 let k = Key::new(KeyCode::Char('a'), KeyModifiers::SHIFT).normalized();
1077 assert_eq!(k.code, KeyCode::Char('a'));
1078 assert_eq!(k.shifted_key, Some('A'));
1079 assert_eq!(k.text.as_deref(), Some("A"));
1080 }
1081
1082 #[test]
1083 fn shifted_key_does_not_pollute_text_without_shift() {
1084 let mut k = Key {
1089 code: KeyCode::Char('a'),
1090 location: KeyLocation::Standard,
1091 modifiers: KeyModifiers::empty(),
1092 repeat: false,
1093 text: None,
1094 shifted_key: Some('A'),
1095 base_key: None,
1096 };
1097 k.normalize();
1098 assert_eq!(k.text.as_deref(), Some("a"));
1099 let mut k = Key {
1101 code: KeyCode::Char('a'),
1102 location: KeyLocation::Standard,
1103 modifiers: KeyModifiers::SHIFT,
1104 repeat: false,
1105 text: None,
1106 shifted_key: Some('A'),
1107 base_key: None,
1108 };
1109 k.normalize();
1110 assert_eq!(k.text.as_deref(), Some("A"));
1111 }
1112
1113 #[test]
1114 fn caps_lock_shifts_cased_letters_only() {
1115 let mut k = Key {
1120 code: KeyCode::Char('2'),
1121 location: KeyLocation::Standard,
1122 modifiers: KeyModifiers::CAPS_LOCK,
1123 repeat: false,
1124 text: None,
1125 shifted_key: Some('@'),
1126 base_key: None,
1127 };
1128 k.normalize();
1129 assert_eq!(k.text.as_deref(), Some("2"));
1130
1131 let mut k = Key {
1133 code: KeyCode::Char('a'),
1134 location: KeyLocation::Standard,
1135 modifiers: KeyModifiers::CAPS_LOCK,
1136 repeat: false,
1137 text: None,
1138 shifted_key: Some('A'),
1139 base_key: None,
1140 };
1141 k.normalize();
1142 assert_eq!(k.text.as_deref(), Some("A"));
1143
1144 let mut k = Key {
1148 code: KeyCode::Char('ä'),
1149 location: KeyLocation::Standard,
1150 modifiers: KeyModifiers::CAPS_LOCK,
1151 repeat: false,
1152 text: None,
1153 shifted_key: Some('Ä'),
1154 base_key: None,
1155 };
1156 k.normalize();
1157 assert_eq!(k.text.as_deref(), Some("Ä"));
1158
1159 let mut k = Key {
1160 code: KeyCode::Char('д'),
1161 location: KeyLocation::Standard,
1162 modifiers: KeyModifiers::CAPS_LOCK,
1163 repeat: false,
1164 text: None,
1165 shifted_key: Some('Д'),
1166 base_key: None,
1167 };
1168 k.normalize();
1169 assert_eq!(k.text.as_deref(), Some("Д"));
1170
1171 let mut k = Key {
1173 code: KeyCode::Char('2'),
1174 location: KeyLocation::Standard,
1175 modifiers: KeyModifiers::SHIFT,
1176 repeat: false,
1177 text: None,
1178 shifted_key: Some('@'),
1179 base_key: None,
1180 };
1181 k.normalize();
1182 assert_eq!(k.text.as_deref(), Some("@"));
1183 }
1184
1185 #[test]
1186 fn new_lowercase_without_shift_populates_text() {
1187 let k = Key::new(KeyCode::Char('a'), KeyModifiers::empty()).normalized();
1188 assert_eq!(k.code, KeyCode::Char('a'));
1189 assert_eq!(k.shifted_key, None);
1190 assert!(k.modifiers.is_empty());
1191 assert_eq!(k.text.as_deref(), Some("a"));
1192 }
1193
1194 #[test]
1195 fn new_ctrl_uppercase_does_not_set_text() {
1196 let k = Key::new(KeyCode::Char('A'), KeyModifiers::CTRL).normalized();
1197 assert_eq!(k.code, KeyCode::Char('a'));
1198 assert_eq!(k.shifted_key, Some('A'));
1199 assert!(k.modifiers.contains(KeyModifiers::CTRL));
1200 assert!(k.modifiers.contains(KeyModifiers::SHIFT));
1201 assert!(k.text.is_none());
1202 }
1203
1204 #[test]
1205 fn new_ctrl_shift_lowercase_does_not_set_text() {
1206 let k = Key::new(KeyCode::Char('a'), KeyModifiers::CTRL | KeyModifiers::SHIFT).normalized();
1207 assert_eq!(k.code, KeyCode::Char('a'));
1208 assert_eq!(k.shifted_key, Some('A'));
1209 assert!(k.text.is_none());
1210 }
1211
1212 #[test]
1213 fn new_cyrillic_uppercase() {
1214 let k = Key::new(KeyCode::Char('Ц'), KeyModifiers::empty()).normalized();
1215 assert_eq!(k.code, KeyCode::Char('ц'));
1216 assert_eq!(k.shifted_key, Some('Ц'));
1217 assert!(k.modifiers.contains(KeyModifiers::SHIFT));
1218 assert_eq!(k.text.as_deref(), Some("Ц"));
1219 }
1220
1221 #[test]
1222 fn new_greek_lowercase_with_shift() {
1223 let k = Key::new(KeyCode::Char('α'), KeyModifiers::SHIFT).normalized();
1224 assert_eq!(k.code, KeyCode::Char('α'));
1225 assert_eq!(k.shifted_key, Some('Α'));
1226 assert_eq!(k.text.as_deref(), Some("Α"));
1227 }
1228
1229 #[test]
1230 fn new_multi_codepoint_lower_left_alone() {
1231 let k = Key::new(KeyCode::Char('İ'), KeyModifiers::empty()).normalized();
1233 assert_eq!(k.code, KeyCode::Char('İ'));
1234 assert_eq!(k.shifted_key, None);
1235 assert!(k.modifiers.is_empty());
1236 assert_eq!(k.text.as_deref(), Some("İ"));
1238 }
1239
1240 #[test]
1241 fn new_titlecase_digraph_left_alone() {
1242 let k = Key::new(KeyCode::Char('Dž'), KeyModifiers::empty()).normalized();
1244 assert_eq!(k.code, KeyCode::Char('Dž'));
1245 assert_eq!(k.shifted_key, None);
1246 assert_eq!(k.text.as_deref(), Some("Dž"));
1247 }
1248
1249 #[test]
1250 fn new_digit_with_shift_keeps_digit_text() {
1251 let k = Key::new(KeyCode::Char('1'), KeyModifiers::SHIFT).normalized();
1253 assert_eq!(k.code, KeyCode::Char('1'));
1254 assert_eq!(k.shifted_key, None);
1255 assert!(k.modifiers.contains(KeyModifiers::SHIFT));
1256 assert_eq!(k.text.as_deref(), Some("1"));
1257 }
1258
1259 #[test]
1260 fn new_non_char_no_text() {
1261 let k = Key::new(KeyCode::Enter, KeyModifiers::SHIFT).normalized();
1262 assert_eq!(k.code, KeyCode::Enter);
1263 assert_eq!(k.shifted_key, None);
1264 assert!(k.text.is_none());
1265 }
1266
1267 #[test]
1268 fn new_space_populates_text() {
1269 let k = Key::new(KeyCode::Space, KeyModifiers::empty()).normalized();
1270 assert_eq!(k.code, KeyCode::Space);
1271 assert_eq!(k.text.as_deref(), Some(" "));
1272 }
1273
1274 #[test]
1275 fn new_space_with_ctrl_no_text() {
1276 let k = Key::new(KeyCode::Space, KeyModifiers::CTRL).normalized();
1277 assert_eq!(k.code, KeyCode::Space);
1278 assert!(k.text.is_none());
1279 }
1280
1281 #[test]
1282 fn eq_ignores_informational_fields() {
1283 let bare = Key::new(KeyCode::Char('a'), KeyModifiers::SHIFT).normalized();
1284 assert!(!bare.repeat);
1285 let mut decorated = Key::new(KeyCode::Char('a'), KeyModifiers::SHIFT).normalized();
1286 decorated.repeat = true;
1287 decorated.text = Some("custom".to_string());
1288 decorated.shifted_key = Some('Z');
1289 decorated.base_key = Some('q');
1290 assert_eq!(bare, decorated);
1291 assert!(decorated.normalized().repeat);
1292 }
1293
1294 #[test]
1295 fn hash_ignores_informational_fields() {
1296 use std::collections::HashMap;
1297 let mut map: HashMap<Key, &'static str> = HashMap::new();
1298 map.insert(
1299 Key::new(KeyCode::Char('a'), KeyModifiers::CTRL).normalized(),
1300 "ctrl-a",
1301 );
1302
1303 let mut lookup = Key::new(KeyCode::Char('a'), KeyModifiers::CTRL).normalized();
1304 lookup.repeat = true;
1305 lookup.text = Some("ignored".to_string());
1306 lookup.shifted_key = Some('X');
1307 assert_eq!(map.get(&lookup), Some(&"ctrl-a"));
1308 }
1309
1310 #[test]
1311 fn eq_distinguishes_code_and_modifiers() {
1312 let a = Key::new(KeyCode::Char('a'), KeyModifiers::empty()).normalized();
1313 let ctrl_a = Key::new(KeyCode::Char('a'), KeyModifiers::CTRL).normalized();
1314 let b = Key::new(KeyCode::Char('b'), KeyModifiers::empty()).normalized();
1315 assert_ne!(a, ctrl_a);
1316 assert_ne!(a, b);
1317 }
1318
1319 #[test]
1320 fn location_is_part_of_exact_identity_and_hashing() {
1321 use std::collections::hash_map::DefaultHasher;
1322 use std::hash::{Hash, Hasher};
1323
1324 let standard = Key::new(KeyCode::Enter, KeyModifiers::CTRL);
1325 let hash = |key: &Key| {
1326 let mut hasher = DefaultHasher::new();
1327 key.hash(&mut hasher);
1328 hasher.finish()
1329 };
1330 let mut keys = std::collections::HashSet::new();
1331 for location in [
1332 KeyLocation::Standard,
1333 KeyLocation::Left,
1334 KeyLocation::Right,
1335 KeyLocation::Keypad,
1336 ] {
1337 let key = Key {
1338 location,
1339 ..standard.clone()
1340 };
1341 let informational = Key {
1342 repeat: true,
1343 text: Some("ignored".into()),
1344 shifted_key: Some('X'),
1345 base_key: Some('y'),
1346 ..key.clone()
1347 };
1348 assert_eq!(key, informational);
1349 assert_eq!(hash(&key), hash(&informational));
1350 if location != KeyLocation::Standard {
1351 assert_ne!(key, standard);
1352 assert_ne!(hash(&key), hash(&standard));
1353 }
1354 assert!(keys.insert(key));
1355 }
1356 }
1357
1358 #[test]
1359 fn normalization_preserves_location_and_supplied_metadata() {
1360 let key = Key {
1361 location: KeyLocation::Keypad,
1362 repeat: true,
1363 text: Some("layout".into()),
1364 shifted_key: Some('@'),
1365 base_key: Some('q'),
1366 ..Key::new(KeyCode::Char('A'), KeyModifiers::NUM_LOCK)
1367 }
1368 .normalized();
1369 assert_eq!(key.code, KeyCode::Char('a'));
1370 assert_eq!(key.location, KeyLocation::Keypad);
1371 assert_eq!(key.modifiers, KeyModifiers::SHIFT | KeyModifiers::NUM_LOCK);
1372 assert!(key.repeat);
1373 assert_eq!(key.text.as_deref(), Some("layout"));
1374 assert_eq!(key.shifted_key, Some('@'));
1375 assert_eq!(key.base_key, Some('q'));
1376
1377 let digit = Key {
1378 location: KeyLocation::Keypad,
1379 ..Key::new(KeyCode::Char('1'), KeyModifiers::NUM_LOCK)
1380 }
1381 .normalized();
1382 assert_eq!(digit.text.as_deref(), Some("1"));
1383 }
1384
1385 #[test]
1386 fn retained_modifier_bits_survive_construction_and_normalization() {
1387 use std::collections::hash_map::DefaultHasher;
1388 use std::hash::{Hash, Hasher};
1389
1390 let modifiers = KeyModifiers::from_bits_retain(u16::MAX);
1391 let key = Key {
1392 location: KeyLocation::Keypad,
1393 ..Key::new(KeyCode::Enter, modifiers)
1394 }
1395 .normalized();
1396 assert_eq!(key.modifiers.bits(), u16::MAX);
1397 let known = Key {
1398 location: KeyLocation::Keypad,
1399 ..Key::new(KeyCode::Enter, KeyModifiers::all())
1400 };
1401 assert_ne!(key, known);
1402 let mut actual = DefaultHasher::new();
1403 key.hash(&mut actual);
1404 let mut expected = DefaultHasher::new();
1405 known.hash(&mut expected);
1406 assert_ne!(actual.finish(), expected.finish());
1407 }
1408
1409 #[test]
1410 fn location_names_compose_with_modifiers() {
1411 for (binding, component) in [
1412 ("standard+enter", "standard"),
1413 ("ctrl+standard+enter", "standard"),
1414 ("left+ctrl", "left"),
1415 ("right+alt", "right"),
1416 ("keypad+0", "keypad"),
1417 ("ctrl+left+alt", "left"),
1418 ("keypad+kpenter", "keypad"),
1419 ] {
1420 assert_eq!(
1421 binding.parse::<Key>(),
1422 Err(ParseKeyError::UnknownModifier(component.into())),
1423 "{binding}"
1424 );
1425 }
1426 for (binding, canonical) in [
1427 ("leftctrl", "leftctrl"),
1428 ("rightalt", "rightalt"),
1429 ("kp1", "kp1"),
1430 ("shift+ctrl+kpf1", "ctrl+shift+kpf1"),
1431 ("ctrl+kpadd", "ctrl+kpadd"),
1432 ("shift+alt+lefttab", "alt+shift+lefttab"),
1433 ("rightA", "shift+righta"),
1434 ("kpspace", "kpspace"),
1435 ("KPDECIMAL", "kpdecimal"),
1436 ("kpbegin", "kpbegin"),
1437 ("kpseparator", "kpseparator"),
1438 ("kpmultiply", "kpmultiply"),
1439 ("kpdivide", "kpdivide"),
1440 ("kpequal", "kpequal"),
1441 ] {
1442 assert_eq!(parse(binding).to_string(), canonical, "{binding}");
1443 assert_eq!(parse(binding), parse(canonical), "{binding}");
1444 }
1445 assert_eq!(parse_key("enter").unwrap().1, None);
1446 assert_eq!(parse_key("kpenter").unwrap().1, Some(KeyLocation::Keypad));
1447 }
1448
1449 #[test]
1450 fn keycode_parsing_keeps_logical_identity_only() {
1451 for code in [
1452 KeyCode::Begin,
1453 KeyCode::Shift,
1454 KeyCode::Ctrl,
1455 KeyCode::Alt,
1456 KeyCode::Super,
1457 KeyCode::Hyper,
1458 KeyCode::Meta,
1459 ] {
1460 assert_eq!(code.to_string().parse::<KeyCode>().unwrap(), code);
1461 assert_eq!(parse(&code.to_string()).location, KeyLocation::Standard);
1462 }
1463 for name in [
1464 "kpenter",
1465 "kp1",
1466 "kpadd",
1467 "kpdecimal",
1468 "kpbegin",
1469 "leftctrl",
1470 "rightalt",
1471 "leftenter",
1472 "standard+enter",
1473 "kpf1",
1474 ] {
1475 assert!(name.parse::<KeyCode>().is_err(), "{name}");
1476 }
1477 }
1478
1479 #[test]
1480 fn display_canonical_mod_order() {
1481 let mods = KeyModifiers::META
1485 | KeyModifiers::HYPER
1486 | KeyModifiers::SUPER
1487 | KeyModifiers::SHIFT
1488 | KeyModifiers::ALT
1489 | KeyModifiers::CTRL;
1490 let k = Key {
1491 code: KeyCode::Char('a'),
1492 location: KeyLocation::Standard,
1493 modifiers: mods,
1494 repeat: true,
1495 text: None,
1496 shifted_key: None,
1497 base_key: None,
1498 };
1499 assert_eq!(k.to_string(), "ctrl+alt+shift+super+hyper+meta+a");
1500 }
1501
1502 #[test]
1503 fn display_omits_lock_state() {
1504 let k = Key {
1505 code: KeyCode::Char('a'),
1506 location: KeyLocation::Standard,
1507 modifiers: KeyModifiers::CAPS_LOCK | KeyModifiers::NUM_LOCK | KeyModifiers::SCROLL_LOCK,
1508 repeat: false,
1509 text: None,
1510 shifted_key: None,
1511 base_key: None,
1512 };
1513 assert_eq!(k.to_string(), "a");
1514 }
1515
1516 #[test]
1517 fn display_lock_state_combined_with_binding_mod() {
1518 let k = Key {
1521 code: KeyCode::Char('a'),
1522 location: KeyLocation::Standard,
1523 modifiers: KeyModifiers::CTRL | KeyModifiers::CAPS_LOCK,
1524 repeat: false,
1525 text: None,
1526 shifted_key: None,
1527 base_key: None,
1528 };
1529 assert_eq!(k.to_string(), "ctrl+a");
1530 }
1531
1532 #[test]
1533 fn display_char_plus_uses_word() {
1534 let k = Key::new(KeyCode::Char('+'), KeyModifiers::CTRL).normalized();
1535 assert_eq!(k.to_string(), "ctrl+plus");
1536 }
1537
1538 #[test]
1539 fn display_modifier_key_variants() {
1540 let k = Key {
1541 location: KeyLocation::Left,
1542 ..Key::new(KeyCode::Shift, KeyModifiers::empty())
1543 }
1544 .normalized();
1545 assert_eq!(k.to_string(), "leftshift");
1546 let k = Key {
1547 location: KeyLocation::Right,
1548 ..Key::new(KeyCode::Alt, KeyModifiers::empty())
1549 }
1550 .normalized();
1551 assert_eq!(k.to_string(), "rightalt");
1552 let k = Key::new(KeyCode::IsoLevel3Shift, KeyModifiers::empty()).normalized();
1553 assert_eq!(k.to_string(), "isolevel3shift");
1554 }
1555
1556 #[test]
1557 fn display_uses_full_words() {
1558 assert_eq!(
1561 Key::new(KeyCode::PageUp, KeyModifiers::empty())
1562 .normalized()
1563 .to_string(),
1564 "pageup"
1565 );
1566 assert_eq!(
1567 Key::new(KeyCode::PageDown, KeyModifiers::empty())
1568 .normalized()
1569 .to_string(),
1570 "pagedown"
1571 );
1572 assert_eq!(
1573 Key::new(KeyCode::Escape, KeyModifiers::empty())
1574 .normalized()
1575 .to_string(),
1576 "escape"
1577 );
1578 assert_eq!(parse("pgup"), parse("pageup"));
1581 assert_eq!(parse("pgdn"), parse("pagedown"));
1582 assert_eq!(parse("pgdown"), parse("pagedown"));
1583 assert_eq!(parse("esc"), parse("escape"));
1584 }
1585
1586 #[test]
1587 fn display_keypad_variants() {
1588 assert_eq!(
1589 Key {
1590 location: KeyLocation::Keypad,
1591 ..Key::new(KeyCode::Char('0'), KeyModifiers::empty())
1592 }
1593 .normalized()
1594 .to_string(),
1595 "kp0"
1596 );
1597 assert_eq!(
1598 Key {
1599 location: KeyLocation::Keypad,
1600 ..Key::new(KeyCode::Enter, KeyModifiers::empty())
1601 }
1602 .normalized()
1603 .to_string(),
1604 "kpenter"
1605 );
1606 assert_eq!(
1607 Key {
1608 location: KeyLocation::Keypad,
1609 ..Key::new(KeyCode::PageUp, KeyModifiers::empty())
1610 }
1611 .normalized()
1612 .to_string(),
1613 "kppageup"
1614 );
1615 }
1616
1617 #[test]
1618 fn display_media_variants() {
1619 assert_eq!(
1620 Key::new(KeyCode::MediaPlayPause, KeyModifiers::empty())
1621 .normalized()
1622 .to_string(),
1623 "mediaplaypause"
1624 );
1625 assert_eq!(
1626 Key::new(KeyCode::VolumeMute, KeyModifiers::empty())
1627 .normalized()
1628 .to_string(),
1629 "volumemute"
1630 );
1631 }
1632
1633 fn parse(s: &str) -> Key {
1636 s.parse::<Key>()
1637 .unwrap_or_else(|e| panic!("parse {s:?}: {e}"))
1638 }
1639
1640 #[test]
1641 fn fromstr_single_char_lowercase() {
1642 let k = parse("a");
1643 assert_eq!(k.code, KeyCode::Char('a'));
1644 assert!(k.modifiers.is_empty());
1645 }
1646
1647 #[test]
1648 fn fromstr_uppercase_char_canonicalizes_to_shift_lowercase() {
1649 assert_eq!(
1652 "A".parse::<Key>().unwrap(),
1653 "shift+a".parse::<Key>().unwrap()
1654 );
1655 }
1656
1657 #[test]
1658 fn fromstr_modifier_order_independent() {
1659 let canonical = parse("ctrl+shift+a");
1660 assert_eq!(parse("shift+ctrl+a"), canonical);
1661 assert_eq!(parse("Shift+Ctrl+a"), canonical);
1662 }
1663
1664 #[test]
1665 fn fromstr_function_keys() {
1666 assert_eq!(parse("f1").code, KeyCode::F(1));
1667 assert_eq!(parse("f12").code, KeyCode::F(12));
1668 assert_eq!(parse("f24").code, KeyCode::F(24));
1669 assert_eq!(parse("f35").code, KeyCode::F(35));
1670 }
1671
1672 #[test]
1673 fn fromstr_function_key_out_of_range() {
1674 assert!(matches!(
1675 "f0".parse::<Key>(),
1676 Err(ParseKeyError::InvalidFunctionKey(_))
1677 ));
1678 assert!(matches!(
1679 "f36".parse::<Key>(),
1680 Err(ParseKeyError::InvalidFunctionKey(_))
1681 ));
1682 }
1683
1684 #[test]
1685 fn keycode_function_validates_range() {
1686 assert_eq!(KeyCode::function(1), Some(KeyCode::F(1)));
1687 assert_eq!(
1688 KeyCode::function(KeyCode::FUNCTION_KEY_MAX),
1689 Some(KeyCode::F(KeyCode::FUNCTION_KEY_MAX))
1690 );
1691 assert_eq!(KeyCode::function(0), None);
1692 assert_eq!(KeyCode::function(KeyCode::FUNCTION_KEY_MAX + 1), None);
1693 }
1694
1695 #[test]
1696 fn fromstr_named_keys() {
1697 assert_eq!(parse("esc").code, KeyCode::Escape);
1698 assert_eq!(parse("escape").code, KeyCode::Escape);
1699 assert_eq!(parse("pgup").code, KeyCode::PageUp);
1700 assert_eq!(parse("pageup").code, KeyCode::PageUp);
1701 assert_eq!(parse("enter").code, KeyCode::Enter);
1702 assert_eq!(parse("return").code, KeyCode::Enter);
1703 assert_eq!(parse("ret").code, KeyCode::Enter);
1704 assert_eq!(parse("backspace").code, KeyCode::Backspace);
1705 assert_eq!(parse("bs").code, KeyCode::Backspace);
1706 let backtab = parse("backtab");
1710 assert_eq!(backtab.code, KeyCode::Tab);
1711 assert_eq!(backtab.modifiers, KeyModifiers::SHIFT);
1712 assert_eq!(parse("shift+tab"), backtab);
1713 assert_eq!(backtab.to_string(), "shift+tab");
1715 let alt_backtab = parse("alt+backtab");
1716 assert_eq!(alt_backtab.code, KeyCode::Tab);
1717 assert_eq!(
1718 alt_backtab.modifiers,
1719 KeyModifiers::SHIFT | KeyModifiers::ALT
1720 );
1721 assert_eq!(parse("alt+shift+tab"), alt_backtab);
1722 assert_eq!(alt_backtab.to_string(), "alt+shift+tab");
1723 assert_eq!(parse("delete").code, KeyCode::Delete);
1724 assert_eq!(parse("del").code, KeyCode::Delete);
1725 assert_eq!(parse("space").code, KeyCode::Space);
1726 }
1727
1728 #[test]
1729 fn fromstr_modifier_aliases() {
1730 assert_eq!(parse("control+a"), parse("ctrl+a"));
1731 assert_eq!(parse("option+a"), parse("alt+a"));
1732 assert_eq!(parse("cmd+a"), parse("super+a"));
1733 assert_eq!(parse("command+a"), parse("super+a"));
1734 assert_eq!(parse("win+a"), parse("super+a"));
1735 }
1736
1737 #[test]
1738 fn fromstr_plus_alias_round_trips() {
1739 let k = parse("ctrl+plus");
1740 assert_eq!(k.code, KeyCode::Char('+'));
1741 assert!(k.modifiers.contains(KeyModifiers::CTRL));
1742 assert_eq!(k.to_string(), "ctrl+plus");
1743 }
1744
1745 #[test]
1746 fn fromstr_keypad_and_media() {
1747 for (name, code) in [
1748 ("kp0", KeyCode::Char('0')),
1749 ("kp1", KeyCode::Char('1')),
1750 ("kp2", KeyCode::Char('2')),
1751 ("kp3", KeyCode::Char('3')),
1752 ("kp4", KeyCode::Char('4')),
1753 ("kp5", KeyCode::Char('5')),
1754 ("kp6", KeyCode::Char('6')),
1755 ("kp7", KeyCode::Char('7')),
1756 ("kp8", KeyCode::Char('8')),
1757 ("kp9", KeyCode::Char('9')),
1758 ("kpenter", KeyCode::Enter),
1759 ("kpadd", KeyCode::Char('+')),
1760 ("kpsubtract", KeyCode::Char('-')),
1761 ("kpmultiply", KeyCode::Char('*')),
1762 ("kpdivide", KeyCode::Char('/')),
1763 ("kpdecimal", KeyCode::Char('.')),
1764 ("kpequal", KeyCode::Char('=')),
1765 ("kpseparator", KeyCode::Char(',')),
1766 ("kpleft", KeyCode::Left),
1767 ("kpright", KeyCode::Right),
1768 ("kpup", KeyCode::Up),
1769 ("kpdown", KeyCode::Down),
1770 ("kppageup", KeyCode::PageUp),
1771 ("kppagedown", KeyCode::PageDown),
1772 ("kphome", KeyCode::Home),
1773 ("kpend", KeyCode::End),
1774 ("kpinsert", KeyCode::Insert),
1775 ("kpdelete", KeyCode::Delete),
1776 ("kpbegin", KeyCode::Begin),
1777 ] {
1778 let key = parse(name);
1779 assert_eq!(
1780 key,
1781 Key {
1782 location: KeyLocation::Keypad,
1783 ..Key::new(code, KeyModifiers::empty())
1784 },
1785 "{name}"
1786 );
1787 assert_eq!(key.to_string(), name);
1788 assert!(name.parse::<KeyCode>().is_err(), "{name}");
1789 }
1790 assert_eq!(parse("mediaplaypause").code, KeyCode::MediaPlayPause);
1791 assert_eq!(parse("volumemute").code, KeyCode::VolumeMute);
1792 }
1793
1794 #[test]
1795 fn fromstr_modifier_keys_themselves() {
1796 assert_eq!(
1797 parse("leftshift"),
1798 Key {
1799 location: KeyLocation::Left,
1800 ..Key::new(KeyCode::Shift, KeyModifiers::empty())
1801 }
1802 );
1803 assert_eq!(
1804 parse("rightalt"),
1805 Key {
1806 location: KeyLocation::Right,
1807 ..Key::new(KeyCode::Alt, KeyModifiers::empty())
1808 }
1809 );
1810 assert_eq!(parse("isolevel3shift").code, KeyCode::IsoLevel3Shift);
1811 }
1812
1813 #[test]
1814 fn fromstr_unicode_char() {
1815 assert_eq!(parse("ц").code, KeyCode::Char('ц'));
1816 assert_eq!(parse("α").code, KeyCode::Char('α'));
1817 }
1818
1819 #[test]
1820 fn fromstr_trims_whitespace() {
1821 assert_eq!(parse(" ctrl+a "), parse("ctrl+a"));
1822 }
1823
1824 #[test]
1825 fn fromstr_errors() {
1826 assert_eq!("".parse::<Key>(), Err(ParseKeyError::Empty));
1827 assert_eq!(" ".parse::<Key>(), Err(ParseKeyError::Empty));
1828 assert_eq!("ctrl+".parse::<Key>(), Err(ParseKeyError::EmptyComponent));
1829 assert_eq!("ctrl++a".parse::<Key>(), Err(ParseKeyError::EmptyComponent));
1832 assert_eq!("+a".parse::<Key>(), Err(ParseKeyError::EmptyComponent));
1834 assert_eq!("+ctrl+a".parse::<Key>(), Err(ParseKeyError::EmptyComponent));
1835 assert!(matches!(
1836 "foo+a".parse::<Key>(),
1837 Err(ParseKeyError::UnknownModifier(_))
1838 ));
1839 assert!(matches!(
1840 "ctrl+xyz".parse::<Key>(),
1841 Err(ParseKeyError::UnknownKey(_))
1842 ));
1843 }
1844
1845 #[test]
1846 fn fromstr_keycode_only() {
1847 let kc: KeyCode = "esc".parse().unwrap();
1848 assert_eq!(kc, KeyCode::Escape);
1849 let kc: KeyCode = "f5".parse().unwrap();
1850 assert_eq!(kc, KeyCode::F(5));
1851 assert!(matches!(
1852 "ctrl+a".parse::<KeyCode>(),
1853 Err(ParseKeyError::UnknownKey(_))
1854 ));
1855 }
1856
1857 #[test]
1858 fn fromstr_literal_plus() {
1859 assert_eq!(parse("+").code, KeyCode::Char('+'));
1861 assert_eq!(parse("plus").code, KeyCode::Char('+'));
1863 assert_eq!(
1865 parse("ctrl++"),
1866 Key::new(KeyCode::Char('+'), KeyModifiers::CTRL).normalized()
1867 );
1868 assert_eq!(parse("ctrl++"), parse("ctrl+plus"));
1870 }
1871
1872 #[test]
1873 fn fromstr_literal_symbols() {
1874 assert_eq!(parse("-").code, KeyCode::Char('-'));
1876 assert_eq!(parse("*").code, KeyCode::Char('*'));
1877 assert_eq!(parse("/").code, KeyCode::Char('/'));
1878 assert_eq!(parse("=").code, KeyCode::Char('='));
1879 assert_eq!(parse("[").code, KeyCode::Char('['));
1880 assert_eq!(parse("ctrl+-").code, KeyCode::Char('-'));
1881 assert_eq!(parse("ctrl+/").code, KeyCode::Char('/'));
1882 assert_eq!(parse("alt+[").code, KeyCode::Char('['));
1883 }
1884
1885 #[test]
1886 fn fromstr_minus_aliases() {
1887 assert_eq!(parse("minus").code, KeyCode::Char('-'));
1888 assert_eq!(parse("dash").code, KeyCode::Char('-'));
1889 assert_eq!(parse("hyphen").code, KeyCode::Char('-'));
1890 assert_eq!(parse("ctrl+minus"), parse("ctrl+-"));
1891 assert_eq!(parse("ctrl+dash"), parse("ctrl+-"));
1892 }
1893
1894 #[test]
1895 fn fromstr_equals_aliases() {
1896 assert_eq!(parse("equals").code, KeyCode::Char('='));
1897 assert_eq!(parse("equal").code, KeyCode::Char('='));
1898 assert_eq!(parse("ctrl+equals"), parse("ctrl+="));
1899 }
1900
1901 #[test]
1902 fn display_uses_named_symbol_forms() {
1903 assert_eq!(
1904 Key::new(KeyCode::Char('-'), KeyModifiers::empty())
1905 .normalized()
1906 .to_string(),
1907 "minus"
1908 );
1909 assert_eq!(
1910 Key::new(KeyCode::Char('='), KeyModifiers::empty())
1911 .normalized()
1912 .to_string(),
1913 "equals"
1914 );
1915 assert_eq!(
1916 Key::new(KeyCode::Char('+'), KeyModifiers::empty())
1917 .normalized()
1918 .to_string(),
1919 "plus"
1920 );
1921 assert_eq!(
1922 Key::new(KeyCode::Char('-'), KeyModifiers::CTRL)
1923 .normalized()
1924 .to_string(),
1925 "ctrl+minus"
1926 );
1927 }
1928
1929 #[test]
1930 fn fromstr_rejects_hyphen_aliases() {
1931 assert!(matches!(
1934 "page-up".parse::<Key>(),
1935 Err(ParseKeyError::UnknownKey(_))
1936 ));
1937 assert!(matches!(
1938 "back-tab".parse::<Key>(),
1939 Err(ParseKeyError::UnknownKey(_))
1940 ));
1941 assert!(matches!(
1942 "caps-lock".parse::<Key>(),
1943 Err(ParseKeyError::UnknownKey(_))
1944 ));
1945 }
1946
1947 #[test]
1948 fn display_kp_pageup_long_form() {
1949 assert_eq!(
1950 Key {
1951 location: KeyLocation::Keypad,
1952 ..Key::new(KeyCode::PageDown, KeyModifiers::empty())
1953 }
1954 .normalized()
1955 .to_string(),
1956 "kppagedown"
1957 );
1958 assert_eq!(parse("kppgup"), parse("kppageup"));
1960 assert_eq!(parse("kppgdn"), parse("kppagedown"));
1961 }
1962
1963 #[test]
1964 fn display_fromstr_roundtrip_named_variants() {
1965 let cases: &[(KeyCode, KeyModifiers)] = &[
1968 (KeyCode::Char('a'), KeyModifiers::empty()),
1969 (KeyCode::Char('a'), KeyModifiers::CTRL),
1970 (KeyCode::Char('a'), KeyModifiers::CTRL | KeyModifiers::ALT),
1971 (
1972 KeyCode::Char('a'),
1973 KeyModifiers::CTRL
1974 | KeyModifiers::ALT
1975 | KeyModifiers::SHIFT
1976 | KeyModifiers::SUPER
1977 | KeyModifiers::HYPER
1978 | KeyModifiers::META,
1979 ),
1980 (KeyCode::Char('-'), KeyModifiers::CTRL),
1981 (KeyCode::Char('='), KeyModifiers::CTRL),
1982 (KeyCode::Char('-'), KeyModifiers::empty()),
1983 (KeyCode::Char('='), KeyModifiers::empty()),
1984 (KeyCode::Char('ц'), KeyModifiers::empty()),
1985 (KeyCode::F(1), KeyModifiers::empty()),
1986 (KeyCode::F(24), KeyModifiers::CTRL),
1987 (KeyCode::F(35), KeyModifiers::empty()),
1988 (KeyCode::Up, KeyModifiers::empty()),
1989 (KeyCode::Down, KeyModifiers::SHIFT),
1990 (KeyCode::Left, KeyModifiers::ALT),
1991 (KeyCode::Right, KeyModifiers::CTRL),
1992 (KeyCode::Home, KeyModifiers::empty()),
1993 (KeyCode::End, KeyModifiers::empty()),
1994 (KeyCode::PageUp, KeyModifiers::empty()),
1995 (KeyCode::PageDown, KeyModifiers::empty()),
1996 (KeyCode::Backspace, KeyModifiers::empty()),
1997 (KeyCode::Delete, KeyModifiers::empty()),
1998 (KeyCode::Insert, KeyModifiers::empty()),
1999 (KeyCode::Tab, KeyModifiers::empty()),
2000 (KeyCode::Tab, KeyModifiers::SHIFT),
2001 (KeyCode::Enter, KeyModifiers::empty()),
2002 (KeyCode::Space, KeyModifiers::empty()),
2003 (KeyCode::Escape, KeyModifiers::empty()),
2004 (KeyCode::CapsLock, KeyModifiers::empty()),
2005 (KeyCode::ScrollLock, KeyModifiers::empty()),
2006 (KeyCode::NumLock, KeyModifiers::empty()),
2007 (KeyCode::PrintScreen, KeyModifiers::empty()),
2008 (KeyCode::Pause, KeyModifiers::empty()),
2009 (KeyCode::Menu, KeyModifiers::empty()),
2010 (KeyCode::Char('0'), KeyModifiers::empty()),
2011 (KeyCode::Char('9'), KeyModifiers::empty()),
2012 (KeyCode::Begin, KeyModifiers::empty()),
2013 (KeyCode::MediaPlay, KeyModifiers::empty()),
2014 (KeyCode::MediaPlayPause, KeyModifiers::empty()),
2015 (KeyCode::VolumeUp, KeyModifiers::empty()),
2016 (KeyCode::VolumeMute, KeyModifiers::empty()),
2017 (KeyCode::Shift, KeyModifiers::empty()),
2018 (KeyCode::Ctrl, KeyModifiers::empty()),
2019 (KeyCode::Alt, KeyModifiers::empty()),
2020 (KeyCode::Super, KeyModifiers::empty()),
2021 (KeyCode::Hyper, KeyModifiers::empty()),
2022 (KeyCode::Meta, KeyModifiers::empty()),
2023 (KeyCode::IsoLevel3Shift, KeyModifiers::empty()),
2024 (KeyCode::IsoLevel5Shift, KeyModifiers::empty()),
2025 ];
2026 for (code, mods) in cases {
2027 for location in [
2028 KeyLocation::Standard,
2029 KeyLocation::Left,
2030 KeyLocation::Right,
2031 KeyLocation::Keypad,
2032 ] {
2033 let k = Key {
2034 location,
2035 ..Key::new(*code, *mods)
2036 }
2037 .normalized();
2038 let s = k.to_string();
2039 let parsed = s.parse::<Key>().unwrap_or_else(|e| {
2040 panic!("failed to parse {s:?} (from {code:?}, {mods:?}): {e}")
2041 });
2042 assert_eq!(parsed, k, "round-trip mismatch for {s:?}");
2043 }
2044 }
2045 }
2046
2047 #[test]
2048 fn eq_ignores_lock_state() {
2049 let plain = Key::new(KeyCode::Char('c'), KeyModifiers::CTRL).normalized();
2050 let with_caps = Key::new(
2051 KeyCode::Char('c'),
2052 KeyModifiers::CTRL | KeyModifiers::CAPS_LOCK,
2053 )
2054 .normalized();
2055 let with_num = Key::new(
2056 KeyCode::Char('c'),
2057 KeyModifiers::CTRL | KeyModifiers::NUM_LOCK,
2058 )
2059 .normalized();
2060 let with_scroll = Key::new(
2061 KeyCode::Char('c'),
2062 KeyModifiers::CTRL | KeyModifiers::SCROLL_LOCK,
2063 )
2064 .normalized();
2065 let with_all_locks = Key::new(
2066 KeyCode::Char('c'),
2067 KeyModifiers::CTRL | KeyModifiers::LOCK_MASK,
2068 )
2069 .normalized();
2070 assert_eq!(plain, with_caps);
2071 assert_eq!(plain, with_num);
2072 assert_eq!(plain, with_scroll);
2073 assert_eq!(plain, with_all_locks);
2074 }
2075
2076 #[test]
2077 fn hash_ignores_lock_state() {
2078 use std::collections::hash_map::DefaultHasher;
2079 use std::hash::{Hash, Hasher};
2080 fn h(k: &Key) -> u64 {
2081 let mut s = DefaultHasher::new();
2082 k.hash(&mut s);
2083 s.finish()
2084 }
2085 let plain = Key::new(KeyCode::Char('c'), KeyModifiers::CTRL).normalized();
2086 let with_locks = Key::new(
2087 KeyCode::Char('c'),
2088 KeyModifiers::CTRL | KeyModifiers::LOCK_MASK,
2089 )
2090 .normalized();
2091 assert_eq!(h(&plain), h(&with_locks));
2092 }
2093
2094 #[test]
2095 fn eq_still_distinguishes_binding_modifiers() {
2096 let ctrl = Key::new(KeyCode::Char('c'), KeyModifiers::CTRL).normalized();
2097 let alt = Key::new(KeyCode::Char('c'), KeyModifiers::ALT).normalized();
2098 let ctrl_alt =
2099 Key::new(KeyCode::Char('c'), KeyModifiers::CTRL | KeyModifiers::ALT).normalized();
2100 assert_ne!(ctrl, alt);
2101 assert_ne!(ctrl, ctrl_alt);
2102 }
2103
2104 #[test]
2105 fn parsed_key_equals_key_with_lock_state() {
2106 let parsed: Key = "ctrl+c".parse().expect("parse");
2107 let live = Key::new(
2108 KeyCode::Char('c'),
2109 KeyModifiers::CTRL | KeyModifiers::CAPS_LOCK,
2110 )
2111 .normalized();
2112 assert_eq!(parsed, live);
2113 }
2114
2115 #[test]
2116 fn matches_simple_char() {
2117 let k = Key::new(KeyCode::Char('a'), KeyModifiers::empty()).normalized();
2118 assert!(k.matches("a"));
2119 assert!(!k.matches("b"));
2120 }
2121
2122 #[test]
2123 fn matches_general_bindings_ignore_location() {
2124 for pattern in ["enter", "left", "begin", "ctrl+1", "alt+plus", "ctrl"] {
2125 for location in [
2126 KeyLocation::Standard,
2127 KeyLocation::Left,
2128 KeyLocation::Right,
2129 KeyLocation::Keypad,
2130 ] {
2131 let mut key = parse(pattern);
2132 key.location = location;
2133 assert!(key.matches(pattern), "{pattern}: {location:?}");
2134 }
2135 }
2136 let digit = Key {
2137 location: KeyLocation::Keypad,
2138 ..Key::new(KeyCode::Char('1'), KeyModifiers::CTRL)
2139 };
2140 assert!(digit.matches("ctrl+1"));
2141 assert!(!digit.matches("1"));
2142 assert!(!digit.matches("alt+1"));
2143 assert!(!digit.matches("ctrl+shift+1"));
2144 }
2145
2146 #[test]
2147 fn matches_explicit_location_requires_exact_identity() {
2148 let keypad = parse("ctrl+kpenter");
2149 assert!(keypad.matches("ctrl+kpenter"));
2150 assert!(!keypad.matches("ctrl+keypad+enter"));
2151 assert!(keypad.matches_any(["rightctrl", "ctrl+kpenter"]));
2152 assert!(!keypad.matches("ctrl+standard+enter"));
2153 assert!(!keypad.matches("kpenter"));
2154 let standard = parse("enter");
2155 assert!(!standard.matches("standard+enter"));
2156 assert!(!standard.matches("kpenter"));
2157 let right = parse("rightctrl");
2158 assert!(right.matches("ctrl"));
2159 assert!(right.matches("rightctrl"));
2160 assert!(!right.matches("right+ctrl"));
2161 assert!(!right.matches("leftctrl"));
2162
2163 for mut key in [
2164 Key::new(KeyCode::Enter, KeyModifiers::empty()),
2165 Key {
2166 location: KeyLocation::Keypad,
2167 ..Key::new(KeyCode::Char('x'), KeyModifiers::empty())
2168 },
2169 ] {
2170 key.text = Some("kpenter".into());
2171 assert!(!key.matches("kpenter"));
2172 }
2173 }
2174
2175 #[test]
2176 fn matches_modifier_combo() {
2177 let k = Key::new(KeyCode::Char('c'), KeyModifiers::CTRL).normalized();
2178 assert!(k.matches("ctrl+c"));
2179 assert!(!k.matches("alt+c"));
2180 assert!(!k.matches("ctrl+x"));
2181 }
2182
2183 #[test]
2184 fn matches_named_key() {
2185 for repeat in [false, true] {
2186 let mut k = Key::new(KeyCode::F(5), KeyModifiers::SHIFT).normalized();
2187 k.repeat = repeat;
2188 assert!(k.matches("shift+f5"));
2189 assert!(!k.matches("f5"));
2190 }
2191 }
2192
2193 #[test]
2194 fn matches_ignores_lock_state() {
2195 let k = Key::new(
2196 KeyCode::Char('a'),
2197 KeyModifiers::CTRL | KeyModifiers::CAPS_LOCK | KeyModifiers::NUM_LOCK,
2198 )
2199 .normalized();
2200 assert!(k.matches("ctrl+a"));
2201 }
2202
2203 #[test]
2204 fn matches_invalid_pattern_is_false() {
2205 let k = Key::new(KeyCode::Char('a'), KeyModifiers::empty()).normalized();
2206 assert!(!k.matches(""));
2207 assert!(!k.matches("frob+nargle"));
2208 assert!(!k.matches("ctrl+"));
2209 }
2210
2211 #[test]
2212 fn matches_any_basic() {
2213 let k = Key::new(KeyCode::Escape, KeyModifiers::empty()).normalized();
2214 assert!(k.matches_any(["esc", "ctrl+c", "q"]));
2215 assert!(!k.matches_any(["enter", "tab"]));
2216 }
2217
2218 #[test]
2219 fn matches_any_empty_is_false() {
2220 let k = Key::new(KeyCode::Char('a'), KeyModifiers::empty()).normalized();
2221 let none: [&str; 0] = [];
2222 assert!(!k.matches_any(none));
2223 }
2224
2225 #[test]
2226 fn matches_any_accepts_string_and_str() {
2227 let k = Key::new(KeyCode::Char('q'), KeyModifiers::empty()).normalized();
2228 let owned: Vec<String> = vec!["esc".into(), "q".into()];
2229 assert!(k.matches_any(&owned));
2230 let borrowed: Vec<&str> = vec!["esc", "q"];
2231 assert!(k.matches_any(borrowed));
2232 }
2233
2234 #[test]
2235 fn matches_is_case_sensitive_for_letters() {
2236 let plain_g = Key::new(KeyCode::Char('g'), KeyModifiers::empty()).normalized();
2238 assert!(plain_g.matches("g"));
2239 assert!(!plain_g.matches("G"));
2240 assert!(!plain_g.matches("shift+g"));
2241
2242 let big_g = Key::new(KeyCode::Char('G'), KeyModifiers::empty()).normalized();
2245 assert_eq!(big_g.code, KeyCode::Char('g'));
2246 assert!(big_g.modifiers.contains(KeyModifiers::SHIFT));
2247 assert!(big_g.matches("G"));
2248 assert!(big_g.matches("shift+g"));
2249 assert!(!big_g.matches("g"));
2250 }
2251
2252 #[test]
2253 fn matches_modifier_combos_with_letters() {
2254 let ctrl_g = Key::new(KeyCode::Char('g'), KeyModifiers::CTRL).normalized();
2255 assert!(ctrl_g.matches("ctrl+g"));
2256 assert!(!ctrl_g.matches("ctrl+G"));
2257 assert!(!ctrl_g.matches("ctrl+shift+g"));
2258 assert!(!ctrl_g.matches("g"));
2259 assert!(!ctrl_g.matches("alt+g"));
2260 }
2261
2262 #[test]
2263 fn matches_text_first_layout_independent() {
2264 for repeat in [false, true] {
2267 let mut shift_1 = Key::new(KeyCode::Char('1'), KeyModifiers::SHIFT).normalized();
2268 shift_1.repeat = repeat;
2269 shift_1.text = Some("!".to_string());
2270 assert!(shift_1.matches("!"));
2271 assert!(shift_1.matches("shift+1"));
2273 }
2274 }
2275
2276 #[test]
2277 fn matches_text_first_respects_binding_modifiers() {
2278 let mut shift_1 = Key::new(KeyCode::Char('1'), KeyModifiers::SHIFT).normalized();
2281 shift_1.text = Some("!".to_string());
2282 assert!(!shift_1.matches("ctrl+!"));
2283 }
2284
2285 #[test]
2286 fn matches_text_first_handles_layout_glyph() {
2287 let mut shift_slash = Key::new(KeyCode::Char('/'), KeyModifiers::SHIFT).normalized();
2289 shift_slash.location = KeyLocation::Keypad;
2290 shift_slash.text = Some("?".to_string());
2291 assert!(shift_slash.matches("?"));
2292 assert!(shift_slash.matches("shift+/"));
2293 assert!(!shift_slash.matches("kp?"));
2294 assert!(!shift_slash.matches("ctrl+?"));
2295 assert_ne!(shift_slash, parse("shift+/"));
2296 }
2297}