Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions crates/gpui/nsh-platform-gpui/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,8 +439,10 @@ pub(crate) fn install<V: gpui::EntityInputHandler>(
// canonical stroke, and reaches the focused view; a key with a code
// keeps the code's meaning. Only the keymap or a listener needs it.
let vk = crate::keys::vk_of(&e.keystroke.key);
let wants_raw =
crate::input::hears_keys(&s) || (vk.is_none() && crate::keymap::mounted(&s));
// A binding of typed characters needs the text the key types.
let wants_raw = crate::input::hears_keys(&s)
|| (vk.is_none() && crate::keymap::mounted(&s))
|| crate::keymap::takes_typed(&s);
let raw = wants_raw.then(|| crate::keys::RawKey::down(&e.keystroke, e.is_held));
let event = KeyEvent {
vk: vk.unwrap_or(0),
Expand Down
10 changes: 8 additions & 2 deletions crates/gpui/nsh-platform-gpui/src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1412,7 +1412,13 @@ pub(crate) fn key_now_raw(
let editing = crate::text_input::focused(surface).is_some();
let mut handled = shortcut
|| crate::system::key(surface, &event)
|| crate::keymap::key_stroke(surface, &event, editing, source);
|| crate::keymap::key_stroke(
surface,
&event,
editing,
source,
raw.as_ref().and_then(|r| r.typed()),
);
// The focused view hears the key as the source reported it, and a
// capture rule over it runs no native default. A text field or a
// native component owns its keys: its ancestors hear none of them.
Expand Down Expand Up @@ -1585,7 +1591,7 @@ pub(crate) fn component_key(
crate::text_input::disarm(surface);
}
let handled = surface.shortcuts.borrow().iter().any(|f| f(&event))
|| crate::keymap::key_stroke(surface, &event, true, source)
|| crate::keymap::key_stroke(surface, &event, true, source, raw.and_then(|r| r.typed()))
|| crate::chrome::shortcut(surface, &event);
if handled && event.modifiers.alt {
surface.input.alt_combo.set(true);
Expand Down
117 changes: 106 additions & 11 deletions crates/gpui/nsh-platform-gpui/src/keymap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use std::{

use nsh_core::{
EventKind, EventPayload, PayloadValue, ROOT_ID,
keymap::{Key, Keymap, Keystroke, Modifiers},
keymap::{Key, KeyMatch, Keymap, Keystroke, Modifiers},
};

use crate::{input::KeyEvent, keys, keys::OS, surface::Surface};
Expand All @@ -61,7 +61,8 @@ enum Held {

/// `MountItem::Keymap`: replaces the surface's table.
pub(crate) fn set(surface: &Surface, keymap: Arc<Keymap>) {
*surface.keymap.table.borrow_mut() = (!keymap.is_empty()).then_some(keymap);
let used = !keymap.is_empty() || keymap.takes_typed();
*surface.keymap.table.borrow_mut() = used.then_some(keymap);
}

/// Drops the table (the app stopped).
Expand All @@ -81,26 +82,37 @@ pub(crate) fn clear(surface: &Surface) {
/// rules — the platform's own repeat mark (`event.repeat`) counting too,
/// and the held stroke updated either way. A key with a virtual code keeps
/// matching by it.
///
/// `typed`: the characters the key types, in their case, and the
/// modifiers it typed them with ([`crate::keys::RawKey::typed`]). A key
/// no binding takes goes to the bindings of typed characters
/// ([`Keymap::find_typed`]) with them; one that fires reports its id and
/// the text ([`nsh_core::keymap::typed_payload`]).
pub(crate) fn key_stroke(
surface: &Rc<Surface>,
event: &KeyEvent,
editing: bool,
source: Option<Keystroke>,
typed: Option<(&str, Modifiers)>,
) -> bool {
// The key a binding could name: a virtual code's, or the source's
// stroke for a key without one (a modifier key has neither).
let Some(keystroke) = source.or_else(|| keystroke(event)) else {
// stroke for a key without one (a modifier key has neither). A key
// no binding can name may still type text (`é`, `ж`).
let stroke = source.or_else(|| keystroke(event));
if stroke.is_none() && typed.is_none() {
return false;
};
let repeat = match source {
Some(stroke) => repeats_stroke(&surface.keymap, stroke, event.repeat),
None => repeats(&surface.keymap, event),
}
let repeat = match (source, stroke) {
(Some(stroke), _) => repeats_stroke(&surface.keymap, stroke, event.repeat),
(None, Some(_)) => repeats(&surface.keymap, event),
// Only the platform's mark: X11's repeats of such a key fire again.
(None, None) => event.repeat,
};
let Some(table) = surface.keymap.table.borrow().clone() else {
return false;
};
// The dev host's Ctrl+R / Cmd+R reloads, whatever the app binds.
if cfg!(feature = "dev") && keystroke.reloads(OS) {
if cfg!(feature = "dev") && stroke.is_some_and(|k| k.reloads(OS)) {
return false;
}
// Only the bindings of the window the key is in (and JS's) take it.
Expand All @@ -114,7 +126,10 @@ pub(crate) fn key_stroke(
focus.editing = editing;
focus.control = control;
focus.covered = crate::key_focus::covered(surface);
let found = table.find_with(window, keystroke, focus, repeat);
let found = match stroke {
Some(keystroke) => table.find_with(window, keystroke, focus, repeat),
None => KeyMatch::None,
};
if let Some(id) = found.fired() {
surface.event(
ROOT_ID,
Expand All @@ -127,7 +142,28 @@ pub(crate) fn key_stroke(
crate::text_input::arm(surface);
}
}
found.consumed()
if found != KeyMatch::None {
return found.consumed();
}
// No binding took the key: the characters it types, for a binding of
// typed characters (a list's typeahead). While a field edits (and so
// while an input method composes) the core takes none.
let Some((text, modifiers)) = typed.filter(|_| table.takes_typed()) else {
return false;
};
let apple = cfg!(target_os = "macos");
match table.find_typed(window, text, modifiers, focus, repeat, apple) {
KeyMatch::Fire(id) => {
surface.event(
ROOT_ID,
EventKind::KeyCommand,
nsh_core::keymap::typed_payload(id, text),
);
true
}
KeyMatch::Held => true,
KeyMatch::None | KeyMatch::Notify(_) => false,
}
}

/// Whether a key down is an auto-repeat (see the module docs), noting the
Expand Down Expand Up @@ -176,6 +212,17 @@ pub(crate) fn released_stroke(surface: &Surface, stroke: &Keystroke) {
}
}

/// Whether the surface's table has bindings of typed characters: a key
/// is then needed as the source reported it, for the text it types.
pub(crate) fn takes_typed(surface: &Surface) -> bool {
surface
.keymap
.table
.borrow()
.as_ref()
.is_some_and(|t| t.takes_typed())
}

/// Whether the surface has a table of bindings (a key with no virtual
/// code is only needed as a raw key when one could match its stroke).
pub(crate) fn mounted(surface: &Surface) -> bool {
Expand Down Expand Up @@ -261,6 +308,7 @@ mod tests {
},
false,
None,
None,
)
};
// Pressed in the main window: not its binding, the key goes on.
Expand Down Expand Up @@ -298,6 +346,7 @@ mod tests {
},
false,
Some(stroke),
None,
)
};
assert!(press(question));
Expand Down Expand Up @@ -349,6 +398,52 @@ mod tests {
assert!(repeats(&surface.keymap, &key(0x4B)));
}

#[test]
fn a_key_no_binding_takes_goes_to_the_bindings_of_typed_characters() {
use nsh_core::keymap::{KeyBinding, Keymap, Keystroke, Modifiers, When};

use super::{KeyEvent, key_stroke};
use crate::surface::Surface;

let surface = Surface::new(nsh_engine::Environment::default());
let any = Keystroke::parse_with("a", false).unwrap();
let typed = KeyBinding::new(5, any, When::NotEditing, false);
// A table of typed characters alone is kept.
super::set(
&surface,
std::sync::Arc::new(Keymap::new(vec![]).with_typed(vec![typed])),
);
assert!(super::takes_typed(&surface));
let shift = Modifiers {
shift: true,
..Modifiers::default()
};
let press = |vk: u16, text: Option<&str>, modifiers: Modifiers, editing: bool| {
surface.keymap.held.set(None);
let event = KeyEvent {
vk,
down: true,
repeat: false,
modifiers: crate::input::Modifiers {
shift: modifiers.shift,
ctrl: modifiers.ctrl,
alt: modifiers.alt,
meta: modifiers.cmd,
},
};
key_stroke(&surface, &event, editing, None, text.map(|t| (t, modifiers)))
};
// Shift+A types `A`; `é` has no virtual key code and still types.
// (With no engine running nothing is dispatched: what the key
// does is what it returns.)
assert!(press(0x41, Some("A"), shift, false));
assert!(press(0, Some("é"), Modifiers::default(), false));
// A field edits (an input method may compose): the key goes on.
assert!(!press(0x41, Some("a"), Modifiers::default(), true));
// A key that types nothing goes on.
assert!(!press(0x41, None, Modifiers::default(), false));
}

#[test]
fn virtual_keys() {
assert_eq!(super::key_of(0x4B), Some(Key::Char('k')));
Expand Down
67 changes: 67 additions & 0 deletions crates/gpui/nsh-platform-gpui/src/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,9 @@ pub(crate) struct RawKey {
repeat: bool,
/// The key in the keymap's spelling, for matching ([`source_stroke`]).
stroke: Option<Keystroke>,
/// The characters the key types, in their case ([`typed_text`]), for
/// the keymap's bindings of typed characters.
typed: Option<SharedString>,
}

impl RawKey {
Expand Down Expand Up @@ -209,12 +212,17 @@ impl RawKey {
}
named => named_key(named),
};
let typed = match keystroke.key {
ShortcutKey::Char(_) => Some(key.clone()),
_ => None,
};
RawKey {
down,
key,
modifiers,
repeat: false,
stroke: Some(*keystroke),
typed,
}
}

Expand All @@ -227,9 +235,22 @@ impl RawKey {
modifiers,
repeat,
stroke,
typed: typed_text(keystroke),
}
}

/// The characters the key types, in their case (Shift's `A`, the
/// layout's `é` or `ж`), with the modifiers it was typed with: AltGr
/// ([`KeyModifiers::alt_graph`]) where Control and Alt typed a
/// character the key does not name (Windows reports AltGr as both).
/// `None` for a key that types nothing.
pub(crate) fn typed(&self) -> Option<(&str, KeyModifiers)> {
let text = self.typed.as_ref()?;
let mut modifiers = self.modifiers;
modifiers.alt_graph = alt_graph(modifiers, text, self.stroke.as_ref());
Some((text.as_ref(), modifiers))
}

/// The source's key as a canonical shortcut keystroke
/// ([`source_stroke`]): what a capture rule and an app binding match.
/// `None` for a key no shortcut can name (a non-ASCII character, a
Expand All @@ -253,6 +274,27 @@ impl RawKey {
}
}

/// The characters GPUI reports key `keystroke` types (`key_char`), in their
/// case: `None` when it types nothing or a control character.
fn typed_text(keystroke: &gpui::Keystroke) -> Option<SharedString> {
let text = keystroke.key_char.as_deref()?;
(!text.is_empty() && !text.chars().any(char::is_control)).then(|| SharedString::from(text.to_string()))
}

/// Whether Control and Alt held off Apple platforms typed `text` from the
/// layout's AltGr level: it is not the character the key names (AltGr+Q's
/// `@` on a German layout, not Control+Alt+Q's `q`).
fn alt_graph(modifiers: KeyModifiers, text: &str, stroke: Option<&Keystroke>) -> bool {
if cfg!(target_os = "macos") || !(modifiers.ctrl && modifiers.alt) {
return false;
}
let mut chars = text.chars();
match (chars.next(), chars.next(), stroke.map(|s| s.key)) {
(Some(c), None, Some(ShortcutKey::Char(k))) => c.to_ascii_lowercase() != k,
_ => true,
}
}

/// The key's name: the character the platform reports it types (its case
/// as reported), else the web's spelling of a key both platforms name
/// alike, else GPUI's own name for it.
Expand Down Expand Up @@ -461,6 +503,31 @@ mod tests {
assert_eq!(vk_of("é"), None);
}

#[test]
fn a_raw_key_types_its_characters_in_their_case() {
let typed = |key: &str, key_char: Option<&str>, m: gpui::Modifiers| {
RawKey::down(&stroke(key, key_char, m), false)
.typed()
.map(|(text, m)| (text.to_string(), m.alt_graph))
};
assert_eq!(typed("a", Some("A"), shift()), Some(("A".into(), false)));
assert_eq!(typed("e", Some("é"), Default::default()), Some(("é".into(), false)));
assert_eq!(typed("f", Some("а"), Default::default()), Some(("а".into(), false)));
// Keys that type nothing, or a control character.
assert_eq!(typed("enter", None, Default::default()), None);
assert_eq!(typed("tab", Some("\t"), Default::default()), None);
// Control and Alt typing another character than the key's: AltGr,
// off Apple platforms (Option types characters on its own there).
let ctrl_alt = gpui::Modifiers {
control: true,
alt: true,
..Default::default()
};
let altgr = !cfg!(target_os = "macos");
assert_eq!(typed("q", Some("@"), ctrl_alt), Some(("@".into(), altgr)));
assert_eq!(typed("q", Some("q"), ctrl_alt), Some(("q".into(), false)));
}

#[test]
fn a_raw_key_keeps_what_the_source_reported_and_matches_by_its_key() {
// Shift+A: GPUI lower cases the key and reports the typed `A`.
Expand Down
2 changes: 1 addition & 1 deletion crates/gpui/nsh-platform-gpui/src/navigation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1728,7 +1728,7 @@ mod tests {
};
// The dialog's binding takes Return, and the covered button is not
// pressed.
assert!(crate::keymap::key_stroke(&surface, &key, false, None));
assert!(crate::keymap::key_stroke(&surface, &key, false, None, None));
assert!(!crate::key_focus::key(&surface, &key));
crate::key_focus::forget(&surface);
}
Expand Down
Loading
Loading