1use crate::{
2 Action, ActionRegistry, DispatchPhase, ElementContext, EntityId, FocusId, KeyBinding,
3 KeyContext, Keymap, KeymatchResult, 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(crate) 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 ElementContext)>;
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 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
279 ) -> KeymatchResult {
280 let mut bindings = SmallVec::new();
281 let mut pending = false;
282
283 let mut context_stack: SmallVec<[KeyContext; 4]> = SmallVec::new();
284 for node_id in dispatch_path {
285 let node = self.node(*node_id);
286
287 if let Some(context) = node.context.clone() {
288 context_stack.push(context);
289 }
290 }
291
292 while !context_stack.is_empty() {
293 let keystroke_matcher = self
294 .keystroke_matchers
295 .entry(context_stack.clone())
296 .or_insert_with(|| KeystrokeMatcher::new(self.keymap.clone()));
297
298 let mut result = keystroke_matcher.match_keystroke(keystroke, &context_stack);
299 pending = result.pending || pending;
300 bindings.append(&mut result.bindings);
301 context_stack.pop();
302 }
303
304 KeymatchResult { bindings, pending }
305 }
306
307 pub fn has_pending_keystrokes(&self) -> bool {
308 self.keystroke_matchers
309 .iter()
310 .any(|(_, matcher)| matcher.has_pending_keystrokes())
311 }
312
313 pub fn dispatch_path(&self, target: DispatchNodeId) -> SmallVec<[DispatchNodeId; 32]> {
314 let mut dispatch_path: SmallVec<[DispatchNodeId; 32]> = SmallVec::new();
315 let mut current_node_id = Some(target);
316 while let Some(node_id) = current_node_id {
317 dispatch_path.push(node_id);
318 current_node_id = self.nodes[node_id.0].parent;
319 }
320 dispatch_path.reverse(); // Reverse the path so it goes from the root to the focused node.
321 dispatch_path
322 }
323
324 pub fn focus_path(&self, focus_id: FocusId) -> SmallVec<[FocusId; 8]> {
325 let mut focus_path: SmallVec<[FocusId; 8]> = SmallVec::new();
326 let mut current_node_id = self.focusable_node_ids.get(&focus_id).copied();
327 while let Some(node_id) = current_node_id {
328 let node = self.node(node_id);
329 if let Some(focus_id) = node.focus_id {
330 focus_path.push(focus_id);
331 }
332 current_node_id = node.parent;
333 }
334 focus_path.reverse(); // Reverse the path so it goes from the root to the focused node.
335 focus_path
336 }
337
338 pub fn view_path(&self, view_id: EntityId) -> SmallVec<[EntityId; 8]> {
339 let mut view_path: SmallVec<[EntityId; 8]> = SmallVec::new();
340 let mut current_node_id = self.view_node_ids.get(&view_id).copied();
341 while let Some(node_id) = current_node_id {
342 let node = self.node(node_id);
343 if let Some(view_id) = node.view_id {
344 view_path.push(view_id);
345 }
346 current_node_id = node.parent;
347 }
348 view_path.reverse(); // Reverse the path so it goes from the root to the view node.
349 view_path
350 }
351
352 pub fn node(&self, node_id: DispatchNodeId) -> &DispatchNode {
353 &self.nodes[node_id.0]
354 }
355
356 fn active_node(&mut self) -> &mut DispatchNode {
357 let active_node_id = self.active_node_id();
358 &mut self.nodes[active_node_id.0]
359 }
360
361 pub fn focusable_node_id(&self, target: FocusId) -> Option<DispatchNodeId> {
362 self.focusable_node_ids.get(&target).copied()
363 }
364
365 pub fn root_node_id(&self) -> DispatchNodeId {
366 debug_assert!(!self.nodes.is_empty());
367 DispatchNodeId(0)
368 }
369
370 fn active_node_id(&self) -> DispatchNodeId {
371 *self.node_stack.last().unwrap()
372 }
373}
374
375#[cfg(test)]
376mod tests {
377 use std::{rc::Rc, sync::Arc};
378
379 use parking_lot::Mutex;
380
381 use crate::{Action, ActionRegistry, DispatchTree, KeyBinding, KeyContext, Keymap};
382
383 #[derive(PartialEq, Eq)]
384 struct TestAction;
385
386 impl Action for TestAction {
387 fn name(&self) -> &'static str {
388 "test::TestAction"
389 }
390
391 fn debug_name() -> &'static str
392 where
393 Self: ::std::marker::Sized,
394 {
395 "test::TestAction"
396 }
397
398 fn partial_eq(&self, action: &dyn Action) -> bool {
399 action
400 .as_any()
401 .downcast_ref::<Self>()
402 .map_or(false, |a| self == a)
403 }
404
405 fn boxed_clone(&self) -> std::boxed::Box<dyn Action> {
406 Box::new(TestAction)
407 }
408
409 fn as_any(&self) -> &dyn ::std::any::Any {
410 self
411 }
412
413 fn build(_value: serde_json::Value) -> anyhow::Result<Box<dyn Action>>
414 where
415 Self: Sized,
416 {
417 Ok(Box::new(TestAction))
418 }
419 }
420
421 #[test]
422 fn test_keybinding_for_action_bounds() {
423 let keymap = Keymap::new(vec![KeyBinding::new(
424 "cmd-n",
425 TestAction,
426 Some("ProjectPanel"),
427 )]);
428
429 let mut registry = ActionRegistry::default();
430
431 registry.load_action::<TestAction>();
432
433 let keymap = Arc::new(Mutex::new(keymap));
434
435 let tree = DispatchTree::new(keymap, Rc::new(registry));
436
437 let contexts = vec![
438 KeyContext::parse("Workspace").unwrap(),
439 KeyContext::parse("ProjectPanel").unwrap(),
440 ];
441
442 let keybinding = tree.bindings_for_action(&TestAction, &contexts);
443
444 assert!(keybinding[0].action.partial_eq(&TestAction))
445 }
446}