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