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, _cx: &mut ViewContext<Self>) { ... }
 13///   fn redo(&mut self, _: &Redo, _cx: &mut ViewContext<Self>) { ... }
 14/// }
 15///
 16/// impl Render for Editor {
 17///   fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 18///     div()
 19///       .track_focus(&self.focus_handle)
 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, DispatchPhase, ElementContext, EntityId, FocusId, KeyBinding,
 54    KeyContext, Keymap, KeymatchResult, Keystroke, KeystrokeMatcher, ModifiersChangedEvent,
 55    WindowContext,
 56};
 57use collections::FxHashMap;
 58use smallvec::SmallVec;
 59use std::{
 60    any::{Any, TypeId},
 61    cell::RefCell,
 62    mem,
 63    ops::Range,
 64    rc::Rc,
 65};
 66
 67#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
 68pub(crate) struct DispatchNodeId(usize);
 69
 70pub(crate) struct DispatchTree {
 71    node_stack: Vec<DispatchNodeId>,
 72    pub(crate) context_stack: Vec<KeyContext>,
 73    view_stack: Vec<EntityId>,
 74    nodes: Vec<DispatchNode>,
 75    focusable_node_ids: FxHashMap<FocusId, DispatchNodeId>,
 76    view_node_ids: FxHashMap<EntityId, DispatchNodeId>,
 77    keystroke_matchers: FxHashMap<SmallVec<[KeyContext; 4]>, KeystrokeMatcher>,
 78    keymap: Rc<RefCell<Keymap>>,
 79    action_registry: Rc<ActionRegistry>,
 80}
 81
 82#[derive(Default)]
 83pub(crate) struct DispatchNode {
 84    pub key_listeners: Vec<KeyListener>,
 85    pub action_listeners: Vec<DispatchActionListener>,
 86    pub modifiers_changed_listeners: Vec<ModifiersChangedListener>,
 87    pub context: Option<KeyContext>,
 88    pub focus_id: Option<FocusId>,
 89    view_id: Option<EntityId>,
 90    parent: Option<DispatchNodeId>,
 91}
 92
 93pub(crate) struct ReusedSubtree {
 94    old_range: Range<usize>,
 95    new_range: Range<usize>,
 96}
 97
 98impl ReusedSubtree {
 99    pub fn refresh_node_id(&self, node_id: DispatchNodeId) -> DispatchNodeId {
100        debug_assert!(
101            self.old_range.contains(&node_id.0),
102            "node {} was not part of the reused subtree {:?}",
103            node_id.0,
104            self.old_range
105        );
106        DispatchNodeId((node_id.0 - self.old_range.start) + self.new_range.start)
107    }
108}
109
110type KeyListener = Rc<dyn Fn(&dyn Any, DispatchPhase, &mut ElementContext)>;
111type ModifiersChangedListener = Rc<dyn Fn(&ModifiersChangedEvent, &mut ElementContext)>;
112
113#[derive(Clone)]
114pub(crate) struct DispatchActionListener {
115    pub(crate) action_type: TypeId,
116    pub(crate) listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>,
117}
118
119impl DispatchTree {
120    pub fn new(keymap: Rc<RefCell<Keymap>>, action_registry: Rc<ActionRegistry>) -> Self {
121        Self {
122            node_stack: Vec::new(),
123            context_stack: Vec::new(),
124            view_stack: Vec::new(),
125            nodes: Vec::new(),
126            focusable_node_ids: FxHashMap::default(),
127            view_node_ids: FxHashMap::default(),
128            keystroke_matchers: FxHashMap::default(),
129            keymap,
130            action_registry,
131        }
132    }
133
134    pub fn clear(&mut self) {
135        self.node_stack.clear();
136        self.context_stack.clear();
137        self.view_stack.clear();
138        self.nodes.clear();
139        self.focusable_node_ids.clear();
140        self.view_node_ids.clear();
141        self.keystroke_matchers.clear();
142    }
143
144    pub fn len(&self) -> usize {
145        self.nodes.len()
146    }
147
148    pub fn push_node(&mut self) -> DispatchNodeId {
149        let parent = self.node_stack.last().copied();
150        let node_id = DispatchNodeId(self.nodes.len());
151
152        self.nodes.push(DispatchNode {
153            parent,
154            ..Default::default()
155        });
156        self.node_stack.push(node_id);
157        node_id
158    }
159
160    pub fn set_active_node(&mut self, node_id: DispatchNodeId) {
161        let next_node_parent = self.nodes[node_id.0].parent;
162        while self.node_stack.last().copied() != next_node_parent && !self.node_stack.is_empty() {
163            self.pop_node();
164        }
165
166        if self.node_stack.last().copied() == next_node_parent {
167            self.node_stack.push(node_id);
168            let active_node = &self.nodes[node_id.0];
169            if let Some(view_id) = active_node.view_id {
170                self.view_stack.push(view_id)
171            }
172            if let Some(context) = active_node.context.clone() {
173                self.context_stack.push(context);
174            }
175        } else {
176            debug_assert_eq!(self.node_stack.len(), 0);
177
178            let mut current_node_id = Some(node_id);
179            while let Some(node_id) = current_node_id {
180                let node = &self.nodes[node_id.0];
181                if let Some(context) = node.context.clone() {
182                    self.context_stack.push(context);
183                }
184                if node.view_id.is_some() {
185                    self.view_stack.push(node.view_id.unwrap());
186                }
187                self.node_stack.push(node_id);
188                current_node_id = node.parent;
189            }
190
191            self.context_stack.reverse();
192            self.view_stack.reverse();
193            self.node_stack.reverse();
194        }
195    }
196
197    pub fn set_key_context(&mut self, context: KeyContext) {
198        self.active_node().context = Some(context.clone());
199        self.context_stack.push(context);
200    }
201
202    pub fn set_focus_id(&mut self, focus_id: FocusId) {
203        let node_id = *self.node_stack.last().unwrap();
204        self.nodes[node_id.0].focus_id = Some(focus_id);
205        self.focusable_node_ids.insert(focus_id, node_id);
206    }
207
208    pub fn parent_view_id(&mut self) -> Option<EntityId> {
209        self.view_stack.last().copied()
210    }
211
212    pub fn set_view_id(&mut self, view_id: EntityId) {
213        if self.view_stack.last().copied() != Some(view_id) {
214            let node_id = *self.node_stack.last().unwrap();
215            self.nodes[node_id.0].view_id = Some(view_id);
216            self.view_node_ids.insert(view_id, node_id);
217            self.view_stack.push(view_id);
218        }
219    }
220
221    pub fn pop_node(&mut self) {
222        let node = &self.nodes[self.active_node_id().unwrap().0];
223        if node.context.is_some() {
224            self.context_stack.pop();
225        }
226        if node.view_id.is_some() {
227            self.view_stack.pop();
228        }
229        self.node_stack.pop();
230    }
231
232    fn move_node(&mut self, source: &mut DispatchNode) {
233        self.push_node();
234        if let Some(context) = source.context.clone() {
235            self.set_key_context(context);
236        }
237        if let Some(focus_id) = source.focus_id {
238            self.set_focus_id(focus_id);
239        }
240        if let Some(view_id) = source.view_id {
241            self.set_view_id(view_id);
242        }
243
244        let target = self.active_node();
245        target.key_listeners = mem::take(&mut source.key_listeners);
246        target.action_listeners = mem::take(&mut source.action_listeners);
247        target.modifiers_changed_listeners = mem::take(&mut source.modifiers_changed_listeners);
248    }
249
250    pub fn reuse_subtree(&mut self, old_range: Range<usize>, source: &mut Self) -> ReusedSubtree {
251        let new_range = self.nodes.len()..self.nodes.len() + old_range.len();
252
253        let mut source_stack = vec![];
254        for (source_node_id, source_node) in source
255            .nodes
256            .iter_mut()
257            .enumerate()
258            .skip(old_range.start)
259            .take(old_range.len())
260        {
261            let source_node_id = DispatchNodeId(source_node_id);
262            while let Some(source_ancestor) = source_stack.last() {
263                if source_node.parent == Some(*source_ancestor) {
264                    break;
265                } else {
266                    source_stack.pop();
267                    self.pop_node();
268                }
269            }
270
271            source_stack.push(source_node_id);
272            self.move_node(source_node);
273        }
274
275        while !source_stack.is_empty() {
276            source_stack.pop();
277            self.pop_node();
278        }
279
280        ReusedSubtree {
281            old_range,
282            new_range,
283        }
284    }
285
286    pub fn clear_pending_keystrokes(&mut self) {
287        self.keystroke_matchers.clear();
288    }
289
290    /// Preserve keystroke matchers from previous frames to support multi-stroke
291    /// bindings across multiple frames.
292    pub fn preserve_pending_keystrokes(&mut self, old_tree: &mut Self, focus_id: Option<FocusId>) {
293        if let Some(node_id) = focus_id.and_then(|focus_id| self.focusable_node_id(focus_id)) {
294            let dispatch_path = self.dispatch_path(node_id);
295
296            self.context_stack.clear();
297            for node_id in dispatch_path {
298                let node = self.node(node_id);
299                if let Some(context) = node.context.clone() {
300                    self.context_stack.push(context);
301                }
302
303                if let Some((context_stack, matcher)) = old_tree
304                    .keystroke_matchers
305                    .remove_entry(self.context_stack.as_slice())
306                {
307                    self.keystroke_matchers.insert(context_stack, matcher);
308                }
309            }
310        }
311    }
312
313    pub fn on_key_event(&mut self, listener: KeyListener) {
314        self.active_node().key_listeners.push(listener);
315    }
316
317    pub fn on_modifiers_changed(&mut self, listener: ModifiersChangedListener) {
318        self.active_node()
319            .modifiers_changed_listeners
320            .push(listener);
321    }
322
323    pub fn on_action(
324        &mut self,
325        action_type: TypeId,
326        listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>,
327    ) {
328        self.active_node()
329            .action_listeners
330            .push(DispatchActionListener {
331                action_type,
332                listener,
333            });
334    }
335
336    pub fn focus_contains(&self, parent: FocusId, child: FocusId) -> bool {
337        if parent == child {
338            return true;
339        }
340
341        if let Some(parent_node_id) = self.focusable_node_ids.get(&parent) {
342            let mut current_node_id = self.focusable_node_ids.get(&child).copied();
343            while let Some(node_id) = current_node_id {
344                if node_id == *parent_node_id {
345                    return true;
346                }
347                current_node_id = self.nodes[node_id.0].parent;
348            }
349        }
350        false
351    }
352
353    pub fn available_actions(&self, target: DispatchNodeId) -> Vec<Box<dyn Action>> {
354        let mut actions = Vec::<Box<dyn Action>>::new();
355        for node_id in self.dispatch_path(target) {
356            let node = &self.nodes[node_id.0];
357            for DispatchActionListener { action_type, .. } in &node.action_listeners {
358                if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id())
359                {
360                    // Intentionally silence these errors without logging.
361                    // If an action cannot be built by default, it's not available.
362                    let action = self.action_registry.build_action_type(action_type).ok();
363                    if let Some(action) = action {
364                        actions.insert(ix, action);
365                    }
366                }
367            }
368        }
369        actions
370    }
371
372    pub fn is_action_available(&self, action: &dyn Action, target: DispatchNodeId) -> bool {
373        for node_id in self.dispatch_path(target) {
374            let node = &self.nodes[node_id.0];
375            if node
376                .action_listeners
377                .iter()
378                .any(|listener| listener.action_type == action.as_any().type_id())
379            {
380                return true;
381            }
382        }
383        false
384    }
385
386    pub fn bindings_for_action(
387        &self,
388        action: &dyn Action,
389        context_stack: &[KeyContext],
390    ) -> Vec<KeyBinding> {
391        let keymap = self.keymap.borrow();
392        keymap
393            .bindings_for_action(action)
394            .filter(|binding| {
395                for i in 0..context_stack.len() {
396                    let context = &context_stack[0..=i];
397                    if keymap.binding_enabled(binding, context) {
398                        return true;
399                    }
400                }
401                false
402            })
403            .cloned()
404            .collect()
405    }
406
407    // dispatch_key pushes the next keystroke into any key binding matchers.
408    // any matching bindings are returned in the order that they should be dispatched:
409    // * First by length of binding (so if you have a binding for "b" and "ab", the "ab" binding fires first)
410    // * Secondly by depth in the tree (so if Editor has a binding for "b" and workspace a
411    // binding for "b", the Editor action fires first).
412    pub fn dispatch_key(
413        &mut self,
414        keystroke: &Keystroke,
415        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
416    ) -> KeymatchResult {
417        let mut bindings = SmallVec::<[KeyBinding; 1]>::new();
418        let mut pending = false;
419
420        let mut context_stack: SmallVec<[KeyContext; 4]> = SmallVec::new();
421        for node_id in dispatch_path {
422            let node = self.node(*node_id);
423
424            if let Some(context) = node.context.clone() {
425                context_stack.push(context);
426            }
427        }
428
429        while !context_stack.is_empty() {
430            let keystroke_matcher = self
431                .keystroke_matchers
432                .entry(context_stack.clone())
433                .or_insert_with(|| KeystrokeMatcher::new(self.keymap.clone()));
434
435            let result = keystroke_matcher.match_keystroke(keystroke, &context_stack);
436            if result.pending && !pending && !bindings.is_empty() {
437                context_stack.pop();
438                continue;
439            }
440
441            pending = result.pending || pending;
442            for new_binding in result.bindings {
443                match bindings
444                    .iter()
445                    .position(|el| el.keystrokes.len() < new_binding.keystrokes.len())
446                {
447                    Some(idx) => {
448                        bindings.insert(idx, new_binding);
449                    }
450                    None => bindings.push(new_binding),
451                }
452            }
453            context_stack.pop();
454        }
455
456        KeymatchResult { bindings, pending }
457    }
458
459    pub fn has_pending_keystrokes(&self) -> bool {
460        self.keystroke_matchers
461            .iter()
462            .any(|(_, matcher)| matcher.has_pending_keystrokes())
463    }
464
465    pub fn dispatch_path(&self, target: DispatchNodeId) -> SmallVec<[DispatchNodeId; 32]> {
466        let mut dispatch_path: SmallVec<[DispatchNodeId; 32]> = SmallVec::new();
467        let mut current_node_id = Some(target);
468        while let Some(node_id) = current_node_id {
469            dispatch_path.push(node_id);
470            current_node_id = self.nodes[node_id.0].parent;
471        }
472        dispatch_path.reverse(); // Reverse the path so it goes from the root to the focused node.
473        dispatch_path
474    }
475
476    pub fn focus_path(&self, focus_id: FocusId) -> SmallVec<[FocusId; 8]> {
477        let mut focus_path: SmallVec<[FocusId; 8]> = SmallVec::new();
478        let mut current_node_id = self.focusable_node_ids.get(&focus_id).copied();
479        while let Some(node_id) = current_node_id {
480            let node = self.node(node_id);
481            if let Some(focus_id) = node.focus_id {
482                focus_path.push(focus_id);
483            }
484            current_node_id = node.parent;
485        }
486        focus_path.reverse(); // Reverse the path so it goes from the root to the focused node.
487        focus_path
488    }
489
490    pub fn view_path(&self, view_id: EntityId) -> SmallVec<[EntityId; 8]> {
491        let mut view_path: SmallVec<[EntityId; 8]> = SmallVec::new();
492        let mut current_node_id = self.view_node_ids.get(&view_id).copied();
493        while let Some(node_id) = current_node_id {
494            let node = self.node(node_id);
495            if let Some(view_id) = node.view_id {
496                view_path.push(view_id);
497            }
498            current_node_id = node.parent;
499        }
500        view_path.reverse(); // Reverse the path so it goes from the root to the view node.
501        view_path
502    }
503
504    pub fn node(&self, node_id: DispatchNodeId) -> &DispatchNode {
505        &self.nodes[node_id.0]
506    }
507
508    fn active_node(&mut self) -> &mut DispatchNode {
509        let active_node_id = self.active_node_id().unwrap();
510        &mut self.nodes[active_node_id.0]
511    }
512
513    pub fn focusable_node_id(&self, target: FocusId) -> Option<DispatchNodeId> {
514        self.focusable_node_ids.get(&target).copied()
515    }
516
517    pub fn root_node_id(&self) -> DispatchNodeId {
518        debug_assert!(!self.nodes.is_empty());
519        DispatchNodeId(0)
520    }
521
522    pub fn active_node_id(&self) -> Option<DispatchNodeId> {
523        self.node_stack.last().copied()
524    }
525}
526
527#[cfg(test)]
528mod tests {
529    use std::{cell::RefCell, rc::Rc};
530
531    use crate::{Action, ActionRegistry, DispatchTree, KeyBinding, KeyContext, Keymap};
532
533    #[derive(PartialEq, Eq)]
534    struct TestAction;
535
536    impl Action for TestAction {
537        fn name(&self) -> &'static str {
538            "test::TestAction"
539        }
540
541        fn debug_name() -> &'static str
542        where
543            Self: ::std::marker::Sized,
544        {
545            "test::TestAction"
546        }
547
548        fn partial_eq(&self, action: &dyn Action) -> bool {
549            action
550                .as_any()
551                .downcast_ref::<Self>()
552                .map_or(false, |a| self == a)
553        }
554
555        fn boxed_clone(&self) -> std::boxed::Box<dyn Action> {
556            Box::new(TestAction)
557        }
558
559        fn as_any(&self) -> &dyn ::std::any::Any {
560            self
561        }
562
563        fn build(_value: serde_json::Value) -> anyhow::Result<Box<dyn Action>>
564        where
565            Self: Sized,
566        {
567            Ok(Box::new(TestAction))
568        }
569    }
570
571    #[test]
572    fn test_keybinding_for_action_bounds() {
573        let keymap = Keymap::new(vec![KeyBinding::new(
574            "cmd-n",
575            TestAction,
576            Some("ProjectPanel"),
577        )]);
578
579        let mut registry = ActionRegistry::default();
580
581        registry.load_action::<TestAction>();
582
583        let keymap = Rc::new(RefCell::new(keymap));
584
585        let tree = DispatchTree::new(keymap, Rc::new(registry));
586
587        let contexts = vec![
588            KeyContext::parse("Workspace").unwrap(),
589            KeyContext::parse("ProjectPanel").unwrap(),
590        ];
591
592        let keybinding = tree.bindings_for_action(&TestAction, &contexts);
593
594        assert!(keybinding[0].action.partial_eq(&TestAction))
595    }
596}