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, old_dispatcher: &mut Self) {
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 if let Some((context_stack, matcher)) = old_dispatcher
75 .keystroke_matchers
76 .remove_entry(self.context_stack.as_slice())
77 {
78 self.keystroke_matchers.insert(context_stack, matcher);
79 }
80 }
81 }
82
83 pub fn pop_node(&mut self) {
84 let node_id = self.node_stack.pop().unwrap();
85 if !self.nodes[node_id.0].context.is_empty() {
86 self.context_stack.pop();
87 }
88 }
89
90 pub fn on_key_event(&mut self, listener: KeyListener) {
91 self.active_node().key_listeners.push(listener);
92 }
93
94 pub fn on_action(
95 &mut self,
96 action_type: TypeId,
97 listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>,
98 ) {
99 self.active_node()
100 .action_listeners
101 .push(DispatchActionListener {
102 action_type,
103 listener,
104 });
105 }
106
107 pub fn make_focusable(&mut self, focus_id: FocusId) {
108 self.focusable_node_ids
109 .insert(focus_id, self.active_node_id());
110 }
111
112 pub fn focus_contains(&self, parent: FocusId, child: FocusId) -> bool {
113 if parent == child {
114 return true;
115 }
116
117 if let Some(parent_node_id) = self.focusable_node_ids.get(&parent) {
118 let mut current_node_id = self.focusable_node_ids.get(&child).copied();
119 while let Some(node_id) = current_node_id {
120 if node_id == *parent_node_id {
121 return true;
122 }
123 current_node_id = self.nodes[node_id.0].parent;
124 }
125 }
126 false
127 }
128
129 pub fn available_actions(&self, target: FocusId) -> Vec<Box<dyn Action>> {
130 let mut actions = Vec::new();
131 if let Some(node) = self.focusable_node_ids.get(&target) {
132 for node_id in self.dispatch_path(*node) {
133 let node = &self.nodes[node_id.0];
134 for DispatchActionListener { action_type, .. } in &node.action_listeners {
135 actions.extend(build_action_from_type(action_type).log_err());
136 }
137 }
138 }
139 actions
140 }
141
142 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
143 self.keymap
144 .lock()
145 .bindings_for_action(action.type_id())
146 .filter(|candidate| candidate.action.partial_eq(action))
147 .cloned()
148 .collect()
149 }
150
151 pub fn dispatch_key(
152 &mut self,
153 keystroke: &Keystroke,
154 context: &[KeyContext],
155 ) -> Option<Box<dyn Action>> {
156 if !self.keystroke_matchers.contains_key(context) {
157 let keystroke_contexts = context.iter().cloned().collect();
158 self.keystroke_matchers.insert(
159 keystroke_contexts,
160 KeystrokeMatcher::new(self.keymap.clone()),
161 );
162 }
163
164 let keystroke_matcher = self.keystroke_matchers.get_mut(context).unwrap();
165 if let KeyMatch::Some(action) = keystroke_matcher.match_keystroke(keystroke, context) {
166 // Clear all pending keystrokes when an action has been found.
167 for keystroke_matcher in self.keystroke_matchers.values_mut() {
168 keystroke_matcher.clear_pending();
169 }
170
171 Some(action)
172 } else {
173 None
174 }
175 }
176
177 pub fn dispatch_path(&self, target: DispatchNodeId) -> SmallVec<[DispatchNodeId; 32]> {
178 let mut dispatch_path: SmallVec<[DispatchNodeId; 32]> = SmallVec::new();
179 let mut current_node_id = Some(target);
180 while let Some(node_id) = current_node_id {
181 dispatch_path.push(node_id);
182 current_node_id = self.nodes[node_id.0].parent;
183 }
184 dispatch_path.reverse(); // Reverse the path so it goes from the root to the focused node.
185 dispatch_path
186 }
187
188 pub fn node(&self, node_id: DispatchNodeId) -> &DispatchNode {
189 &self.nodes[node_id.0]
190 }
191
192 fn active_node(&mut self) -> &mut DispatchNode {
193 let active_node_id = self.active_node_id();
194 &mut self.nodes[active_node_id.0]
195 }
196
197 pub fn focusable_node_id(&self, target: FocusId) -> Option<DispatchNodeId> {
198 self.focusable_node_ids.get(&target).copied()
199 }
200
201 fn active_node_id(&self) -> DispatchNodeId {
202 *self.node_stack.last().unwrap()
203 }
204}