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