Skip to main content

Key

Struct Key 

Source
pub struct Key {
    pub code: KeyCode,
    pub modifiers: KeyModifiers,
    pub text: Option<String>,
    pub shifted_key: Option<char>,
    pub base_key: Option<char>,
}
Expand description

A key event.

Equality and hashing intentionally consider only code and the binding portion of modifiers: two keys representing the same press compare equal regardless of whether informational fields (text, shifted_key, base_key) were populated by the producing decoder, and regardless of lock state (CAPS_LOCK, NUM_LOCK, SCROLL_LOCK). This makes Key safe to use as a HashMap key for binding lookups across decoder paths and across keyboard latch states.

For string-based binding matching that additionally folds letter case and consults text for layout-specific glyphs, see matches and matches_any.

Fields§

§code: KeyCode

The key code (which key was pressed).

§modifiers: KeyModifiers

Active modifiers.

§text: Option<String>

Associated text (from Kitty protocol or composed input).

Informational; ignored by == and Hash. Consulted by Key::matches when it carries a layout-specific glyph that differs from code (for example "!" for shift+1 on a US layout), enabling layout-independent string bindings.

§shifted_key: Option<char>

Shifted-layer codepoint (Kitty Report-Alternate-Keys).

Informational; ignored by == and Hash.

§base_key: Option<char>

Base-layout codepoint (Kitty Report-Alternate-Keys).

Informational; ignored by == and Hash.

Implementations§

Source§

impl Key

Source

pub fn new(code: KeyCode, modifiers: KeyModifiers) -> Self

Construct a Key with the given code and modifiers.

This is a transparent constructor: no canonicalization is performed. Optional fields (text, shifted_key, base_key) start empty. Decoder paths populate the optional fields as needed and then chain Key::normalized (or call Key::normalize in place) to apply the canonical identity rules (case folding, printable text auto-population).

Source

pub fn normalized(self) -> Self

Consume self and return the canonical form. The recommended way to build a canonical key in expression position (Key::new(code, mods).normalized()); see Key::normalize for the in-place equivalent and the full list of rules.

Source

pub fn char(&self) -> Option<char>

Return the character if this is a simple character key. KeyCode::Space reports ' '; other named keys report None.

Source

pub fn matches(&self, pattern: &str) -> bool

Test whether this key matches a string pattern.

Matching is two-tier:

  1. If this key carries a text value and it equals pattern byte-for-byte, the match succeeds. Lets bindings be written as the produced glyph ("?", "!", "@") and hit any keystroke that resolves to that text, independent of keyboard layout. Note that text reflects the user-perceived character, so CapsLock can shift the matched form (pressing g with CapsLock on yields text == "G" and matches the pattern "G").
  2. Otherwise, pattern is parsed as a Key with the same grammar as FromStr (for example "ctrl+c", "shift+f1", "alt+plus") and compared with PartialEq. Lock state (CapsLock, NumLock, ScrollLock) is ignored by ==, so step 2 is layout- sensitive but lock-insensitive. Matching is otherwise case-sensitive — "g" and "G" are distinct ("G" is a synonym for "shift+g").

Returns false for any pattern that fails to parse and has no matching text; invalid patterns never panic.

§Examples
use uncurses::event::{Key, KeyCode, KeyModifiers};

// Case-sensitive: g and G are distinct (vim-style).
let plain_g = Key::new(KeyCode::Char('g'), KeyModifiers::empty()).normalized();
let big_g   = Key::new(KeyCode::Char('G'), KeyModifiers::empty()).normalized();
assert!(plain_g.matches("g"));
assert!(!plain_g.matches("G"));
assert!(big_g.matches("G"));
assert!(big_g.matches("shift+g")); // "G" and "shift+g" are synonyms.
assert!(!big_g.matches("g"));
Source

pub fn matches_any<I, S>(&self, patterns: I) -> bool
where I: IntoIterator<Item = S>, S: AsRef<str>,

Test whether this key matches any pattern in the iterator.

Equivalent to calling matches for each pattern and stopping at the first hit. Accepts any iterable yielding string-like items, including arrays, slices, and vectors.

§Examples
use uncurses::event::{Key, KeyCode, KeyModifiers};

let key = Key::new(KeyCode::Char('c'), KeyModifiers::CTRL).normalized();
assert!(key.matches_any(["esc", "ctrl+c", "q"]));
assert!(!key.matches_any(["esc", "q"]));
Source

pub fn normalize(&mut self)

Apply the canonical identity rules in place. Idempotent.

Decoder paths construct keys via Key::new, populate optional fields, and then call this method (or chain Key::normalized) to produce the canonical form. The rules applied are:

  • Case folding for printable Char codes: uppercase chars are lowercased and the original is stored in shifted_key; SHIFT is added only when CAPS_LOCK is not set (with CapsLock the case change is attributed to the lock state, not a Shift press).
  • Printable text auto-population when text is empty and the modifier set is a subset of SHIFT | CAPS_LOCK | NUM_LOCK.

Trait Implementations§

Source§

impl Clone for Key

Source§

fn clone(&self) -> Key

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Key

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Key

Formats the key as its canonical binding spelling: a modifier prefix (ctrl+, alt+, shift+, super+, hyper+, meta+) followed by the KeyCode name, for example "ctrl+c", "shift+f1", or "space".

This is the inverse of FromStr: every string it produces parses back to an equal Key. It renders the structural key identity only and intentionally ignores the informational text, shifted_key, and base_key fields, along with lock state (CapsLock/NumLock/ScrollLock). It therefore always spells the space bar as "space" (never " "), and composed or IME input is shown by its code, not its produced glyph.

For the user-perceived character that was typed, use char or read text directly; for layout-aware string matching that consults text, use matches.

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl FromStr for Key

Source§

type Err = ParseKeyError

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl Hash for Key

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Key

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for Key

Auto Trait Implementations§

§

impl Freeze for Key

§

impl RefUnwindSafe for Key

§

impl Send for Key

§

impl Sync for Key

§

impl Unpin for Key

§

impl UnsafeUnpin for Key

§

impl UnwindSafe for Key

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> ToCompactString for T
where T: Display,

§

fn try_to_compact_string(&self) -> Result<CompactString, ToCompactStringError>

Fallible version of [ToCompactString::to_compact_string()] Read more
§

fn to_compact_string(&self) -> CompactString

Converts the given value to a [CompactString]. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> ErasedDestructor for T
where T: 'static,