key_dispatch.rs

  1/// KeyDispatch is where GPUI deals with binding actions to key events.
  2///
  3/// The key pieces to making a key binding work are to define an action,
  4/// implement a method that takes that action as a type parameter,
  5/// and then to register the action during render on a focused node
  6/// with a keymap context:
  7///
  8/// ```rust
  9/// actions!(editor,[Undo, Redo]);;
 10///
 11/// impl Editor {
 12///   fn undo(&mut self, _: &Undo, _window: &mut Window, _cx: &mut Context<Self>) { ... }
 13///   fn redo(&mut self, _: &Redo, _window: &mut Window, _cx: &mut Context<Self>) { ... }
 14/// }
 15///
 16/// impl Render for Editor {
 17///   fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 18///     div()
 19///       .track_focus(&self.focus_handle(cx))
 20///       .keymap_context("Editor")
 21///       .on_action(cx.listener(Editor::undo))
 22///       .on_action(cx.listener(Editor::redo))
 23///     ...
 24///    }
 25/// }
 26///```
 27///
 28/// The keybindings themselves are managed independently by calling cx.bind_keys().
 29/// (Though mostly when developing Zed itself, you just need to add a new line to
 30///  assets/keymaps/default.json).
 31///
 32/// ```rust
 33/// cx.bind_keys([
 34///   KeyBinding::new("cmd-z", Editor::undo, Some("Editor")),
 35///   KeyBinding::new("cmd-shift-z", Editor::redo, Some("Editor")),
 36/// ])
 37/// ```
 38///
 39/// With all of this in place, GPUI will ensure that if you have an Editor that contains
 40/// the focus, hitting cmd-z will Undo.
 41///
 42/// In real apps, it is a little more complicated than this, because typically you have
 43/// several nested views that each register keyboard handlers. In this case action matching
 44/// bubbles up from the bottom. For example in Zed, the Workspace is the top-level view, which contains Pane's, which contain Editors. If there are conflicting keybindings defined
 45/// then the Editor's bindings take precedence over the Pane's bindings, which take precedence over the Workspace.
 46///
 47/// In GPUI, keybindings are not limited to just single keystrokes, you can define
 48/// sequences by separating the keys with a space:
 49///
 50///  KeyBinding::new("cmd-k left", pane::SplitLeft, Some("Pane"))
 51///
 52use crate::{
 53    Action, ActionRegistry, App, DispatchPhase, EntityId, FocusId, KeyBinding, KeyContext, Keymap,
 54    Keystroke, ModifiersChangedEvent, Window,
 55};
 56use collections::FxHashMap;
 57use smallvec::SmallVec;
 58use std::{
 59    any::{Any, TypeId},
 60    cell::RefCell,
 61    mem,
 62    ops::Range,
 63    rc::Rc,
 64};
 65
 66#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
 67pub(crate) struct DispatchNodeId(usize);
 68
 69pub(crate) struct DispatchTree {
 70    node_stack: Vec<DispatchNodeId>,
 71    pub(crate) context_stack: Vec<KeyContext>,
 72    view_stack: Vec<EntityId>,
 73    nodes: Vec<DispatchNode>,
 74    focusable_node_ids: FxHashMap<FocusId, DispatchNodeId>,
 75    view_node_ids: FxHashMap<EntityId, DispatchNodeId>,
 76    keymap: Rc<RefCell<Keymap>>,
 77    action_registry: Rc<ActionRegistry>,
 78}
 79
 80#[derive(Default)]
 81pub(crate) struct DispatchNode {
 82    pub key_listeners: Vec<KeyListener>,
 83    pub action_listeners: Vec<DispatchActionListener>,
 84    pub modifiers_changed_listeners: Vec<ModifiersChangedListener>,
 85    pub context: Option<KeyContext>,
 86    pub focus_id: Option<FocusId>,
 87    view_id: Option<EntityId>,
 88    parent: Option<DispatchNodeId>,
 89}
 90
 91pub(crate) struct ReusedSubtree {
 92    old_range: Range<usize>,
 93    new_range: Range<usize>,
 94    contains_focus: bool,
 95}
 96
 97impl ReusedSubtree {
 98    pub fn refresh_node_id(&self, node_id: DispatchNodeId) -> DispatchNodeId {
 99        debug_assert!(
100            self.old_range.contains(&node_id.0),
101            "node {} was not part of the reused subtree {:?}",
102            node_id.0,
103            self.old_range
104        );
105        DispatchNodeId((node_id.0 - self.old_range.start) + self.new_range.start)
106    }
107
108    pub fn contains_focus(&self) -> bool {
109        self.contains_focus
110    }
111}
112
113#[derive(Default, Debug)]
114pub(crate) struct Replay {
115    pub(crate) keystroke: Keystroke,
116    pub(crate) bindings: SmallVec<[KeyBinding; 1]>,
117}
118
119#[derive(Default, Debug)]
120pub(crate) struct DispatchResult {
121    pub(crate) pending: SmallVec<[Keystroke; 1]>,
122    pub(crate) bindings: SmallVec<[KeyBinding; 1]>,
123    pub(crate) to_replay: SmallVec<[Replay; 1]>,
124}
125
126type KeyListener = Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App)>;
127type ModifiersChangedListener = Rc<dyn Fn(&ModifiersChangedEvent, &mut Window, &mut App)>;
128
129#[derive(Clone)]
130pub(crate) struct DispatchActionListener {
131    pub(crate) action_type: TypeId,
132    pub(crate) listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App)>,
133}
134
135impl DispatchTree {
136    pub fn new(keymap: Rc<RefCell<Keymap>>, action_registry: Rc<ActionRegistry>) -> Self {
137        Self {
138            node_stack: Vec::new(),
139            context_stack: Vec::new(),
140            view_stack: Vec::new(),
141            nodes: Vec::new(),
142            focusable_node_ids: FxHashMap::default(),
143            view_node_ids: FxHashMap::default(),
144            keymap,
145            action_registry,
146        }
147    }
148
149    pub fn clear(&mut self) {
150        self.node_stack.clear();
151        self.context_stack.clear();
152        self.view_stack.clear();
153        self.nodes.clear();
154        self.focusable_node_ids.clear();
155        self.view_node_ids.clear();
156    }
157
158    pub fn len(&self) -> usize {
159        self.nodes.len()
160    }
161
162    pub fn push_node(&mut self) -> DispatchNodeId {
163        let parent = self.node_stack.last().copied();
164        let node_id = DispatchNodeId(self.nodes.len());
165
166        self.nodes.push(DispatchNode {
167            parent,
168            ..Default::default()
169        });
170        self.node_stack.push(node_id);
171        node_id
172    }
173
174    pub fn set_active_node(&mut self, node_id: DispatchNodeId) {
175        let next_node_parent = self.nodes[node_id.0].parent;
176        while self.node_stack.last().copied() != next_node_parent && !self.node_stack.is_empty() {
177            self.pop_node();
178        }
179
180        if self.node_stack.last().copied() == next_node_parent {
181            self.node_stack.push(node_id);
182            let active_node = &self.nodes[node_id.0];
183            if let Some(view_id) = active_node.view_id {
184                self.view_stack.push(view_id)
185            }
186            if let Some(context) = active_node.context.clone() {
187                self.context_stack.push(context);
188            }
189        } else {
190            debug_assert_eq!(self.node_stack.len(), 0);
191
192            let mut current_node_id = Some(node_id);
193            while let Some(node_id) = current_node_id {
194                let node = &self.nodes[node_id.0];
195                if let Some(context) = node.context.clone() {
196                    self.context_stack.push(context);
197                }
198                if node.view_id.is_some() {
199                    self.view_stack.push(node.view_id.unwrap());
200                }
201                self.node_stack.push(node_id);
202                current_node_id = node.parent;
203            }
204
205            self.context_stack.reverse();
206            self.view_stack.reverse();
207            self.node_stack.reverse();
208        }
209    }
210
211    pub fn set_key_context(&mut self, context: KeyContext) {
212        self.active_node().context = Some(context.clone());
213        self.context_stack.push(context);
214    }
215
216    pub fn set_focus_id(&mut self, focus_id: FocusId) {
217        let node_id = *self.node_stack.last().unwrap();
218        self.nodes[node_id.0].focus_id = Some(focus_id);
219        self.focusable_node_ids.insert(focus_id, node_id);
220    }
221
222    pub fn set_view_id(&mut self, view_id: EntityId) {
223        if self.view_stack.last().copied() != Some(view_id) {
224            let node_id = *self.node_stack.last().unwrap();
225            self.nodes[node_id.0].view_id = Some(view_id);
226            self.view_node_ids.insert(view_id, node_id);
227            self.view_stack.push(view_id);
228        }
229    }
230
231    pub fn pop_node(&mut self) {
232        let node = &self.nodes[self.active_node_id().unwrap().0];
233        if node.context.is_some() {
234            self.context_stack.pop();
235        }
236        if node.view_id.is_some() {
237            self.view_stack.pop();
238        }
239        self.node_stack.pop();
240    }
241
242    fn move_node(&mut self, source: &mut DispatchNode) {
243        self.push_node();
244        if let Some(context) = source.context.clone() {
245            self.set_key_context(context);
246        }
247        if let Some(focus_id) = source.focus_id {
248            self.set_focus_id(focus_id);
249        }
250        if let Some(view_id) = source.view_id {
251            self.set_view_id(view_id);
252        }
253
254        let target = self.active_node();
255        target.key_listeners = mem::take(&mut source.key_listeners);
256        target.action_listeners = mem::take(&mut source.action_listeners);
257        target.modifiers_changed_listeners = mem::take(&mut source.modifiers_changed_listeners);
258    }
259
260    pub fn reuse_subtree(
261        &mut self,
262        old_range: Range<usize>,
263        source: &mut Self,
264        focus: Option<FocusId>,
265    ) -> ReusedSubtree {
266        let new_range = self.nodes.len()..self.nodes.len() + old_range.len();
267
268        let mut contains_focus = false;
269        let mut source_stack = vec![];
270        for (source_node_id, source_node) in source
271            .nodes
272            .iter_mut()
273            .enumerate()
274            .skip(old_range.start)
275            .take(old_range.len())
276        {
277            let source_node_id = DispatchNodeId(source_node_id);
278            while let Some(source_ancestor) = source_stack.last() {
279                if source_node.parent == Some(*source_ancestor) {
280                    break;
281                } else {
282                    source_stack.pop();
283                    self.pop_node();
284                }
285            }
286
287            source_stack.push(source_node_id);
288            if source_node.focus_id.is_some() && source_node.focus_id == focus {
289                contains_focus = true;
290            }
291            self.move_node(source_node);
292        }
293
294        while !source_stack.is_empty() {
295            source_stack.pop();
296            self.pop_node();
297        }
298
299        ReusedSubtree {
300            old_range,
301            new_range,
302            contains_focus,
303        }
304    }
305
306    pub fn truncate(&mut self, index: usize) {
307        for node in &self.nodes[index..] {
308            if let Some(focus_id) = node.focus_id {
309                self.focusable_node_ids.remove(&focus_id);
310            }
311
312            if let Some(view_id) = node.view_id {
313                self.view_node_ids.remove(&view_id);
314            }
315        }
316        self.nodes.truncate(index);
317    }
318
319    pub fn on_key_event(&mut self, listener: KeyListener) {
320        self.active_node().key_listeners.push(listener);
321    }
322
323    pub fn on_modifiers_changed(&mut self, listener: ModifiersChangedListener) {
324        self.active_node()
325            .modifiers_changed_listeners
326            .push(listener);
327    }
328
329    pub fn on_action(
330        &mut self,
331        action_type: TypeId,
332        listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App)>,
333    ) {
334        self.active_node()
335            .action_listeners
336            .push(DispatchActionListener {
337                action_type,
338                listener,
339            });
340    }
341
342    pub fn focus_contains(&self, parent: FocusId, child: FocusId) -> bool {
343        if parent == child {
344            return true;
345        }
346
347        if let Some(parent_node_id) = self.focusable_node_ids.get(&parent) {
348            let mut current_node_id = self.focusable_node_ids.get(&child).copied();
349            while let Some(node_id) = current_node_id {
350                if node_id == *parent_node_id {
351                    return true;
352                }
353                current_node_id = self.nodes[node_id.0].parent;
354            }
355        }
356        false
357    }
358
359    pub fn available_actions(&self, target: DispatchNodeId) -> Vec<Box<dyn Action>> {
360        let mut actions = Vec::<Box<dyn Action>>::new();
361        for node_id in self.dispatch_path(target) {
362            let node = &self.nodes[node_id.0];
363            for DispatchActionListener { action_type, .. } in &node.action_listeners {
364                if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id())
365                {
366                    // Intentionally silence these errors without logging.
367                    // If an action cannot be built by default, it's not available.
368                    let action = self.action_registry.build_action_type(action_type).ok();
369                    if let Some(action) = action {
370                        actions.insert(ix, action);
371                    }
372                }
373            }
374        }
375        actions
376    }
377
378    pub fn is_action_available(&self, action: &dyn Action, target: DispatchNodeId) -> bool {
379        for node_id in self.dispatch_path(target) {
380            let node = &self.nodes[node_id.0];
381            if node
382                .action_listeners
383                .iter()
384                .any(|listener| listener.action_type == action.as_any().type_id())
385            {
386                return true;
387            }
388        }
389        false
390    }
391
392    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
393    /// returned in the order they were added. For display, the last binding should take precedence.
394    pub fn bindings_for_action(
395        &self,
396        action: &dyn Action,
397        context_stack: &[KeyContext],
398    ) -> Vec<KeyBinding> {
399        let keymap = self.keymap.borrow();
400        keymap
401            .bindings_for_action(action)
402            .filter(|binding| {
403                let (bindings, _) = keymap.bindings_for_input(&binding.keystrokes, context_stack);
404                bindings
405                    .iter()
406                    .next()
407                    .is_some_and(|b| b.action.partial_eq(action))
408            })
409            .cloned()
410            .collect()
411    }
412
413    fn bindings_for_input(
414        &self,
415        input: &[Keystroke],
416        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
417    ) -> (SmallVec<[KeyBinding; 1]>, bool) {
418        let context_stack: SmallVec<[KeyContext; 4]> = dispatch_path
419            .iter()
420            .filter_map(|node_id| self.node(*node_id).context.clone())
421            .collect();
422
423        self.keymap
424            .borrow()
425            .bindings_for_input(input, &context_stack)
426    }
427
428    /// dispatch_key processes the keystroke
429    /// input should be set to the value of `pending` from the previous call to dispatch_key.
430    /// This returns three instructions to the input handler:
431    /// - bindings: any bindings to execute before processing this keystroke
432    /// - pending: the new set of pending keystrokes to store
433    /// - to_replay: any keystroke that had been pushed to pending, but are no-longer matched,
434    ///   these should be replayed first.
435    pub fn dispatch_key(
436        &mut self,
437        mut input: SmallVec<[Keystroke; 1]>,
438        keystroke: Keystroke,
439        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
440    ) -> DispatchResult {
441        input.push(keystroke.clone());
442        let (bindings, pending) = self.bindings_for_input(&input, dispatch_path);
443
444        if pending {
445            return DispatchResult {
446                pending: input,
447                ..Default::default()
448            };
449        } else if !bindings.is_empty() {
450            return DispatchResult {
451                bindings,
452                ..Default::default()
453            };
454        } else if input.len() == 1 {
455            return DispatchResult::default();
456        }
457        input.pop();
458
459        let (suffix, mut to_replay) = self.replay_prefix(input, dispatch_path);
460
461        let mut result = self.dispatch_key(suffix, keystroke, dispatch_path);
462        to_replay.extend(result.to_replay);
463        result.to_replay = to_replay;
464        result
465    }
466
467    /// If the user types a matching prefix of a binding and then waits for a timeout
468    /// flush_dispatch() converts any previously pending input to replay events.
469    pub fn flush_dispatch(
470        &mut self,
471        input: SmallVec<[Keystroke; 1]>,
472        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
473    ) -> SmallVec<[Replay; 1]> {
474        let (suffix, mut to_replay) = self.replay_prefix(input, dispatch_path);
475
476        if !suffix.is_empty() {
477            to_replay.extend(self.flush_dispatch(suffix, dispatch_path))
478        }
479
480        to_replay
481    }
482
483    /// Converts the longest prefix of input to a replay event and returns the rest.
484    fn replay_prefix(
485        &self,
486        mut input: SmallVec<[Keystroke; 1]>,
487        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
488    ) -> (SmallVec<[Keystroke; 1]>, SmallVec<[Replay; 1]>) {
489        let mut to_replay: SmallVec<[Replay; 1]> = Default::default();
490        for last in (0..input.len()).rev() {
491            let (bindings, _) = self.bindings_for_input(&input[0..=last], dispatch_path);
492            if !bindings.is_empty() {
493                to_replay.push(Replay {
494                    keystroke: input.drain(0..=last).last().unwrap(),
495                    bindings,
496                });
497                break;
498            }
499        }
500        if to_replay.is_empty() {
501            to_replay.push(Replay {
502                keystroke: input.remove(0),
503                ..Default::default()
504            });
505        }
506        (input, to_replay)
507    }
508
509    pub fn dispatch_path(&self, target: DispatchNodeId) -> SmallVec<[DispatchNodeId; 32]> {
510        let mut dispatch_path: SmallVec<[DispatchNodeId; 32]> = SmallVec::new();
511        let mut current_node_id = Some(target);
512        while let Some(node_id) = current_node_id {
513            dispatch_path.push(node_id);
514            current_node_id = self.nodes[node_id.0].parent;
515        }
516        dispatch_path.reverse(); // Reverse the path so it goes from the root to the focused node.
517        dispatch_path
518    }
519
520    pub fn focus_path(&self, focus_id: FocusId) -> SmallVec<[FocusId; 8]> {
521        let mut focus_path: SmallVec<[FocusId; 8]> = SmallVec::new();
522        let mut current_node_id = self.focusable_node_ids.get(&focus_id).copied();
523        while let Some(node_id) = current_node_id {
524            let node = self.node(node_id);
525            if let Some(focus_id) = node.focus_id {
526                focus_path.push(focus_id);
527            }
528            current_node_id = node.parent;
529        }
530        focus_path.reverse(); // Reverse the path so it goes from the root to the focused node.
531        focus_path
532    }
533
534    pub fn view_path(&self, view_id: EntityId) -> SmallVec<[EntityId; 8]> {
535        let mut view_path: SmallVec<[EntityId; 8]> = SmallVec::new();
536        let mut current_node_id = self.view_node_ids.get(&view_id).copied();
537        while let Some(node_id) = current_node_id {
538            let node = self.node(node_id);
539            if let Some(view_id) = node.view_id {
540                view_path.push(view_id);
541            }
542            current_node_id = node.parent;
543        }
544        view_path.reverse(); // Reverse the path so it goes from the root to the view node.
545        view_path
546    }
547
548    pub fn node(&self, node_id: DispatchNodeId) -> &DispatchNode {
549        &self.nodes[node_id.0]
550    }
551
552    fn active_node(&mut self) -> &mut DispatchNode {
553        let active_node_id = self.active_node_id().unwrap();
554        &mut self.nodes[active_node_id.0]
555    }
556
557    pub fn focusable_node_id(&self, target: FocusId) -> Option<DispatchNodeId> {
558        self.focusable_node_ids.get(&target).copied()
559    }
560
561    pub fn root_node_id(&self) -> DispatchNodeId {
562        debug_assert!(!self.nodes.is_empty());
563        DispatchNodeId(0)
564    }
565
566    pub fn active_node_id(&self) -> Option<DispatchNodeId> {
567        self.node_stack.last().copied()
568    }
569}
570
571#[cfg(test)]
572mod tests {
573    use std::{cell::RefCell, rc::Rc};
574
575    use crate::{Action, ActionRegistry, DispatchTree, KeyBinding, KeyContext, Keymap};
576
577    #[derive(PartialEq, Eq)]
578    struct TestAction;
579
580    impl Action for TestAction {
581        fn name(&self) -> &'static str {
582            "test::TestAction"
583        }
584
585        fn debug_name() -> &'static str
586        where
587            Self: ::std::marker::Sized,
588        {
589            "test::TestAction"
590        }
591
592        fn partial_eq(&self, action: &dyn Action) -> bool {
593            action
594                .as_any()
595                .downcast_ref::<Self>()
596                .map_or(false, |a| self == a)
597        }
598
599        fn boxed_clone(&self) -> std::boxed::Box<dyn Action> {
600            Box::new(TestAction)
601        }
602
603        fn as_any(&self) -> &dyn ::std::any::Any {
604            self
605        }
606
607        fn build(_value: serde_json::Value) -> anyhow::Result<Box<dyn Action>>
608        where
609            Self: Sized,
610        {
611            Ok(Box::new(TestAction))
612        }
613    }
614
615    #[test]
616    fn test_keybinding_for_action_bounds() {
617        let keymap = Keymap::new(vec![KeyBinding::new(
618            "cmd-n",
619            TestAction,
620            Some("ProjectPanel"),
621        )]);
622
623        let mut registry = ActionRegistry::default();
624
625        registry.load_action::<TestAction>();
626
627        let keymap = Rc::new(RefCell::new(keymap));
628
629        let tree = DispatchTree::new(keymap, Rc::new(registry));
630
631        let contexts = vec![
632            KeyContext::parse("Workspace").unwrap(),
633            KeyContext::parse("ProjectPanel").unwrap(),
634        ];
635
636        let keybinding = tree.bindings_for_action(&TestAction, &contexts);
637
638        assert!(keybinding[0].action.partial_eq(&TestAction))
639    }
640}