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 truncate(&mut self, index: usize) {
287 for node in &self.nodes[index..] {
288 if let Some(focus_id) = node.focus_id {
289 self.focusable_node_ids.remove(&focus_id);
290 }
291
292 if let Some(view_id) = node.view_id {
293 self.view_node_ids.remove(&view_id);
294 }
295 }
296 self.nodes.truncate(index);
297 }
298
299 pub fn clear_pending_keystrokes(&mut self) {
300 self.keystroke_matchers.clear();
301 }
302
303 /// Preserve keystroke matchers from previous frames to support multi-stroke
304 /// bindings across multiple frames.
305 pub fn preserve_pending_keystrokes(&mut self, old_tree: &mut Self, focus_id: Option<FocusId>) {
306 if let Some(node_id) = focus_id.and_then(|focus_id| self.focusable_node_id(focus_id)) {
307 let dispatch_path = self.dispatch_path(node_id);
308
309 self.context_stack.clear();
310 for node_id in dispatch_path {
311 let node = self.node(node_id);
312 if let Some(context) = node.context.clone() {
313 self.context_stack.push(context);
314 }
315
316 if let Some((context_stack, matcher)) = old_tree
317 .keystroke_matchers
318 .remove_entry(self.context_stack.as_slice())
319 {
320 self.keystroke_matchers.insert(context_stack, matcher);
321 }
322 }
323 }
324 }
325
326 pub fn on_key_event(&mut self, listener: KeyListener) {
327 self.active_node().key_listeners.push(listener);
328 }
329
330 pub fn on_modifiers_changed(&mut self, listener: ModifiersChangedListener) {
331 self.active_node()
332 .modifiers_changed_listeners
333 .push(listener);
334 }
335
336 pub fn on_action(
337 &mut self,
338 action_type: TypeId,
339 listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>,
340 ) {
341 self.active_node()
342 .action_listeners
343 .push(DispatchActionListener {
344 action_type,
345 listener,
346 });
347 }
348
349 pub fn focus_contains(&self, parent: FocusId, child: FocusId) -> bool {
350 if parent == child {
351 return true;
352 }
353
354 if let Some(parent_node_id) = self.focusable_node_ids.get(&parent) {
355 let mut current_node_id = self.focusable_node_ids.get(&child).copied();
356 while let Some(node_id) = current_node_id {
357 if node_id == *parent_node_id {
358 return true;
359 }
360 current_node_id = self.nodes[node_id.0].parent;
361 }
362 }
363 false
364 }
365
366 pub fn available_actions(&self, target: DispatchNodeId) -> Vec<Box<dyn Action>> {
367 let mut actions = Vec::<Box<dyn Action>>::new();
368 for node_id in self.dispatch_path(target) {
369 let node = &self.nodes[node_id.0];
370 for DispatchActionListener { action_type, .. } in &node.action_listeners {
371 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id())
372 {
373 // Intentionally silence these errors without logging.
374 // If an action cannot be built by default, it's not available.
375 let action = self.action_registry.build_action_type(action_type).ok();
376 if let Some(action) = action {
377 actions.insert(ix, action);
378 }
379 }
380 }
381 }
382 actions
383 }
384
385 pub fn is_action_available(&self, action: &dyn Action, target: DispatchNodeId) -> bool {
386 for node_id in self.dispatch_path(target) {
387 let node = &self.nodes[node_id.0];
388 if node
389 .action_listeners
390 .iter()
391 .any(|listener| listener.action_type == action.as_any().type_id())
392 {
393 return true;
394 }
395 }
396 false
397 }
398
399 pub fn bindings_for_action(
400 &self,
401 action: &dyn Action,
402 context_stack: &[KeyContext],
403 ) -> Vec<KeyBinding> {
404 let keymap = self.keymap.borrow();
405 keymap
406 .bindings_for_action(action)
407 .filter(|binding| {
408 for i in 0..context_stack.len() {
409 let context = &context_stack[0..=i];
410 if keymap.binding_enabled(binding, context) {
411 return true;
412 }
413 }
414 false
415 })
416 .cloned()
417 .collect()
418 }
419
420 // dispatch_key pushes the next keystroke into any key binding matchers.
421 // any matching bindings are returned in the order that they should be dispatched:
422 // * First by length of binding (so if you have a binding for "b" and "ab", the "ab" binding fires first)
423 // * Secondly by depth in the tree (so if Editor has a binding for "b" and workspace a
424 // binding for "b", the Editor action fires first).
425 pub fn dispatch_key(
426 &mut self,
427 keystroke: &Keystroke,
428 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
429 ) -> KeymatchResult {
430 let mut bindings = SmallVec::<[KeyBinding; 1]>::new();
431 let mut pending = false;
432
433 let mut context_stack: SmallVec<[KeyContext; 4]> = SmallVec::new();
434 for node_id in dispatch_path {
435 let node = self.node(*node_id);
436
437 if let Some(context) = node.context.clone() {
438 context_stack.push(context);
439 }
440 }
441
442 while !context_stack.is_empty() {
443 let keystroke_matcher = self
444 .keystroke_matchers
445 .entry(context_stack.clone())
446 .or_insert_with(|| KeystrokeMatcher::new(self.keymap.clone()));
447
448 let result = keystroke_matcher.match_keystroke(keystroke, &context_stack);
449 if result.pending && !pending && !bindings.is_empty() {
450 context_stack.pop();
451 continue;
452 }
453
454 pending = result.pending || pending;
455 for new_binding in result.bindings {
456 match bindings
457 .iter()
458 .position(|el| el.keystrokes.len() < new_binding.keystrokes.len())
459 {
460 Some(idx) => {
461 bindings.insert(idx, new_binding);
462 }
463 None => bindings.push(new_binding),
464 }
465 }
466 context_stack.pop();
467 }
468
469 KeymatchResult { bindings, pending }
470 }
471
472 pub fn has_pending_keystrokes(&self) -> bool {
473 self.keystroke_matchers
474 .iter()
475 .any(|(_, matcher)| matcher.has_pending_keystrokes())
476 }
477
478 pub fn dispatch_path(&self, target: DispatchNodeId) -> SmallVec<[DispatchNodeId; 32]> {
479 let mut dispatch_path: SmallVec<[DispatchNodeId; 32]> = SmallVec::new();
480 let mut current_node_id = Some(target);
481 while let Some(node_id) = current_node_id {
482 dispatch_path.push(node_id);
483 current_node_id = self.nodes[node_id.0].parent;
484 }
485 dispatch_path.reverse(); // Reverse the path so it goes from the root to the focused node.
486 dispatch_path
487 }
488
489 pub fn focus_path(&self, focus_id: FocusId) -> SmallVec<[FocusId; 8]> {
490 let mut focus_path: SmallVec<[FocusId; 8]> = SmallVec::new();
491 let mut current_node_id = self.focusable_node_ids.get(&focus_id).copied();
492 while let Some(node_id) = current_node_id {
493 let node = self.node(node_id);
494 if let Some(focus_id) = node.focus_id {
495 focus_path.push(focus_id);
496 }
497 current_node_id = node.parent;
498 }
499 focus_path.reverse(); // Reverse the path so it goes from the root to the focused node.
500 focus_path
501 }
502
503 pub fn view_path(&self, view_id: EntityId) -> SmallVec<[EntityId; 8]> {
504 let mut view_path: SmallVec<[EntityId; 8]> = SmallVec::new();
505 let mut current_node_id = self.view_node_ids.get(&view_id).copied();
506 while let Some(node_id) = current_node_id {
507 let node = self.node(node_id);
508 if let Some(view_id) = node.view_id {
509 view_path.push(view_id);
510 }
511 current_node_id = node.parent;
512 }
513 view_path.reverse(); // Reverse the path so it goes from the root to the view node.
514 view_path
515 }
516
517 pub fn node(&self, node_id: DispatchNodeId) -> &DispatchNode {
518 &self.nodes[node_id.0]
519 }
520
521 fn active_node(&mut self) -> &mut DispatchNode {
522 let active_node_id = self.active_node_id().unwrap();
523 &mut self.nodes[active_node_id.0]
524 }
525
526 pub fn focusable_node_id(&self, target: FocusId) -> Option<DispatchNodeId> {
527 self.focusable_node_ids.get(&target).copied()
528 }
529
530 pub fn root_node_id(&self) -> DispatchNodeId {
531 debug_assert!(!self.nodes.is_empty());
532 DispatchNodeId(0)
533 }
534
535 pub fn active_node_id(&self) -> Option<DispatchNodeId> {
536 self.node_stack.last().copied()
537 }
538}
539
540#[cfg(test)]
541mod tests {
542 use std::{cell::RefCell, rc::Rc};
543
544 use crate::{Action, ActionRegistry, DispatchTree, KeyBinding, KeyContext, Keymap};
545
546 #[derive(PartialEq, Eq)]
547 struct TestAction;
548
549 impl Action for TestAction {
550 fn name(&self) -> &'static str {
551 "test::TestAction"
552 }
553
554 fn debug_name() -> &'static str
555 where
556 Self: ::std::marker::Sized,
557 {
558 "test::TestAction"
559 }
560
561 fn partial_eq(&self, action: &dyn Action) -> bool {
562 action
563 .as_any()
564 .downcast_ref::<Self>()
565 .map_or(false, |a| self == a)
566 }
567
568 fn boxed_clone(&self) -> std::boxed::Box<dyn Action> {
569 Box::new(TestAction)
570 }
571
572 fn as_any(&self) -> &dyn ::std::any::Any {
573 self
574 }
575
576 fn build(_value: serde_json::Value) -> anyhow::Result<Box<dyn Action>>
577 where
578 Self: Sized,
579 {
580 Ok(Box::new(TestAction))
581 }
582 }
583
584 #[test]
585 fn test_keybinding_for_action_bounds() {
586 let keymap = Keymap::new(vec![KeyBinding::new(
587 "cmd-n",
588 TestAction,
589 Some("ProjectPanel"),
590 )]);
591
592 let mut registry = ActionRegistry::default();
593
594 registry.load_action::<TestAction>();
595
596 let keymap = Rc::new(RefCell::new(keymap));
597
598 let tree = DispatchTree::new(keymap, Rc::new(registry));
599
600 let contexts = vec![
601 KeyContext::parse("Workspace").unwrap(),
602 KeyContext::parse("ProjectPanel").unwrap(),
603 ];
604
605 let keybinding = tree.bindings_for_action(&TestAction, &contexts);
606
607 assert!(keybinding[0].action.partial_eq(&TestAction))
608 }
609}