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