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