1use crate::{
2 Action, ActionRegistry, DispatchPhase, EntityId, FocusId, KeyBinding, KeyContext, KeyMatch,
3 Keymap, Keystroke, KeystrokeMatcher, WindowContext,
4};
5use collections::FxHashMap;
6use parking_lot::Mutex;
7use smallvec::{smallvec, SmallVec};
8use std::{
9 any::{Any, TypeId},
10 mem,
11 rc::Rc,
12 sync::Arc,
13};
14
15#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
16pub struct DispatchNodeId(usize);
17
18pub(crate) struct DispatchTree {
19 node_stack: Vec<DispatchNodeId>,
20 pub(crate) context_stack: Vec<KeyContext>,
21 nodes: Vec<DispatchNode>,
22 focusable_node_ids: FxHashMap<FocusId, DispatchNodeId>,
23 view_node_ids: FxHashMap<EntityId, DispatchNodeId>,
24 keystroke_matchers: FxHashMap<SmallVec<[KeyContext; 4]>, KeystrokeMatcher>,
25 keymap: Arc<Mutex<Keymap>>,
26 action_registry: Rc<ActionRegistry>,
27}
28
29#[derive(Default)]
30pub(crate) struct DispatchNode {
31 pub key_listeners: Vec<KeyListener>,
32 pub action_listeners: Vec<DispatchActionListener>,
33 pub context: Option<KeyContext>,
34 focus_id: Option<FocusId>,
35 view_id: Option<EntityId>,
36 parent: Option<DispatchNodeId>,
37}
38
39type KeyListener = Rc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>;
40
41#[derive(Clone)]
42pub(crate) struct DispatchActionListener {
43 pub(crate) action_type: TypeId,
44 pub(crate) listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>,
45}
46
47impl DispatchTree {
48 pub fn new(keymap: Arc<Mutex<Keymap>>, action_registry: Rc<ActionRegistry>) -> Self {
49 Self {
50 node_stack: Vec::new(),
51 context_stack: Vec::new(),
52 nodes: Vec::new(),
53 focusable_node_ids: FxHashMap::default(),
54 view_node_ids: FxHashMap::default(),
55 keystroke_matchers: FxHashMap::default(),
56 keymap,
57 action_registry,
58 }
59 }
60
61 pub fn clear(&mut self) {
62 self.node_stack.clear();
63 self.context_stack.clear();
64 self.nodes.clear();
65 self.focusable_node_ids.clear();
66 self.view_node_ids.clear();
67 self.keystroke_matchers.clear();
68 }
69
70 pub fn push_node(
71 &mut self,
72 context: Option<KeyContext>,
73 focus_id: Option<FocusId>,
74 view_id: Option<EntityId>,
75 ) {
76 let parent = self.node_stack.last().copied();
77 let node_id = DispatchNodeId(self.nodes.len());
78 self.nodes.push(DispatchNode {
79 parent,
80 focus_id,
81 view_id,
82 ..Default::default()
83 });
84 self.node_stack.push(node_id);
85
86 if let Some(context) = context {
87 self.active_node().context = Some(context.clone());
88 self.context_stack.push(context);
89 }
90
91 if let Some(focus_id) = focus_id {
92 self.focusable_node_ids.insert(focus_id, node_id);
93 }
94
95 if let Some(view_id) = view_id {
96 self.view_node_ids.insert(view_id, node_id);
97 }
98 }
99
100 pub fn pop_node(&mut self) {
101 let node = &self.nodes[self.active_node_id().0];
102 if node.context.is_some() {
103 self.context_stack.pop();
104 }
105 self.node_stack.pop();
106 }
107
108 fn move_node(&mut self, source: &mut DispatchNode) {
109 self.push_node(source.context.take(), source.focus_id, source.view_id);
110 let target = self.active_node();
111 target.key_listeners = mem::take(&mut source.key_listeners);
112 target.action_listeners = mem::take(&mut source.action_listeners);
113 }
114
115 pub fn reuse_view(&mut self, view_id: EntityId, source: &mut Self) -> SmallVec<[EntityId; 8]> {
116 let view_source_node_id = source
117 .view_node_ids
118 .get(&view_id)
119 .expect("view should exist in previous dispatch tree");
120 let view_source_node = &mut source.nodes[view_source_node_id.0];
121 self.move_node(view_source_node);
122
123 let mut grafted_view_ids = smallvec![view_id];
124 let mut source_stack = vec![*view_source_node_id];
125 for (source_node_id, source_node) in source
126 .nodes
127 .iter_mut()
128 .enumerate()
129 .skip(view_source_node_id.0 + 1)
130 {
131 let source_node_id = DispatchNodeId(source_node_id);
132 while let Some(source_ancestor) = source_stack.last() {
133 if source_node.parent != Some(*source_ancestor) {
134 source_stack.pop();
135 self.pop_node();
136 } else {
137 break;
138 }
139 }
140
141 if source_stack.is_empty() {
142 break;
143 } else {
144 source_stack.push(source_node_id);
145 self.move_node(source_node);
146 if let Some(view_id) = source_node.view_id {
147 grafted_view_ids.push(view_id);
148 }
149 }
150 }
151
152 while !source_stack.is_empty() {
153 source_stack.pop();
154 self.pop_node();
155 }
156
157 grafted_view_ids
158 }
159
160 pub fn clear_pending_keystrokes(&mut self) {
161 self.keystroke_matchers.clear();
162 }
163
164 /// Preserve keystroke matchers from previous frames to support multi-stroke
165 /// bindings across multiple frames.
166 pub fn preserve_pending_keystrokes(&mut self, old_tree: &mut Self, focus_id: Option<FocusId>) {
167 if let Some(node_id) = focus_id.and_then(|focus_id| self.focusable_node_id(focus_id)) {
168 let dispatch_path = self.dispatch_path(node_id);
169
170 self.context_stack.clear();
171 for node_id in dispatch_path {
172 let node = self.node(node_id);
173 if let Some(context) = node.context.clone() {
174 self.context_stack.push(context);
175 }
176
177 if let Some((context_stack, matcher)) = old_tree
178 .keystroke_matchers
179 .remove_entry(self.context_stack.as_slice())
180 {
181 self.keystroke_matchers.insert(context_stack, matcher);
182 }
183 }
184 }
185 }
186
187 pub fn on_key_event(&mut self, listener: KeyListener) {
188 self.active_node().key_listeners.push(listener);
189 }
190
191 pub fn on_action(
192 &mut self,
193 action_type: TypeId,
194 listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>,
195 ) {
196 self.active_node()
197 .action_listeners
198 .push(DispatchActionListener {
199 action_type,
200 listener,
201 });
202 }
203
204 pub fn focus_contains(&self, parent: FocusId, child: FocusId) -> bool {
205 if parent == child {
206 return true;
207 }
208
209 if let Some(parent_node_id) = self.focusable_node_ids.get(&parent) {
210 let mut current_node_id = self.focusable_node_ids.get(&child).copied();
211 while let Some(node_id) = current_node_id {
212 if node_id == *parent_node_id {
213 return true;
214 }
215 current_node_id = self.nodes[node_id.0].parent;
216 }
217 }
218 false
219 }
220
221 pub fn available_actions(&self, target: DispatchNodeId) -> Vec<Box<dyn Action>> {
222 let mut actions = Vec::<Box<dyn Action>>::new();
223 for node_id in self.dispatch_path(target) {
224 let node = &self.nodes[node_id.0];
225 for DispatchActionListener { action_type, .. } in &node.action_listeners {
226 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id())
227 {
228 // Intentionally silence these errors without logging.
229 // If an action cannot be built by default, it's not available.
230 let action = self.action_registry.build_action_type(action_type).ok();
231 if let Some(action) = action {
232 actions.insert(ix, action);
233 }
234 }
235 }
236 }
237 actions
238 }
239
240 pub fn is_action_available(&self, action: &dyn Action, target: DispatchNodeId) -> bool {
241 for node_id in self.dispatch_path(target) {
242 let node = &self.nodes[node_id.0];
243 if node
244 .action_listeners
245 .iter()
246 .any(|listener| listener.action_type == action.as_any().type_id())
247 {
248 return true;
249 }
250 }
251 false
252 }
253
254 pub fn bindings_for_action(
255 &self,
256 action: &dyn Action,
257 context_stack: &Vec<KeyContext>,
258 ) -> Vec<KeyBinding> {
259 let keymap = self.keymap.lock();
260 keymap
261 .bindings_for_action(action)
262 .filter(|binding| {
263 for i in 0..context_stack.len() {
264 let context = &context_stack[0..=i];
265 if keymap.binding_enabled(binding, context) {
266 return true;
267 }
268 }
269 false
270 })
271 .cloned()
272 .collect()
273 }
274
275 pub fn dispatch_key(
276 &mut self,
277 keystroke: &Keystroke,
278 context: &[KeyContext],
279 ) -> Vec<Box<dyn Action>> {
280 if !self.keystroke_matchers.contains_key(context) {
281 let keystroke_contexts = context.iter().cloned().collect();
282 self.keystroke_matchers.insert(
283 keystroke_contexts,
284 KeystrokeMatcher::new(self.keymap.clone()),
285 );
286 }
287
288 let keystroke_matcher = self.keystroke_matchers.get_mut(context).unwrap();
289 if let KeyMatch::Some(actions) = keystroke_matcher.match_keystroke(keystroke, context) {
290 // Clear all pending keystrokes when an action has been found.
291 for keystroke_matcher in self.keystroke_matchers.values_mut() {
292 keystroke_matcher.clear_pending();
293 }
294
295 actions
296 } else {
297 vec![]
298 }
299 }
300
301 pub fn has_pending_keystrokes(&self) -> bool {
302 self.keystroke_matchers
303 .iter()
304 .any(|(_, matcher)| matcher.has_pending_keystrokes())
305 }
306
307 pub fn dispatch_path(&self, target: DispatchNodeId) -> SmallVec<[DispatchNodeId; 32]> {
308 let mut dispatch_path: SmallVec<[DispatchNodeId; 32]> = SmallVec::new();
309 let mut current_node_id = Some(target);
310 while let Some(node_id) = current_node_id {
311 dispatch_path.push(node_id);
312 current_node_id = self.nodes[node_id.0].parent;
313 }
314 dispatch_path.reverse(); // Reverse the path so it goes from the root to the focused node.
315 dispatch_path
316 }
317
318 pub fn focus_path(&self, focus_id: FocusId) -> SmallVec<[FocusId; 8]> {
319 let mut focus_path: SmallVec<[FocusId; 8]> = SmallVec::new();
320 let mut current_node_id = self.focusable_node_ids.get(&focus_id).copied();
321 while let Some(node_id) = current_node_id {
322 let node = self.node(node_id);
323 if let Some(focus_id) = node.focus_id {
324 focus_path.push(focus_id);
325 }
326 current_node_id = node.parent;
327 }
328 focus_path.reverse(); // Reverse the path so it goes from the root to the focused node.
329 focus_path
330 }
331
332 pub fn view_path(&self, view_id: EntityId) -> SmallVec<[EntityId; 8]> {
333 let mut view_path: SmallVec<[EntityId; 8]> = SmallVec::new();
334 let mut current_node_id = self.view_node_ids.get(&view_id).copied();
335 while let Some(node_id) = current_node_id {
336 let node = self.node(node_id);
337 if let Some(view_id) = node.view_id {
338 view_path.push(view_id);
339 }
340 current_node_id = node.parent;
341 }
342 view_path.reverse(); // Reverse the path so it goes from the root to the view node.
343 view_path
344 }
345
346 pub fn node(&self, node_id: DispatchNodeId) -> &DispatchNode {
347 &self.nodes[node_id.0]
348 }
349
350 fn active_node(&mut self) -> &mut DispatchNode {
351 let active_node_id = self.active_node_id();
352 &mut self.nodes[active_node_id.0]
353 }
354
355 pub fn focusable_node_id(&self, target: FocusId) -> Option<DispatchNodeId> {
356 self.focusable_node_ids.get(&target).copied()
357 }
358
359 pub fn root_node_id(&self) -> DispatchNodeId {
360 debug_assert!(!self.nodes.is_empty());
361 DispatchNodeId(0)
362 }
363
364 fn active_node_id(&self) -> DispatchNodeId {
365 *self.node_stack.last().unwrap()
366 }
367}
368
369#[cfg(test)]
370mod tests {
371 use std::{rc::Rc, sync::Arc};
372
373 use parking_lot::Mutex;
374
375 use crate::{Action, ActionRegistry, DispatchTree, KeyBinding, KeyContext, Keymap};
376
377 #[derive(PartialEq, Eq)]
378 struct TestAction;
379
380 impl Action for TestAction {
381 fn name(&self) -> &'static str {
382 "test::TestAction"
383 }
384
385 fn debug_name() -> &'static str
386 where
387 Self: ::std::marker::Sized,
388 {
389 "test::TestAction"
390 }
391
392 fn partial_eq(&self, action: &dyn Action) -> bool {
393 action
394 .as_any()
395 .downcast_ref::<Self>()
396 .map_or(false, |a| self == a)
397 }
398
399 fn boxed_clone(&self) -> std::boxed::Box<dyn Action> {
400 Box::new(TestAction)
401 }
402
403 fn as_any(&self) -> &dyn ::std::any::Any {
404 self
405 }
406
407 fn build(_value: serde_json::Value) -> anyhow::Result<Box<dyn Action>>
408 where
409 Self: Sized,
410 {
411 Ok(Box::new(TestAction))
412 }
413 }
414
415 #[test]
416 fn test_keybinding_for_action_bounds() {
417 let keymap = Keymap::new(vec![KeyBinding::new(
418 "cmd-n",
419 TestAction,
420 Some("ProjectPanel"),
421 )]);
422
423 let mut registry = ActionRegistry::default();
424
425 registry.load_action::<TestAction>();
426
427 let keymap = Arc::new(Mutex::new(keymap));
428
429 let tree = DispatchTree::new(keymap, Rc::new(registry));
430
431 let contexts = vec![
432 KeyContext::parse("Workspace").unwrap(),
433 KeyContext::parse("ProjectPanel").unwrap(),
434 ];
435
436 let keybinding = tree.bindings_for_action(&TestAction, &contexts);
437
438 assert!(keybinding[0].action.partial_eq(&TestAction))
439 }
440}