1use crate::{
2 build_action_from_type, Action, DispatchPhase, FocusId, KeyContext, KeyMatch, Keymap,
3 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 dispatch_key(
143 &mut self,
144 keystroke: &Keystroke,
145 context: &[KeyContext],
146 ) -> Option<Box<dyn Action>> {
147 if !self.keystroke_matchers.contains_key(context) {
148 let keystroke_contexts = context.iter().cloned().collect();
149 self.keystroke_matchers.insert(
150 keystroke_contexts,
151 KeystrokeMatcher::new(self.keymap.clone()),
152 );
153 }
154
155 let keystroke_matcher = self.keystroke_matchers.get_mut(context).unwrap();
156 if let KeyMatch::Some(action) = keystroke_matcher.match_keystroke(keystroke, context) {
157 // Clear all pending keystrokes when an action has been found.
158 for keystroke_matcher in self.keystroke_matchers.values_mut() {
159 keystroke_matcher.clear_pending();
160 }
161
162 Some(action)
163 } else {
164 None
165 }
166 }
167
168 pub fn dispatch_path(&self, target: DispatchNodeId) -> SmallVec<[DispatchNodeId; 32]> {
169 let mut dispatch_path: SmallVec<[DispatchNodeId; 32]> = SmallVec::new();
170 let mut current_node_id = Some(target);
171 while let Some(node_id) = current_node_id {
172 dispatch_path.push(node_id);
173 current_node_id = self.nodes[node_id.0].parent;
174 }
175 dispatch_path.reverse(); // Reverse the path so it goes from the root to the focused node.
176 dispatch_path
177 }
178
179 pub fn node(&self, node_id: DispatchNodeId) -> &DispatchNode {
180 &self.nodes[node_id.0]
181 }
182
183 fn active_node(&mut self) -> &mut DispatchNode {
184 let active_node_id = self.active_node_id();
185 &mut self.nodes[active_node_id.0]
186 }
187
188 pub fn focusable_node_id(&self, target: FocusId) -> Option<DispatchNodeId> {
189 self.focusable_node_ids.get(&target).copied()
190 }
191
192 fn active_node_id(&self) -> DispatchNodeId {
193 *self.node_stack.last().unwrap()
194 }
195}