Skip to main content

uncurses/event/
key.rs

1//! Key payloads, modifiers, display forms, and binding parsing.
2//!
3//! ## Purpose
4//!
5//! This module defines the key identity used by [`Event::KeyPress`]
6//! and [`Event::KeyRelease`]. It normalizes terminal wire encodings
7//! into a stable [`Key`] value suitable for
8//! equality, hashing, display, and string-based shortcut matching.
9//!
10//! ```text
11//! terminal encoding ──▶ KeyCode + KeyModifiers ──▶ normalize ──▶ Key
12//!       │                         │
13//!       │                         └─ lock-state bits are informational
14//!       └─ optional text / shifted / base glyph metadata
15//! ```
16//!
17//! ## Key types
18//!
19//! * [`KeyCode`] identifies the logical key: a character, navigation key,
20//!   function key, media key, or modifier key.
21//! * [`KeyLocation`] records a reported side or keypad location.
22//! * [`KeyModifiers`] separates binding modifiers (`Ctrl`, `Alt`, `Shift`,
23//!   `Super`, `Hyper`, `Meta`) from lock states.
24//! * [`Key`] combines a code, location, and modifiers with optional text metadata.
25//!   Public fields expose its identity and metadata.
26//! * [`ParseKeyError`] reports why a user-facing binding string did not parse.
27//!
28//! ## Matching and display
29//!
30//! [`Key`] equality and hashing use the code, location, and binding modifiers. Text,
31//! repeat status, alternate-key metadata, and lock-state bits are ignored.
32//! Bindings stay stable across terminal protocols and keyboard latch states.
33//! [`Key::matches`] accepts bindings such as `"ctrl+c"` or `"alt+plus"` at any
34//! location. Explicit location spellings such as `"kpenter"` or `"rightctrl"`
35//! require that location. General bindings also match exact produced text.
36//!
37//! ## Gotchas
38//!
39//! Uppercase character codes normalize to lowercase plus [`KeyModifiers::SHIFT`]
40//! unless [`KeyModifiers::CAPS_LOCK`] explains the case. Bare legacy encodings
41//! cannot always recover the physical base key for shifted symbols or
42//! Ctrl+Shift letters; richer encodings may provide [`Key::text`],
43//! [`Key::shifted_key`], or [`Key::base_key`] for that extra context.
44use bitflags::bitflags;
45use std::fmt;
46
47bitflags! {
48    /// Keyboard modifier flags.
49    ///
50    /// The low eight bits follow Kitty's modifier ordering. CSI keyboard input
51    /// uses this ordering consistently, including legacy functional keys and
52    /// modifyOtherKeys. Xterm's Meta bit is intentionally interpreted as Super.
53    ///
54    /// Modifiers split into two categories:
55    ///
56    /// * **Binding modifiers** — `SHIFT`, `ALT`, `CTRL`, `SUPER`,
57    ///   `HYPER`, `META`. These participate in [`Key`] equality and
58    ///   in [`Key::matches`].
59    /// * **Lock states** — `CAPS_LOCK`, `NUM_LOCK`, `SCROLL_LOCK`,
60    ///   collectively [`LOCK_MASK`](Self::LOCK_MASK). These report
61    ///   the keyboard latch and are *never* binding modifiers: they
62    ///   are ignored by `Key` equality, hashing, [`Key::matches`],
63    ///   and the [`Display`](fmt::Display) form. Hosts that need to
64    ///   inspect lock state can mask `modifiers` with `LOCK_MASK`.
65    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
66    pub struct KeyModifiers: u16 {
67        /// Shift key modifier.
68        const SHIFT       = 0b0000_0000_0000_0001;
69        /// Alt key modifier.
70        const ALT         = 0b0000_0000_0000_0010;
71        /// Control key modifier.
72        const CTRL        = 0b0000_0000_0000_0100;
73        /// Super key modifier.
74        const SUPER       = 0b0000_0000_0000_1000;
75        /// Hyper key modifier.
76        const HYPER       = 0b0000_0000_0001_0000;
77        /// Meta key modifier.
78        const META        = 0b0000_0000_0010_0000;
79        /// Caps Lock state.
80        const CAPS_LOCK   = 0b0000_0000_0100_0000;
81        /// Num Lock state.
82        const NUM_LOCK    = 0b0000_0000_1000_0000;
83        /// Scroll Lock state.
84        const SCROLL_LOCK = 0b0000_0001_0000_0000;
85
86        /// Mask of lock-state bits (`CAPS_LOCK | NUM_LOCK | SCROLL_LOCK`).
87        ///
88        /// Lock states report the current keyboard latch and are *not*
89        /// binding modifiers: they are ignored by [`Key`] equality,
90        /// hashing, [`Key::matches`], and [`Display`](fmt::Display).
91        /// Callers that need to inspect or compare lock state can mask
92        /// the modifier set with this constant.
93        const LOCK_MASK   = Self::CAPS_LOCK.bits()
94                          | Self::NUM_LOCK.bits()
95                          | Self::SCROLL_LOCK.bits();
96    }
97}
98
99/// The reported location of a key.
100///
101/// Location is independent of the logical [`KeyCode`]. Protocols that do not
102/// report a location use [`Standard`](Self::Standard).
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
104pub enum KeyLocation {
105    /// The standard location, or a location that the input does not report.
106    ///
107    /// This value does not guarantee a physical position.
108    #[default]
109    Standard,
110    /// The left member of a key pair.
111    Left,
112    /// The right member of a key pair.
113    Right,
114    /// A key on the numeric keypad.
115    Keypad,
116}
117
118/// A key event.
119///
120/// Equality and hashing use the logical [`code`](Self::code), reported
121/// [`location`](Self::location), and [`modifiers`](Self::modifiers) other than
122/// [`lock states`](KeyModifiers::LOCK_MASK). They ignore repeat status,
123/// associated text, and alternate layout metadata.
124///
125/// For string-based binding matching that additionally folds letter
126/// case and consults [`text`](Self::text) for layout-specific glyphs,
127/// see [`matches`](Self::matches) and [`matches_any`](Self::matches_any).
128#[derive(Debug, Clone)]
129pub struct Key {
130    /// The key code (which key was pressed).
131    pub code: KeyCode,
132    /// The reported key location.
133    pub location: KeyLocation,
134    /// Active modifiers.
135    pub modifiers: KeyModifiers,
136    /// Whether the input protocol identifies this press as an auto-repeat.
137    ///
138    /// `false` means the input did not identify a repeat. Decoder-generated
139    /// releases always use `false`. Normalization preserves this field.
140    /// Win32 records use `false` for the first occurrence and `true` for
141    /// additional key-down occurrences in the same record.
142    /// Equality, hashing, shortcut matching, and display use the key identity
143    /// independently of this field.
144    pub repeat: bool,
145    /// Associated text (from Kitty protocol or composed input).
146    ///
147    /// Informational; ignored by `==` and `Hash`. Consulted by
148    /// [`Key::matches`] when it carries a layout-specific glyph that
149    /// differs from `code` (for example `"!"` for `shift+1` on a US
150    /// layout), enabling layout-independent string bindings.
151    pub text: Option<String>,
152    /// Shifted-layer codepoint (Kitty Report-Alternate-Keys).
153    ///
154    /// Informational; ignored by `==` and `Hash`.
155    pub shifted_key: Option<char>,
156    /// Base-layout codepoint (Kitty Report-Alternate-Keys).
157    ///
158    /// Informational; ignored by `==` and `Hash`.
159    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    /// Construct a [`Key`] with the given code and modifiers.
185    ///
186    /// This is a transparent constructor: no canonicalization is
187    /// performed. Optional fields (`text`, `shifted_key`, `base_key`)
188    /// start empty, [`repeat`](Self::repeat) starts `false`, and
189    /// [`location`](Self::location) starts [`KeyLocation::Standard`].
190    /// All supplied modifier bits remain intact.
191    /// Decoder paths populate the optional fields as
192    /// needed and then chain [`Key::normalized`] (or call
193    /// [`Key::normalize`] in place) to apply the canonical identity
194    /// rules (case folding, printable text auto-population).
195    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    /// Consume `self` and return the canonical form. The recommended
208    /// way to build a canonical key in expression position
209    /// (`Key::new(code, mods).normalized()`); see [`Key::normalize`]
210    /// for the in-place equivalent and the full list of rules.
211    pub fn normalized(mut self) -> Self {
212        self.normalize();
213        self
214    }
215
216    /// Return the character if this is a simple character key.
217    /// [`KeyCode::Space`] reports `' '`; other named keys report `None`.
218    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    /// Test whether this key matches a string pattern.
227    ///
228    /// A pattern with an explicit location compares exact key identity.
229    /// For example, `"kpenter"` requires keypad Enter, and `"rightctrl"` requires
230    /// right Ctrl. Check [`location`](Self::location) to require a standard key.
231    /// Modifier chords combine with location names: `"ctrl+kpenter"`.
232    ///
233    /// A pattern without an explicit location matches in two steps:
234    ///
235    /// 1. If this key carries a [`text`](Self::text) value and it
236    ///    equals `pattern` byte-for-byte, the match succeeds. Lets
237    ///    bindings be written as the produced glyph (`"?"`, `"!"`,
238    ///    `"@"`) and hit any keystroke that resolves to that text,
239    ///    independent of keyboard layout. Note that `text` reflects
240    ///    the user-perceived character, so `CapsLock` *can* shift
241    ///    the matched form (pressing `g` with CapsLock on yields
242    ///    `text == "G"` and matches the pattern `"G"`).
243    /// 2. Otherwise, `pattern` is parsed as a [`Key`] with the same
244    ///    grammar as [`FromStr`](std::str::FromStr) (for example
245    ///    `"ctrl+c"`, `"shift+f1"`, `"alt+plus"`) and compared with
246    ///    [`PartialEq`], except that location is ignored. Thus `"enter"`
247    ///    accepts standard and keypad Enter, and `"ctrl"` accepts either Ctrl.
248    ///    Lock state (`CapsLock`, `NumLock`,
249    ///    `ScrollLock`) is ignored by `==`, so step 2 is layout-
250    ///    sensitive but lock-insensitive. Matching is otherwise
251    ///    case-sensitive — `"g"` and `"G"` are distinct (`"G"` is a
252    ///    synonym for `"shift+g"`).
253    ///
254    /// Returns `false` for any pattern that fails to parse and has
255    /// no matching `text`; invalid patterns never panic.
256    ///
257    /// # Examples
258    ///
259    /// ```
260    /// use uncurses::event::{Key, KeyCode, KeyModifiers};
261    ///
262    /// // Case-sensitive: g and G are distinct (vim-style).
263    /// let plain_g = Key::new(KeyCode::Char('g'), KeyModifiers::empty()).normalized();
264    /// let big_g   = Key::new(KeyCode::Char('G'), KeyModifiers::empty()).normalized();
265    /// assert!(plain_g.matches("g"));
266    /// assert!(!plain_g.matches("G"));
267    /// assert!(big_g.matches("G"));
268    /// assert!(big_g.matches("shift+g")); // "G" and "shift+g" are synonyms.
269    /// assert!(!big_g.matches("g"));
270    /// ```
271    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    /// Test whether this key matches any pattern in the iterator.
288    ///
289    /// Equivalent to calling [`matches`](Self::matches) for each
290    /// pattern and stopping at the first hit. Accepts any iterable
291    /// yielding string-like items, including arrays, slices, and
292    /// vectors.
293    ///
294    /// # Examples
295    ///
296    /// ```
297    /// use uncurses::event::{Key, KeyCode, KeyModifiers};
298    ///
299    /// let key = Key::new(KeyCode::Char('c'), KeyModifiers::CTRL).normalized();
300    /// assert!(key.matches_any(["esc", "ctrl+c", "q"]));
301    /// assert!(!key.matches_any(["esc", "q"]));
302    /// ```
303    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    /// Apply the canonical identity rules in place. Idempotent.
312    ///
313    /// Decoder paths construct keys via [`Key::new`], populate optional
314    /// fields, and then call this method (or chain
315    /// [`Key::normalized`]) to produce the canonical form. The rules
316    /// applied are:
317    ///
318    /// - Case folding for printable `Char` codes: uppercase chars are
319    ///   lowercased and the original is stored in `shifted_key`;
320    ///   `SHIFT` is added only when `CAPS_LOCK` is not set (with
321    ///   CapsLock the case change is attributed to the lock state, not
322    ///   a Shift press).
323    /// - Printable text auto-population when `text` is empty and the
324    ///   modifier set is a subset of `SHIFT | CAPS_LOCK | NUM_LOCK`.
325    ///
326    /// These rules apply to printable keypad characters too. Normalization
327    /// preserves location, repeat metadata, and supplied text and layout values.
328    pub fn normalize(&mut self) {
329        // Case folding for printable Char codes.
330        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        // Text auto-population for printable input.
362        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                // The shifted glyph is only what the user perceives
368                // when the shifted layer is actually engaged. Decoders
369                // may populate `shifted_key` regardless of whether
370                // Shift is actually held, so we must not blindly use
371                // it here.
372                //
373                // CapsLock only acts as a shifted layer for cased
374                // letters. `Key::new` normalizes uppercase to lowercase
375                // + SHIFT before we get here, so `is_lowercase()` is
376                // the right test: it covers every Unicode cased letter
377                // (ASCII, Cyrillic, Greek, Latin-Extended, …) and
378                // excludes digits, symbols, and uncased scripts where
379                // CapsLock has no effect on common layouts.
380                //
381                // Whether Shift cancels CapsLock on letters is a host
382                // convention (some platforms cancel, most OR); the
383                // library takes the OR-side that matches the majority.
384                // Hosts wanting cancellation should populate `text`
385                // directly from the resolved character.
386                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/// Logical identity of a key, before modifiers are considered.
412///
413/// `KeyCode` is intentionally broader than printable text: it covers named
414/// navigation/editing keys, media keys, and modifier-key
415/// identities reported by modern keyboard protocols. Combine it with
416/// [`KeyModifiers`] in a [`Key`] to represent a full key event.
417///
418/// Use [`KeyCode::function`] when constructing function keys from untrusted
419/// numeric input; the raw [`KeyCode::F`] variant is public for pattern matching
420/// and decoder construction.
421#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
422pub enum KeyCode {
423    /// A Unicode character key.
424    ///
425    /// Printable spaces are normally represented as [`KeyCode::Space`] for
426    /// cross-decoder stability. Other printable and non-control Unicode scalar
427    /// values use this variant after [`Key::normalize`] applies case folding.
428    Char(char),
429    /// Function key. Valid range is `1..=35` (xterm goes to F20,
430    /// kitty extends to F35). Construct via [`KeyCode::function`] for
431    /// a checked builder; the bare variant is `pub` so decoders can
432    /// emit literals, but downstream code matching on `F(n)` should
433    /// treat values outside the valid range as bugs.
434    F(u8),
435    /// Legacy VT220 Find key, distinct from Home. Only emitted when the
436    /// decoder is configured to recognize the legacy Find key.
437    Find,
438    /// Legacy VT220 Select key, distinct from End. Only emitted when the
439    /// decoder is configured to recognize the legacy Select key.
440    Select,
441    // Navigation
442    /// Up arrow key.
443    Up,
444    /// Down arrow key.
445    Down,
446    /// Left arrow key.
447    Left,
448    /// Right arrow key.
449    Right,
450    /// Home key.
451    Home,
452    /// End key.
453    End,
454    /// Begin key.
455    Begin,
456    /// Page Up key.
457    PageUp,
458    /// Page Down key.
459    PageDown,
460    // Editing
461    /// Backspace key.
462    Backspace,
463    /// Delete key.
464    Delete,
465    /// Insert key.
466    Insert,
467    /// Tab key.
468    Tab,
469    /// Enter key.
470    Enter,
471    // Whitespace
472    /// Space key.
473    ///
474    /// The space bar decodes to this variant, **not** [`KeyCode::Char(' ')`]
475    /// — match on `KeyCode::Space` (a `Char(' ')` arm never fires). It still
476    /// reports `text` of `" "`, so text entry via [`Key::text`] is unaffected.
477    /// Rust has no variant aliases; to treat both alike by character, use
478    /// [`Key::char`], which returns `Some(' ')` for `Space` and `Char(' ')`.
479    ///
480    /// [`KeyCode::Char(' ')`]: KeyCode::Char
481    Space,
482    // Special
483    /// Escape key.
484    Escape,
485    /// Caps Lock key.
486    CapsLock,
487    /// Scroll Lock key.
488    ScrollLock,
489    /// Num Lock key.
490    NumLock,
491    /// Print Screen key.
492    PrintScreen,
493    /// Pause key.
494    Pause,
495    /// Menu key.
496    Menu,
497    // Media
498    /// Media Play key.
499    MediaPlay,
500    /// Media Pause key.
501    MediaPause,
502    /// Media Play/Pause key.
503    MediaPlayPause,
504    /// Media Reverse key.
505    MediaReverse,
506    /// Media Stop key.
507    MediaStop,
508    /// Media Rewind key.
509    MediaRewind,
510    /// Media Fast Forward key.
511    MediaFastForward,
512    /// Media Next key.
513    MediaNext,
514    /// Media Previous key.
515    MediaPrev,
516    /// Media Record key.
517    MediaRecord,
518    /// Volume Up key.
519    VolumeUp,
520    /// Volume Down key.
521    VolumeDown,
522    /// Volume Mute key.
523    VolumeMute,
524    // Modifier keys (reported with Kitty protocol)
525    /// Shift key.
526    Shift,
527    /// Control key.
528    Ctrl,
529    /// Alt key.
530    Alt,
531    /// Super key.
532    Super,
533    /// Hyper key.
534    Hyper,
535    /// Meta key.
536    Meta,
537    /// ISO Level 3 Shift (typically AltGr).
538    IsoLevel3Shift,
539    /// ISO Level 5 Shift.
540    IsoLevel5Shift,
541}
542
543impl KeyCode {
544    /// Highest valid function-key index accepted by [`KeyCode::function`].
545    ///
546    /// Function keys are represented as `F(1)` through `F(35)`. Values outside
547    /// that range are not produced by the checked constructor.
548    pub const FUNCTION_KEY_MAX: u8 = 35;
549
550    /// Construct a checked function-key code.
551    ///
552    /// Returns `Some(KeyCode::F(n))` when `n` is in
553    /// `1..=KeyCode::FUNCTION_KEY_MAX`; returns `None` for `0` or values above
554    /// the supported range. This function is useful when decoding or accepting
555    /// user input that may contain an invalid function-key number. It never
556    /// panics.
557    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
566/// Formats the key as its canonical binding spelling: a modifier prefix
567/// (`ctrl+`, `alt+`, `shift+`, `super+`, `hyper+`, `meta+`) followed by the
568/// [`KeyCode`] name, for example `"ctrl+c"`, `"shift+f1"`, or `"space"`.
569///
570/// Location prefixes attach to the key name, as in `"leftctrl"`, `"rightalt"`,
571/// `"kp0"`, and `"kpf1"`. Modifier chords use `"+"`, as in `"ctrl+kp0"`.
572///
573/// This is the inverse of [`FromStr`](std::str::FromStr): every string it
574/// produces parses back to an equal `Key`. It renders the structural key
575/// identity only and intentionally ignores the informational
576/// [`text`](Self::text), [`shifted_key`](Self::shifted_key), and
577/// [`base_key`](Self::base_key) fields, along with lock state
578/// (`CapsLock`/`NumLock`/`ScrollLock`). It therefore always spells the space
579/// bar as `"space"` (never `" "`), and composed or IME input is shown by its
580/// `code`, not its produced glyph.
581///
582/// For the user-perceived character that was typed, use
583/// [`char`](Self::char) or read [`text`](Self::text) directly; for
584/// layout-aware string matching that consults `text`, use
585/// [`matches`](Self::matches).
586impl fmt::Display for Key {
587    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
588        let mods = self.modifiers;
589        // Canonical order: ctrl, alt, shift, super, hyper, meta. Lock
590        // states (Caps/Num/Scroll) are intentionally omitted — they are
591        // session state, not binding modifiers.
592        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            // Media
694            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            // Modifier keys
708            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/// Error produced when parsing a [`Key`] or [`KeyCode`] from a binding string.
721///
722/// Parsing is used by [`Key::matches`], [`std::str::FromStr`] for [`Key`], and
723/// [`std::str::FromStr`] for [`KeyCode`]. The variants retain the offending
724/// token where useful so configuration UIs can report actionable messages.
725#[derive(Debug, Clone, PartialEq, Eq)]
726pub enum ParseKeyError {
727    /// Input was empty or whitespace-only.
728    Empty,
729    /// A `+`-separated component was empty.
730    ///
731    /// Examples include `"ctrl++a"`, `"ctrl+"`, and strings with a leading
732    /// separator such as `"+a"`.
733    EmptyComponent,
734    /// A modifier token was not recognized.
735    ///
736    /// The contained string is the exact modifier component that failed to
737    /// parse, before any case normalization beyond comparison.
738    UnknownModifier(String),
739    /// The terminal key token was not recognized.
740    ///
741    /// The contained string is the key component after modifiers have been
742    /// split off. Single-character tokens are accepted as [`KeyCode::Char`], so
743    /// this usually indicates an unknown named key.
744    UnknownKey(String),
745    /// A function-key token (`f<n>`) had an out-of-range index.
746    ///
747    /// Valid function keys are `f1` through `f35`, matching
748    /// [`KeyCode::FUNCTION_KEY_MAX`].
749    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
792/// Maximum byte length of any recognized key-code keyword. The
793/// longest spellings (`isolevel3shift`, `mediafastforward`) are 14
794/// and 16 bytes respectively, so anything longer than this cap cannot
795/// match a known keyword and parsing can bail out without further
796/// work. The buffer in [`parse_key_code`] is sized to this value so
797/// the ASCII-lowercase conversion stays on the stack.
798const KEY_KEYWORD_MAX_LEN: usize = 16;
799
800fn parse_key_code(token: &str) -> Result<KeyCode, ParseKeyError> {
801    // Single character: treat as Char (case preserved so `Key::new`
802    // can canonicalize uppercase into shift+lowercase). Includes `+`
803    // — the modifier-separator handling in `Key::from_str` passes
804    // the literal `+` through to this function as a single-char
805    // token.
806    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    // All recognized keywords are ASCII and fit in KEY_KEYWORD_MAX_LEN
814    // bytes. Tokens longer than that cannot match — bail to the
815    // unknown-key error without touching the allocator. Tokens
816    // containing non-ASCII bytes also can't match a keyword; fall
817    // through to the same error.
818    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    // Function key: f<n> where 1 <= n <= KeyCode::FUNCTION_KEY_MAX.
829    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        // Navigation
842        "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        // Editing
854        "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        // Whitespace / special
860        "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        // Punctuation aliases. `plus`, `minus`, and `equals` are the
869        // Display forms for `Char('+')`, `Char('-')`, and `Char('=')`
870        // respectively; the literal characters are also accepted via
871        // the single-character path. `dash` / `hyphen` and `equal` are
872        // additional spellings for the same two keys.
873        "plus" => KeyCode::Char('+'),
874        "minus" | "dash" | "hyphen" => KeyCode::Char('-'),
875        "equals" | "equal" => KeyCode::Char('='),
876        // Media
877        "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        // Modifier keys
891        "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
935// Keep explicit location separate from the default for binding consumers.
936fn 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    // Single-character input: treat as a literal key with no
943    // modifiers. This lets `+`, `-`, and any other single character
944    // round-trip cleanly without being misread as a `+`-separator.
945    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    // Split on the last `+` to separate modifiers from the key.
951    // The literal `+` key is spelled `plus` in Display output, but
952    // forms like `ctrl++` are also accepted: a trailing `++` means
953    // "the `+` key, with the preceding `+` as separator". A single
954    // trailing `+` with no preceding `+` is a dangling separator.
955    // A leading `+` (e.g. `"+a"`) is also a dangling separator
956    // since there is no modifier before it.
957    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    // `backtab` is a legacy spelling for `shift+tab`. Accept it as
985    // a key-part alias (also when combined with other modifiers,
986    // e.g. `alt+backtab`) even though there is no
987    // `KeyCode::BackTab` variant; the canonical form is the
988    // uniform `Tab + SHIFT`.
989    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        // A decoder may have pre-populated `shifted_key` from protocol
1085        // metadata (e.g. an alternate-key report) even on a bare key
1086        // press. `text` must reflect what the user actually typed,
1087        // which is the unshifted glyph, not the shifted one.
1088        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        // With Shift, the shifted glyph wins.
1100        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        // CapsLock does not produce the shifted glyph for digits or
1116        // symbols on any common layout. Even if a decoder populated
1117        // `shifted_key` for a non-letter key, `text` derived under
1118        // CapsLock alone must use the base glyph.
1119        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        // ASCII letters treat CapsLock as a shifted layer.
1132        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        // Non-ASCII cased letters (e.g. Cyrillic, Greek, Latin
1145        // Extended) participate too — the rule is "any cased letter",
1146        // not "ASCII only".
1147        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        // With Shift held, non-letters still take the shifted glyph.
1172        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        // 'İ' lowercases to "i\u{307}" — two codepoints; leave as-is.
1232        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        // Still printable input — text auto-populates with the original codepoint.
1237        assert_eq!(k.text.as_deref(), Some("İ"));
1238    }
1239
1240    #[test]
1241    fn new_titlecase_digraph_left_alone() {
1242        // 'Dž' is titlecase; is_uppercase() and is_lowercase() are both false.
1243        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        // '1' has no case variant; text auto-populates from the codepoint.
1252        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        // Construct with all six binding modifiers; expect canonical
1482        // ctrl, alt, shift, super, hyper, meta order regardless of
1483        // input insertion.
1484        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        // Real input: Ctrl+a while CapsLock is on. Caps drops from
1519        // Display so the binding string stays stable.
1520        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        // Display always emits the unabbreviated name; the short forms
1559        // (`pgup`, `pgdn`, `esc`, etc.) live only on the parse side.
1560        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        // Round-trip the short forms through Display and back to the
1579        // same Key.
1580        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    // --- FromStr ------------------------------------------------------
1634
1635    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        // Reuse Key::new's canonicalization so callers writing
1650        // "A" or "shift+a" end up at the same identity.
1651        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        // `backtab` is an input alias for `shift+tab`. There is no
1707        // dedicated `KeyCode::BackTab` variant. The alias also
1708        // composes with other modifiers.
1709        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        // Display formats this identity as `shift+tab`, never `backtab`.
1714        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        // `ctrl++a` still errors: the inner `+` produces an empty
1830        // modifier token. (`ctrl++` alone is the ctrl+literal-`+` form.)
1831        assert_eq!("ctrl++a".parse::<Key>(), Err(ParseKeyError::EmptyComponent));
1832        // Leading `+` is a dangling separator with no modifier before it.
1833        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        // Bare `+` is the literal key character (single-char shortcut).
1860        assert_eq!(parse("+").code, KeyCode::Char('+'));
1861        // `plus` alias parses identically.
1862        assert_eq!(parse("plus").code, KeyCode::Char('+'));
1863        // `ctrl++` is ctrl + the literal `+` key.
1864        assert_eq!(
1865            parse("ctrl++"),
1866            Key::new(KeyCode::Char('+'), KeyModifiers::CTRL).normalized()
1867        );
1868        // `ctrl+plus` resolves to the same Key.
1869        assert_eq!(parse("ctrl++"), parse("ctrl+plus"));
1870    }
1871
1872    #[test]
1873    fn fromstr_literal_symbols() {
1874        // Symbol literals are accepted via the single-char path.
1875        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        // Hyphenated key-name aliases are intentionally not accepted;
1932        // `+` is the only valid binding separator.
1933        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        // The short `kppgup`/`kppgdn` forms remain accepted on input.
1959        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        // Every variant emitted by Display must round-trip back to an
1966        // equal Key.
1967        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        // Vim-style: g and G are distinct bindings.
2237        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        // `Key::new(Char('G'), empty).normalized()` normalizes to Char('g') + SHIFT,
2243        // matching what a decoder emits for a shift+g press.
2244        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        // shift+1 on a US layout produces "!". Pattern "!" should hit
2265        // the key by its produced text even though the code is `1`.
2266        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            // The physical-key spelling still matches via strict equality.
2272            assert!(shift_1.matches("shift+1"));
2273        }
2274    }
2275
2276    #[test]
2277    fn matches_text_first_respects_binding_modifiers() {
2278        // ctrl+! must not silently match a key whose text happens to
2279        // be "!" — binding modifiers gate the text fallback.
2280        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        // shift+/ produces "?" on a US layout.
2288        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}