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