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