Skip to main content

nsh_core/
keyboard.rs

1//! Hardware key transitions and mounted capture rules for custom Rust views
2//! and for TSX views.
3//!
4//! Desktops and browsers deliver [`KeyEvent`] notifications for the
5//! focused view; app-rendered interaction surfaces can forward the logical
6//! key, its DOM `code`, repeats and releases to their own input engine. Raw
7//! key names are input data: the DOM's spelling for named keys, and the
8//! character a printable key reports, never forced onto a made-up layout.
9//! `code` is the source's physical identity in the DOM's spelling, mapped
10//! by the backend from the native identifier it really has; a source
11//! without one reports `""` and is never guessed from the logical key.
12//! Named shortcuts remain [`crate::keymap`]'s responsibility.
13//!
14//! [`KeyCapture`] decides native consumption before callbacks run. Its keys
15//! are canonical [`Keystroke`]s, so a capture shares the shortcut vocabulary
16//! and normalization. The platform matches them against the transition's
17//! canonical shortcut stroke, which its own shortcut matcher builds, never
18//! against the event's `key` or `code`. Focus stays with the platform's
19//! existing Tab and explicit-focus behavior.
20
21use std::sync::Arc;
22
23use crate::{
24    element::SharedString,
25    keymap::{Keystroke, Modifiers},
26};
27
28/// A key that went down or came up on the focused view (`on_key_down` /
29/// `on_key_up`), as GPUI's `KeyDownEvent`.
30#[derive(Debug, Clone, PartialEq, Eq)]
31#[non_exhaustive]
32pub struct KeyEvent {
33    /// The logical key the source reports: the DOM's spelling for named
34    /// keys (`"Enter"`, `"Escape"`, `"ArrowLeft"`) and the character a
35    /// printable key reports in its actual case, on the layout in use. Not
36    /// normalized to another layout. `"Unidentified"` when the source names
37    /// none.
38    pub key: SharedString,
39    /// The key's physical identity as the DOM's `KeyboardEvent.code` spells
40    /// it (`"KeyA"`, `"ArrowLeft"`, `"NumpadEnter"`, `"ShiftLeft"`), mapped
41    /// by the backend from the native identifier it really has: a Windows
42    /// scan code, AppKit's `NSEvent.keyCode`, or a GTK hardware keycode;
43    /// browsers provide their DOM code directly. `""` when the source has no
44    /// physical identity (GPUI's logical events, synthetic input): the
45    /// empty string is the DOM's unknown code, and no backend infers a code
46    /// from the printable or logical key.
47    pub code: SharedString,
48    /// The modifiers held after this transition. Releasing one Shift keeps
49    /// `shift` set while the other Shift is still held.
50    pub modifiers: Modifiers,
51    /// An auto-repeat of a key held down (the press itself is not one).
52    pub repeat: bool,
53    /// Whether the mounted [`KeyCapture`] rule of the focused view or an
54    /// enabled ancestor decided this transition before it ran: the platform
55    /// runs no native default and types no text. It is the decision for
56    /// this one transition, observable state as the DOM's `defaultPrevented`
57    /// is, not a veto a listener can cast: the UI thread does not wait for
58    /// engine-thread JS or Rust callbacks, which are told after the fact.
59    pub default_prevented: bool,
60}
61
62impl Default for KeyEvent {
63    /// A key the source has not identified.
64    fn default() -> Self {
65        Self {
66            key: SharedString::new_static("Unidentified"),
67            code: SharedString::default(),
68            modifiers: Modifiers::default(),
69            repeat: false,
70            default_prevented: false,
71        }
72    }
73}
74
75/// The keys a view consumes before the platform's native defaults run
76/// ([`crate::element::Interactive::capture_keys`]).
77///
78/// A view mounts one as a reactive prop; the platform reads the mounted
79/// rule of the focused view and its ancestry and decides without waiting
80/// for a listener. An eligible app shortcut keeps its priority, and a
81/// native input or child keeps its own keys. Disabled views, and views that
82/// left the focused view's ancestry, capture nothing.
83#[derive(Debug, Clone, Default, PartialEq, Eq)]
84#[non_exhaustive]
85pub enum KeyCapture {
86    /// Nothing is captured (the default).
87    #[default]
88    None,
89    /// Every key is captured, named and modifier keys included.
90    All,
91    /// The listed keys are captured: each canonical [`Keystroke`] matches
92    /// the same key and exactly its modifiers.
93    Keys(Arc<[Keystroke]>),
94    /// Typing moves into the view's first enabled text `Input`: a key that
95    /// would type text (a character, a dead key, or a key an input method
96    /// composes; not Space, which activates a focused button) with no
97    /// Control, Alt or platform modifier (macOS's Option, which types
98    /// characters there, still moves), pressed while a non-input view
99    /// inside this one has the keyboard, focuses that input and is
100    /// delivered to it before any native default, so the input method and
101    /// dead keys compose there as if the input had been focused.
102    /// Other keys are not captured. A chat screen's selectable transcript
103    /// uses it so the first key typed goes to the message field.
104    Text,
105}
106
107impl KeyCapture {
108    /// A rule capturing `keys` (each a [`Keystroke`]'s key and modifiers,
109    /// both exact).
110    pub fn keys(keys: impl IntoIterator<Item = Keystroke>) -> Self {
111        KeyCapture::Keys(keys.into_iter().collect())
112    }
113
114    /// Whether this rule captures nothing: [`Self::None`], or
115    /// [`Self::Keys`] without keys. The platform need not look at a key's
116    /// event where it is true.
117    #[doc(hidden)]
118    pub fn is_none(&self) -> bool {
119        match self {
120            KeyCapture::None => true,
121            KeyCapture::All | KeyCapture::Text => false,
122            KeyCapture::Keys(keys) => keys.is_empty(),
123        }
124    }
125
126    /// Whether typing moves into this view's text input ([`Self::Text`]).
127    #[doc(hidden)]
128    pub fn types_into_input(&self) -> bool {
129        matches!(self, KeyCapture::Text)
130    }
131
132    /// Matches the backend's canonical shortcut stroke. A key with no
133    /// representable stroke matches only [`Self::All`].
134    #[doc(hidden)]
135    pub fn captures_key(&self, keystroke: Option<&Keystroke>) -> bool {
136        match self {
137            KeyCapture::None | KeyCapture::Text => false,
138            KeyCapture::All => true,
139            KeyCapture::Keys(keys) => keystroke.is_some_and(|keystroke| keys.contains(keystroke)),
140        }
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    /// The keystroke `text` names on a non-Apple platform.
149    fn stroke(text: &str) -> Keystroke {
150        Keystroke::parse_with(text, false).expect(text)
151    }
152
153    #[test]
154    fn a_default_event_names_no_key_and_captures_nothing() {
155        let event = KeyEvent::default();
156        assert_eq!(event.key.as_str(), "Unidentified");
157        assert_eq!(event.code.as_str(), "");
158        assert_eq!(event.modifiers, Modifiers::default());
159        assert!(!event.repeat && !event.default_prevented);
160    }
161
162    #[test]
163    fn a_capture_with_no_keys_is_none() {
164        assert!(KeyCapture::None.is_none());
165        assert!(KeyCapture::keys(std::iter::empty()).is_none());
166        assert!(!KeyCapture::All.is_none());
167        assert!(!KeyCapture::keys([stroke("a")]).is_none());
168    }
169
170    #[test]
171    fn capture_matches_the_stroke_and_modifiers_exactly() {
172        let a = stroke("a");
173        assert!(!KeyCapture::default().captures_key(Some(&a)));
174        assert!(!KeyCapture::None.captures_key(Some(&a)));
175        assert!(KeyCapture::All.captures_key(Some(&a)));
176        assert!(KeyCapture::keys([stroke("a")]).captures_key(Some(&a)));
177        // A keystroke names the modifiers it needs, all of them.
178        assert!(!KeyCapture::keys([stroke("shift+a")]).captures_key(Some(&a)));
179        assert!(!KeyCapture::keys([stroke("ctrl+a")]).captures_key(Some(&a)));
180        assert!(!KeyCapture::keys([stroke("b")]).captures_key(Some(&a)));
181
182        // Names the shortcut vocabulary has, with exact modifiers.
183        for (name, expected) in [
184            ("left", stroke("left")),
185            ("enter", stroke("enter")),
186            ("escape", stroke("escape")),
187            ("tab", stroke("tab")),
188            ("backspace", stroke("backspace")),
189            ("delete", stroke("delete")),
190            ("pagedown", stroke("pagedown")),
191            ("f5", stroke("f5")),
192            ("space", stroke("space")),
193        ] {
194            assert!(
195                KeyCapture::keys([expected]).captures_key(Some(&expected)),
196                "{name}"
197            );
198        }
199        // Shift+A is the `a` key with Shift: what the platform's matcher
200        // builds, not the reported character.
201        let shifted = Keystroke {
202            modifiers: Modifiers {
203                shift: true,
204                ..Default::default()
205            },
206            key: crate::keymap::Key::Char('a'),
207        };
208        assert!(KeyCapture::keys([stroke("shift+a")]).captures_key(Some(&shifted)));
209        assert!(!KeyCapture::keys([stroke("a")]).captures_key(Some(&shifted)));
210
211        // A shortcut names US-layout ASCII keys: another layout's character
212        // has no keystroke, and only `All` captures it.
213        assert!(KeyCapture::All.captures_key(None));
214        assert!(!KeyCapture::Text.captures_key(None));
215        assert!(!KeyCapture::Text.captures_key(Some(&a)));
216        assert!(!KeyCapture::Text.is_none());
217        assert!(KeyCapture::Text.types_into_input());
218        assert!(!KeyCapture::keys([stroke("a")]).captures_key(None));
219        assert!(!KeyCapture::None.captures_key(None));
220    }
221}