1use crate::{
2 build_action_from_type, Action, DispatchPhase, FocusId, KeyBinding, KeyContext, KeyMatch,
3 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};
13use util::ResultExt;
14
15#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
16pub struct DispatchNodeId(usize);
17
18pub(crate) struct DispatchTree {
19 node_stack: Vec<DispatchNodeId>,
20 context_stack: Vec<KeyContext>,
21 nodes: Vec<DispatchNode>,
22 focusable_node_ids: HashMap<FocusId, DispatchNodeId>,
23 keystroke_matchers: HashMap<SmallVec<[KeyContext; 4]>, KeystrokeMatcher>,
24 keymap: Arc<Mutex<Keymap>>,
25}
26
27#[derive(Default)]
28pub(crate) struct DispatchNode {
29 pub key_listeners: SmallVec<[KeyListener; 2]>,
30 pub action_listeners: SmallVec<[DispatchActionListener; 16]>,
31 pub context: KeyContext,
32 parent: Option<DispatchNodeId>,
33}
34
35type KeyListener = Rc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>;
36
37#[derive(Clone)]
38pub(crate) struct DispatchActionListener {
39 pub(crate) action_type: TypeId,
40 pub(crate) listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>,
41}
42
43impl DispatchTree {
44 pub fn new(keymap: Arc<Mutex<Keymap>>) -> Self {
45 Self {
46 node_stack: Vec::new(),
47 context_stack: Vec::new(),
48 nodes: Vec::new(),
49 focusable_node_ids: HashMap::default(),
50 keystroke_matchers: HashMap::default(),
51 keymap,
52 }
53 }
54
55 pub fn clear(&mut self) {
56 self.node_stack.clear();
57 self.nodes.clear();
58 self.context_stack.clear();
59 self.focusable_node_ids.clear();
60 self.keystroke_matchers.clear();
61 }
62
63 pub fn push_node(&mut self, context: KeyContext) {
64 let parent = self.node_stack.last().copied();
65 let node_id = DispatchNodeId(self.nodes.len());
66 self.nodes.push(DispatchNode {
67 parent,
68 ..Default::default()
69 });
70 self.node_stack.push(node_id);
71 if !context.is_empty() {
72 self.active_node().context = context.clone();
73 self.context_stack.push(context);
74 }
75 }
76
77 pub fn pop_node(&mut self) {
78 let node_id = self.node_stack.pop().unwrap();
79 if !self.nodes[node_id.0].context.is_empty() {
80 self.context_stack.pop();
81 }
82 }
83
84 pub fn clear_keystroke_matchers(&mut self) {
85 self.keystroke_matchers.clear();
86 }
87
88 /// Preserve keystroke matchers from previous frames to support multi-stroke
89 /// bindings across multiple frames.
90 pub fn preserve_keystroke_matchers(&mut self, old_tree: &mut Self, focus_id: Option<FocusId>) {
91 if let Some(node_id) = focus_id.and_then(|focus_id| self.focusable_node_id(focus_id)) {
92 let dispatch_path = self.dispatch_path(node_id);
93
94 self.context_stack.clear();
95 for node_id in dispatch_path {
96 let node = self.node(node_id);
97 if !node.context.is_empty() {
98 self.context_stack.push(node.context.clone());
99 }
100
101 if let Some((context_stack, matcher)) = old_tree
102 .keystroke_matchers
103 .remove_entry(self.context_stack.as_slice())
104 {
105 self.keystroke_matchers.insert(context_stack, matcher);
106 }
107 }
108 }
109 }
110
111 pub fn on_key_event(&mut self, listener: KeyListener) {
112 self.active_node().key_listeners.push(listener);
113 }
114
115 pub fn on_action(
116 &mut self,
117 action_type: TypeId,
118 listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>,
119 ) {
120 self.active_node()
121 .action_listeners
122 .push(DispatchActionListener {
123 action_type,
124 listener,
125 });
126 }
127
128 pub fn make_focusable(&mut self, focus_id: FocusId) {
129 self.focusable_node_ids
130 .insert(focus_id, self.active_node_id());
131 }
132
133 pub fn focus_contains(&self, parent: FocusId, child: FocusId) -> bool {
134 if parent == child {
135 return true;
136 }
137
138 if let Some(parent_node_id) = self.focusable_node_ids.get(&parent) {
139 let mut current_node_id = self.focusable_node_ids.get(&child).copied();
140 while let Some(node_id) = current_node_id {
141 if node_id == *parent_node_id {
142 return true;
143 }
144 current_node_id = self.nodes[node_id.0].parent;
145 }
146 }
147 false
148 }
149
150 pub fn available_actions(&self, target: FocusId) -> Vec<Box<dyn Action>> {
151 let mut actions = Vec::new();
152 if let Some(node) = self.focusable_node_ids.get(&target) {
153 for node_id in self.dispatch_path(*node) {
154 let node = &self.nodes[node_id.0];
155 for DispatchActionListener { action_type, .. } in &node.action_listeners {
156 actions.extend(build_action_from_type(action_type).log_err());
157 }
158 }
159 }
160 actions
161 }
162
163 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
164 self.keymap
165 .lock()
166 .bindings_for_action(action.type_id())
167 .filter(|candidate| candidate.action.partial_eq(action))
168 .cloned()
169 .collect()
170 }
171
172 pub fn dispatch_key(
173 &mut self,
174 keystroke: &Keystroke,
175 context: &[KeyContext],
176 ) -> Option<Box<dyn Action>> {
177 if !self.keystroke_matchers.contains_key(context) {
178 let keystroke_contexts = context.iter().cloned().collect();
179 self.keystroke_matchers.insert(
180 keystroke_contexts,
181 KeystrokeMatcher::new(self.keymap.clone()),
182 );
183 }
184
185 let keystroke_matcher = self.keystroke_matchers.get_mut(context).unwrap();
186 if let KeyMatch::Some(action) = keystroke_matcher.match_keystroke(keystroke, context) {
187 // Clear all pending keystrokes when an action has been found.
188 for keystroke_matcher in self.keystroke_matchers.values_mut() {
189 keystroke_matcher.clear_pending();
190 }
191
192 Some(action)
193 } else {
194 None
195 }
196 }
197
198 pub fn dispatch_path(&self, target: DispatchNodeId) -> SmallVec<[DispatchNodeId; 32]> {
199 let mut dispatch_path: SmallVec<[DispatchNodeId; 32]> = SmallVec::new();
200 let mut current_node_id = Some(target);
201 while let Some(node_id) = current_node_id {
202 dispatch_path.push(node_id);
203 current_node_id = self.nodes[node_id.0].parent;
204 }
205 dispatch_path.reverse(); // Reverse the path so it goes from the root to the focused node.
206 dispatch_path
207 }
208
209 pub fn node(&self, node_id: DispatchNodeId) -> &DispatchNode {
210 &self.nodes[node_id.0]
211 }
212
213 fn active_node(&mut self) -> &mut DispatchNode {
214 let active_node_id = self.active_node_id();
215 &mut self.nodes[active_node_id.0]
216 }
217
218 pub fn focusable_node_id(&self, target: FocusId) -> Option<DispatchNodeId> {
219 self.focusable_node_ids.get(&target).copied()
220 }
221
222 fn active_node_id(&self) -> DispatchNodeId {
223 *self.node_stack.last().unwrap()
224 }
225}