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 parent_view_id(&self) -> Option<EntityId> {
223        self.view_stack.last().copied()
224    }
225
226    pub fn set_view_id(&mut self, view_id: EntityId) {
227        if self.view_stack.last().copied() != Some(view_id) {
228            let node_id = *self.node_stack.last().unwrap();
229            self.nodes[node_id.0].view_id = Some(view_id);
230            self.view_node_ids.insert(view_id, node_id);
231            self.view_stack.push(view_id);
232        }
233    }
234
235    pub fn pop_node(&mut self) {
236        let node = &self.nodes[self.active_node_id().unwrap().0];
237        if node.context.is_some() {
238            self.context_stack.pop();
239        }
240        if node.view_id.is_some() {
241            self.view_stack.pop();
242        }
243        self.node_stack.pop();
244    }
245
246    fn move_node(&mut self, source: &mut DispatchNode) {
247        self.push_node();
248        if let Some(context) = source.context.clone() {
249            self.set_key_context(context);
250        }
251        if let Some(focus_id) = source.focus_id {
252            self.set_focus_id(focus_id);
253        }
254        if let Some(view_id) = source.view_id {
255            self.set_view_id(view_id);
256        }
257
258        let target = self.active_node();
259        target.key_listeners = mem::take(&mut source.key_listeners);
260        target.action_listeners = mem::take(&mut source.action_listeners);
261        target.modifiers_changed_listeners = mem::take(&mut source.modifiers_changed_listeners);
262    }
263
264    pub fn reuse_subtree(
265        &mut self,
266        old_range: Range<usize>,
267        source: &mut Self,
268        focus: Option<FocusId>,
269    ) -> ReusedSubtree {
270        let new_range = self.nodes.len()..self.nodes.len() + old_range.len();
271
272        let mut contains_focus = false;
273        let mut source_stack = vec![];
274        for (source_node_id, source_node) in source
275            .nodes
276            .iter_mut()
277            .enumerate()
278            .skip(old_range.start)
279            .take(old_range.len())
280        {
281            let source_node_id = DispatchNodeId(source_node_id);
282            while let Some(source_ancestor) = source_stack.last() {
283                if source_node.parent == Some(*source_ancestor) {
284                    break;
285                } else {
286                    source_stack.pop();
287                    self.pop_node();
288                }
289            }
290
291            source_stack.push(source_node_id);
292            if source_node.focus_id.is_some() && source_node.focus_id == focus {
293                contains_focus = true;
294            }
295            self.move_node(source_node);
296        }
297
298        while !source_stack.is_empty() {
299            source_stack.pop();
300            self.pop_node();
301        }
302
303        ReusedSubtree {
304            old_range,
305            new_range,
306            contains_focus,
307        }
308    }
309
310    pub fn truncate(&mut self, index: usize) {
311        for node in &self.nodes[index..] {
312            if let Some(focus_id) = node.focus_id {
313                self.focusable_node_ids.remove(&focus_id);
314            }
315
316            if let Some(view_id) = node.view_id {
317                self.view_node_ids.remove(&view_id);
318            }
319        }
320        self.nodes.truncate(index);
321    }
322
323    pub fn on_key_event(&mut self, listener: KeyListener) {
324        self.active_node().key_listeners.push(listener);
325    }
326
327    pub fn on_modifiers_changed(&mut self, listener: ModifiersChangedListener) {
328        self.active_node()
329            .modifiers_changed_listeners
330            .push(listener);
331    }
332
333    pub fn on_action(
334        &mut self,
335        action_type: TypeId,
336        listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App)>,
337    ) {
338        self.active_node()
339            .action_listeners
340            .push(DispatchActionListener {
341                action_type,
342                listener,
343            });
344    }
345
346    pub fn focus_contains(&self, parent: FocusId, child: FocusId) -> bool {
347        if parent == child {
348            return true;
349        }
350
351        if let Some(parent_node_id) = self.focusable_node_ids.get(&parent) {
352            let mut current_node_id = self.focusable_node_ids.get(&child).copied();
353            while let Some(node_id) = current_node_id {
354                if node_id == *parent_node_id {
355                    return true;
356                }
357                current_node_id = self.nodes[node_id.0].parent;
358            }
359        }
360        false
361    }
362
363    pub fn available_actions(&self, target: DispatchNodeId) -> Vec<Box<dyn Action>> {
364        let mut actions = Vec::<Box<dyn Action>>::new();
365        for node_id in self.dispatch_path(target) {
366            let node = &self.nodes[node_id.0];
367            for DispatchActionListener { action_type, .. } in &node.action_listeners {
368                if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id())
369                {
370                    // Intentionally silence these errors without logging.
371                    // If an action cannot be built by default, it's not available.
372                    let action = self.action_registry.build_action_type(action_type).ok();
373                    if let Some(action) = action {
374                        actions.insert(ix, action);
375                    }
376                }
377            }
378        }
379        actions
380    }
381
382    pub fn is_action_available(&self, action: &dyn Action, target: DispatchNodeId) -> bool {
383        for node_id in self.dispatch_path(target) {
384            let node = &self.nodes[node_id.0];
385            if node
386                .action_listeners
387                .iter()
388                .any(|listener| listener.action_type == action.as_any().type_id())
389            {
390                return true;
391            }
392        }
393        false
394    }
395
396    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
397    /// returned in the order they were added. For display, the last binding should take precedence.
398    pub fn bindings_for_action(
399        &self,
400        action: &dyn Action,
401        context_stack: &[KeyContext],
402    ) -> Vec<KeyBinding> {
403        let keymap = self.keymap.borrow();
404        keymap
405            .bindings_for_action(action)
406            .filter(|binding| {
407                let (bindings, _) = keymap.bindings_for_input(&binding.keystrokes, context_stack);
408                bindings
409                    .iter()
410                    .next()
411                    .is_some_and(|b| b.action.partial_eq(action))
412            })
413            .cloned()
414            .collect()
415    }
416
417    fn bindings_for_input(
418        &self,
419        input: &[Keystroke],
420        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
421    ) -> (SmallVec<[KeyBinding; 1]>, bool) {
422        let context_stack: SmallVec<[KeyContext; 4]> = dispatch_path
423            .iter()
424            .filter_map(|node_id| self.node(*node_id).context.clone())
425            .collect();
426
427        self.keymap
428            .borrow()
429            .bindings_for_input(input, &context_stack)
430    }
431
432    /// dispatch_key processes the keystroke
433    /// input should be set to the value of `pending` from the previous call to dispatch_key.
434    /// This returns three instructions to the input handler:
435    /// - bindings: any bindings to execute before processing this keystroke
436    /// - pending: the new set of pending keystrokes to store
437    /// - to_replay: any keystroke that had been pushed to pending, but are no-longer matched,
438    ///   these should be replayed first.
439    pub fn dispatch_key(
440        &mut self,
441        mut input: SmallVec<[Keystroke; 1]>,
442        keystroke: Keystroke,
443        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
444    ) -> DispatchResult {
445        input.push(keystroke.clone());
446        let (bindings, pending) = self.bindings_for_input(&input, dispatch_path);
447
448        if pending {
449            return DispatchResult {
450                pending: input,
451                ..Default::default()
452            };
453        } else if !bindings.is_empty() {
454            return DispatchResult {
455                bindings,
456                ..Default::default()
457            };
458        } else if input.len() == 1 {
459            return DispatchResult::default();
460        }
461        input.pop();
462
463        let (suffix, mut to_replay) = self.replay_prefix(input, dispatch_path);
464
465        let mut result = self.dispatch_key(suffix, keystroke, dispatch_path);
466        to_replay.extend(result.to_replay);
467        result.to_replay = to_replay;
468        result
469    }
470
471    /// If the user types a matching prefix of a binding and then waits for a timeout
472    /// flush_dispatch() converts any previously pending input to replay events.
473    pub fn flush_dispatch(
474        &mut self,
475        input: SmallVec<[Keystroke; 1]>,
476        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
477    ) -> SmallVec<[Replay; 1]> {
478        let (suffix, mut to_replay) = self.replay_prefix(input, dispatch_path);
479
480        if !suffix.is_empty() {
481            to_replay.extend(self.flush_dispatch(suffix, dispatch_path))
482        }
483
484        to_replay
485    }
486
487    /// Converts the longest prefix of input to a replay event and returns the rest.
488    fn replay_prefix(
489        &self,
490        mut input: SmallVec<[Keystroke; 1]>,
491        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
492    ) -> (SmallVec<[Keystroke; 1]>, SmallVec<[Replay; 1]>) {
493        let mut to_replay: SmallVec<[Replay; 1]> = Default::default();
494        for last in (0..input.len()).rev() {
495            let (bindings, _) = self.bindings_for_input(&input[0..=last], dispatch_path);
496            if !bindings.is_empty() {
497                to_replay.push(Replay {
498                    keystroke: input.drain(0..=last).last().unwrap(),
499                    bindings,
500                });
501                break;
502            }
503        }
504        if to_replay.is_empty() {
505            to_replay.push(Replay {
506                keystroke: input.remove(0),
507                ..Default::default()
508            });
509        }
510        (input, to_replay)
511    }
512
513    pub fn dispatch_path(&self, target: DispatchNodeId) -> SmallVec<[DispatchNodeId; 32]> {
514        let mut dispatch_path: SmallVec<[DispatchNodeId; 32]> = SmallVec::new();
515        let mut current_node_id = Some(target);
516        while let Some(node_id) = current_node_id {
517            dispatch_path.push(node_id);
518            current_node_id = self.nodes[node_id.0].parent;
519        }
520        dispatch_path.reverse(); // Reverse the path so it goes from the root to the focused node.
521        dispatch_path
522    }
523
524    pub fn focus_path(&self, focus_id: FocusId) -> SmallVec<[FocusId; 8]> {
525        let mut focus_path: SmallVec<[FocusId; 8]> = SmallVec::new();
526        let mut current_node_id = self.focusable_node_ids.get(&focus_id).copied();
527        while let Some(node_id) = current_node_id {
528            let node = self.node(node_id);
529            if let Some(focus_id) = node.focus_id {
530                focus_path.push(focus_id);
531            }
532            current_node_id = node.parent;
533        }
534        focus_path.reverse(); // Reverse the path so it goes from the root to the focused node.
535        focus_path
536    }
537
538    pub fn view_path(&self, view_id: EntityId) -> SmallVec<[EntityId; 8]> {
539        let mut view_path: SmallVec<[EntityId; 8]> = SmallVec::new();
540        let mut current_node_id = self.view_node_ids.get(&view_id).copied();
541        while let Some(node_id) = current_node_id {
542            let node = self.node(node_id);
543            if let Some(view_id) = node.view_id {
544                view_path.push(view_id);
545            }
546            current_node_id = node.parent;
547        }
548        view_path.reverse(); // Reverse the path so it goes from the root to the view node.
549        view_path
550    }
551
552    pub fn node(&self, node_id: DispatchNodeId) -> &DispatchNode {
553        &self.nodes[node_id.0]
554    }
555
556    fn active_node(&mut self) -> &mut DispatchNode {
557        let active_node_id = self.active_node_id().unwrap();
558        &mut self.nodes[active_node_id.0]
559    }
560
561    pub fn focusable_node_id(&self, target: FocusId) -> Option<DispatchNodeId> {
562        self.focusable_node_ids.get(&target).copied()
563    }
564
565    pub fn root_node_id(&self) -> DispatchNodeId {
566        debug_assert!(!self.nodes.is_empty());
567        DispatchNodeId(0)
568    }
569
570    pub fn active_node_id(&self) -> Option<DispatchNodeId> {
571        self.node_stack.last().copied()
572    }
573}
574
575#[cfg(test)]
576mod tests {
577    use std::{cell::RefCell, rc::Rc};
578
579    use crate::{Action, ActionRegistry, DispatchTree, KeyBinding, KeyContext, Keymap};
580
581    #[derive(PartialEq, Eq)]
582    struct TestAction;
583
584    impl Action for TestAction {
585        fn name(&self) -> &'static str {
586            "test::TestAction"
587        }
588
589        fn debug_name() -> &'static str
590        where
591            Self: ::std::marker::Sized,
592        {
593            "test::TestAction"
594        }
595
596        fn partial_eq(&self, action: &dyn Action) -> bool {
597            action
598                .as_any()
599                .downcast_ref::<Self>()
600                .map_or(false, |a| self == a)
601        }
602
603        fn boxed_clone(&self) -> std::boxed::Box<dyn Action> {
604            Box::new(TestAction)
605        }
606
607        fn as_any(&self) -> &dyn ::std::any::Any {
608            self
609        }
610
611        fn build(_value: serde_json::Value) -> anyhow::Result<Box<dyn Action>>
612        where
613            Self: Sized,
614        {
615            Ok(Box::new(TestAction))
616        }
617    }
618
619    #[test]
620    fn test_keybinding_for_action_bounds() {
621        let keymap = Keymap::new(vec![KeyBinding::new(
622            "cmd-n",
623            TestAction,
624            Some("ProjectPanel"),
625        )]);
626
627        let mut registry = ActionRegistry::default();
628
629        registry.load_action::<TestAction>();
630
631        let keymap = Rc::new(RefCell::new(keymap));
632
633        let tree = DispatchTree::new(keymap, Rc::new(registry));
634
635        let contexts = vec![
636            KeyContext::parse("Workspace").unwrap(),
637            KeyContext::parse("ProjectPanel").unwrap(),
638        ];
639
640        let keybinding = tree.bindings_for_action(&TestAction, &contexts);
641
642        assert!(keybinding[0].action.partial_eq(&TestAction))
643    }
644}