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