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