Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
gpui: Add character input preference to keystroke events (#64859)
Smit Barmase86c20cc9119d
diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rsindex 612d3df5882..3322cde4b4a 100644--- a/crates/gpui/src/app.rs+++ b/crates/gpui/src/app.rs@@ -3200,12 +3200,30 @@ pub struct AnyTooltip {pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,}+/// Whether a keystroke should prefer character input or key bindings.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum InputPreference {+ /// Prefer typing text over triggering key bindings.+ CharacterInput,+ /// Dispatch key bindings normally, if any match.+ KeyBindings,+}+/// A keystroke event, and potentially the associated action#[derive(Debug)]pub struct KeystrokeEvent {/// The keystroke that occurredpub keystroke: Keystroke,+ /// Whether this keystroke should prefer character input or key bindings.+ /// This is [`InputPreference::CharacterInput`] when the platform prefers text for the key+ /// (e.g. AltGr on Windows) and the focused input accepts text. Interceptors still receive+ /// these keystrokes and can consume them.+ ///+ /// If the keystroke is part of a multi-stroke binding, it still waits as pending input+ /// even when this is [`InputPreference::CharacterInput`].+ pub input_preference: InputPreference,+/// The action that was resolved for the keystroke, if anypub action: Option<Box<dyn Action>>,diff --git a/crates/gpui/src/key_dispatch.rs b/crates/gpui/src/key_dispatch.rsindex 5db400fab98..2f755b1d3dc 100644--- a/crates/gpui/src/key_dispatch.rs+++ b/crates/gpui/src/key_dispatch.rs@@ -633,10 +633,11 @@ mod tests {};use crate::{- Action, ActionRegistry, App, Bounds, Context, DispatchPhase, DispatchTree, FocusHandle,- InputHandler, IntoElement, KeyBinding, KeyContext, Keymap, Modifiers, Pixels,- PlatformWindow, Point, Render, Subscription, TestAppContext, UTF16Selection, Unbind,- VisualContext, VisualTestContext, Window,+ Action, ActionRegistry, App, Bounds, Context, DispatchEventResult, DispatchPhase,+ DispatchTree, Entity, FocusHandle, InputHandler, InputPreference, IntoElement, KeyBinding,+ KeyContext, KeyDownEvent, Keymap, Modifiers, Pixels, PlatformInput, PlatformWindow, Point,+ Render, Subscription, TestAppContext, UTF16Selection, Unbind, VisualContext,+ VisualTestContext, Window,};actions!(dispatch_test, [TestAction, SecondaryTestAction]);@@ -661,6 +662,7 @@ mod tests {focus_handle: FocusHandle,text: Rc<RefCell<String>>,action_count: Rc<Cell<usize>>,+ accepts_text_input: Rc<Cell<bool>>,}impl PendingTextInputTestView {@@ -669,6 +671,7 @@ mod tests {focus_handle: cx.focus_handle(),text: Rc::default(),action_count: Rc::default(),+ accepts_text_input: Rc::new(Cell::new(true)),}}}@@ -742,6 +745,10 @@ mod tests {}impl InputHandler for PendingTextInputTestView {+ fn accepts_text_input(&mut self, _: &mut Window, _: &mut App) -> bool {+ self.accepts_text_input.get()+ }+fn selected_text_range(&mut self,_: bool,@@ -921,6 +928,37 @@ mod tests {Some(prefers_ime)}+ fn setup_altgr_test(+ cx: &mut TestAppContext,+ ) -> (Entity<PendingTextInputTestView>, &mut VisualTestContext) {+ let (test, cx) = cx.add_window_view(|_, cx| PendingTextInputTestView::new(cx));+ test.update_in(cx, |test, window, cx| {+ window.focus(&test.focus_handle, cx);+ window.activate_window();+ cx.bind_keys([KeyBinding::new("ctrl-alt-a", TestAction, Some("Terminal"))]);+ });+ (test, cx)+ }++ fn dispatch_altgr_key_down(+ cx: &mut VisualTestContext,+ prefer_character_input: bool,+ ) -> DispatchEventResult {+ cx.update(|window, cx| {+ window.dispatch_event(+ PlatformInput::KeyDown(KeyDownEvent {+ keystroke: Keystroke {+ key_char: Some("ą".into()),+ ..Keystroke::parse("ctrl-alt-a").expect("valid keystroke")+ },+ is_held: false,+ prefer_character_input,+ }),+ cx,+ )+ })+ }+fn simulate_pending_binding(cx: &mut VisualTestContext) {cx.simulate_modifiers_change(crate::Modifiers::control());cx.simulate_keystrokes("ctrl-b");@@ -1580,6 +1618,137 @@ mod tests {assert_eq!(action_count.get(), 1);}+ #[crate::test]+ fn test_keystroke_input_preference(cx: &mut TestAppContext) {+ let (test, cx) = setup_altgr_test(cx);+ let intercepted_preferences = Rc::new(RefCell::new(Vec::new()));+ let observed_preferences = Rc::new(RefCell::new(Vec::new()));+ let _interceptor = cx.update(|_, cx| {+ cx.intercept_keystrokes({+ let intercepted_preferences = intercepted_preferences.clone();+ move |event, _, _| {+ intercepted_preferences+ .borrow_mut()+ .push(event.input_preference);+ }+ })+ });+ let _observer = cx.update(|_, cx| {+ cx.observe_keystrokes({+ let observed_preferences = observed_preferences.clone();+ move |event, _, _| {+ observed_preferences+ .borrow_mut()+ .push(event.input_preference);+ }+ })+ });++ for (prefer_character_input, accepts_text_input, input_preference) in [+ (true, true, InputPreference::CharacterInput),+ (false, true, InputPreference::KeyBindings),+ (true, false, InputPreference::KeyBindings),+ (false, false, InputPreference::KeyBindings),+ ] {+ test.update(cx, |test, _| {+ test.accepts_text_input.set(accepts_text_input);+ test.action_count.set(0);+ });+ intercepted_preferences.borrow_mut().clear();+ observed_preferences.borrow_mut().clear();+ let result = dispatch_altgr_key_down(cx, prefer_character_input);+ assert_eq!(+ result.propagate,+ input_preference == InputPreference::CharacterInput+ );+ assert_eq!(+ intercepted_preferences.borrow().as_slice(),+ &[input_preference]+ );+ assert_eq!(+ observed_preferences.borrow().as_slice(),+ &[input_preference]+ );+ test.read_with(cx, |test, _| {+ assert_eq!(+ test.action_count.get(),+ usize::from(input_preference == InputPreference::KeyBindings)+ );+ });+ }+ }++ #[crate::test]+ fn test_input_preference_rechecked_after_interception(cx: &mut TestAppContext) {+ let (test, cx) = setup_altgr_test(cx);+ let accepts_text_input = test.read_with(cx, |test, _| test.accepts_text_input.clone());+ let _interceptor = cx.update(|_, cx| {+ cx.intercept_keystrokes({+ let accepts_text_input = accepts_text_input.clone();+ move |event, _, _| {+ assert_eq!(+ event.input_preference == InputPreference::CharacterInput,+ accepts_text_input.get()+ );+ accepts_text_input.set(!accepts_text_input.get());+ }+ })+ });+ let observed_preferences = Rc::new(RefCell::new(Vec::new()));+ let _observer = cx.update(|_, cx| {+ cx.observe_keystrokes({+ let observed_preferences = observed_preferences.clone();+ move |event, _, _| {+ observed_preferences+ .borrow_mut()+ .push(event.input_preference);+ }+ })+ });++ for (initially_accepts_text_input, observed_preference) in [+ (true, InputPreference::KeyBindings),+ (false, InputPreference::CharacterInput),+ ] {+ accepts_text_input.set(initially_accepts_text_input);+ test.update(cx, |test, _| test.action_count.set(0));+ observed_preferences.borrow_mut().clear();+ let result = dispatch_altgr_key_down(cx, true);+ assert_eq!(result.propagate, !initially_accepts_text_input);+ assert_eq!(+ observed_preferences.borrow().as_slice(),+ &[observed_preference]+ );+ test.read_with(cx, |test, _| {+ assert_eq!(+ test.action_count.get(),+ usize::from(initially_accepts_text_input)+ );+ });+ }+ }++ #[crate::test]+ fn test_keystroke_interceptors_can_consume_preferred_character_input(cx: &mut TestAppContext) {+ let (test, cx) = setup_altgr_test(cx);+ let intercepted = Rc::new(Cell::new(false));+ let _interceptor = cx.update(|_, cx| {+ cx.intercept_keystrokes({+ let intercepted = intercepted.clone();+ move |event, _, cx| {+ assert_eq!(event.input_preference, InputPreference::CharacterInput);+ intercepted.set(true);+ cx.stop_propagation();+ }+ })+ });++ let result = dispatch_altgr_key_down(cx, true);+ assert!(intercepted.get());+ assert!(!result.propagate);+ test.read_with(cx, |test, _| assert_eq!(test.action_count.get(), 0));+ }+#[crate::test]fn test_consumed_modifier_preserves_pending_input(cx: &mut TestAppContext) {let (test, cx) = cx.add_window_view(|_, cx| PendingTextInputTestView::new(cx));diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rsindex 645f9dbc51a..52d729f75ad 100644--- a/crates/gpui/src/window.rs+++ b/crates/gpui/src/window.rs@@ -10,12 +10,12 @@ use crate::{Capslock, Context, Corners, CursorHideMode, CursorStyle, Decorations, DevicePixels,DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs,- Hsla, InputHandler, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke,- KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent, MonochromeSprite,- MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas,- PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point, PolychromeSprite,- Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams, RenderImage,- RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,+ Hsla, InputHandler, InputPreference, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent,+ Keystroke, KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent,+ MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels,+ PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point,+ PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams,+ RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size,StrikethroughStyle, Style, SubpixelSprite, SubscriberSet, Subscription, SystemWindowTab,SystemWindowTabController, TabStopMap, TaffyLayoutEngine, Task, TextInputConfiguration,@@ -2456,6 +2456,7 @@ impl Window {pub(crate) fn dispatch_keystroke_observers(&mut self,keystroke: &Keystroke,+ input_preference: InputPreference,action: Option<&dyn Action>,context_stack: Vec<KeyContext>,cx: &mut App,@@ -2464,6 +2465,7 @@ impl Window {(callback)(&KeystrokeEvent {keystroke: keystroke.clone(),+ input_preference,action: action.map(|action| action.boxed_clone()),context_stack: context_stack.clone(),},@@ -2476,6 +2478,7 @@ impl Window {pub(crate) fn dispatch_keystroke_interceptors(&mut self,keystroke: &Keystroke,+ input_preference: InputPreference,context_stack: Vec<KeyContext>,cx: &mut App,) {@@ -2485,6 +2488,7 @@ impl Window {(callback)(&KeystrokeEvent {keystroke: keystroke.clone(),+ input_preference,action: None,context_stack: context_stack.clone(),},@@ -5799,6 +5803,27 @@ impl Window {}}+ // If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,+ // we prefer the text input over bindings.+ fn input_preference(&mut self, event: &dyn Any, cx: &mut App) -> InputPreference {+ let prefer_character_input = event+ .downcast_ref::<KeyDownEvent>()+ .is_some_and(|key_down_event| key_down_event.prefer_character_input);+ if !prefer_character_input {+ return InputPreference::KeyBindings;+ }+ let Some(mut input_handler) = self.platform_window.take_input_handler() else {+ return InputPreference::KeyBindings;+ };+ let accepts_text_input = input_handler.accepts_text_input(self, cx);+ self.platform_window.set_input_handler(input_handler);+ if accepts_text_input {+ InputPreference::CharacterInput+ } else {+ InputPreference::KeyBindings+ }+ }+fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {if self.invalidator.is_dirty() {self.draw(cx).clear(cx);@@ -5853,16 +5878,31 @@ impl Window {}let Some(keystroke) = keystroke else {- self.finish_dispatch_key_event(event, None, dispatch_path, self.context_stack(), cx);+ self.finish_dispatch_key_event(+ event,+ None,+ InputPreference::KeyBindings,+ dispatch_path,+ self.context_stack(),+ cx,+ );return;};+ let input_preference = self.input_preference(event, cx);+cx.propagate_event = true;- self.dispatch_keystroke_interceptors(&keystroke, self.context_stack(), cx);+ self.dispatch_keystroke_interceptors(+ &keystroke,+ input_preference,+ self.context_stack(),+ cx,+ );if !cx.propagate_event {self.finish_dispatch_key_event(event,Some(&keystroke),+ input_preference,dispatch_path,self.context_stack(),cx,@@ -5924,28 +5964,15 @@ impl Window {return;}- let skip_bindings = event- .downcast_ref::<KeyDownEvent>()- .filter(|key_down_event| key_down_event.prefer_character_input)- .map(|_| {- self.platform_window- .take_input_handler()- .map_or(false, |mut input_handler| {- let accepts = input_handler.accepts_text_input(self, cx);- self.platform_window.set_input_handler(input_handler);- // If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,- // we prefer the text input over bindings.- accepts- })- })- .unwrap_or(false);-- if !skip_bindings {+ // Interceptors or replayed actions may have changed whether the input handler accepts text.+ let input_preference = self.input_preference(event, cx);+ if input_preference == InputPreference::KeyBindings {for binding in match_result.bindings {self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);if !cx.propagate_event {self.dispatch_keystroke_observers(&keystroke,+ input_preference,Some(binding.action.as_ref()),match_result.context_stack,cx,@@ -5959,6 +5986,7 @@ impl Window {self.finish_dispatch_key_event(event,Some(&keystroke),+ input_preference,dispatch_path,match_result.context_stack,cx,@@ -6008,6 +6036,7 @@ impl Window {&mut self,event: &dyn Any,recognized_keystroke: Option<&Keystroke>,+ input_preference: InputPreference,dispatch_path: SmallVec<[DispatchNodeId; 32]>,context_stack: Vec<KeyContext>,cx: &mut App,@@ -6023,7 +6052,7 @@ impl Window {}if let Some(keystroke) = recognized_keystroke {- self.dispatch_keystroke_observers(keystroke, None, context_stack, cx);+ self.dispatch_keystroke_observers(keystroke, input_preference, None, context_stack, cx);}}@@ -6227,6 +6256,7 @@ impl Window {if !cx.propagate_event {self.dispatch_keystroke_observers(&replay.keystroke,+ InputPreference::KeyBindings,Some(binding.action.as_ref()),Vec::default(),cx,