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