key_dispatch.rs

  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        self.keymap
192            .lock()
193            .bindings_for_action(action.type_id())
194            .filter(|candidate| {
195                if !candidate.action.partial_eq(action) {
196                    return false;
197                }
198                for i in 1..context_stack.len() {
199                    if candidate.matches_context(&context_stack[0..=i]) {
200                        return true;
201                    }
202                }
203                return false;
204            })
205            .cloned()
206            .collect()
207    }
208
209    pub fn dispatch_key(
210        &mut self,
211        keystroke: &Keystroke,
212        context: &[KeyContext],
213    ) -> Vec<Box<dyn Action>> {
214        if !self.keystroke_matchers.contains_key(context) {
215            let keystroke_contexts = context.iter().cloned().collect();
216            self.keystroke_matchers.insert(
217                keystroke_contexts,
218                KeystrokeMatcher::new(self.keymap.clone()),
219            );
220        }
221
222        let keystroke_matcher = self.keystroke_matchers.get_mut(context).unwrap();
223        if let KeyMatch::Some(actions) = keystroke_matcher.match_keystroke(keystroke, context) {
224            // Clear all pending keystrokes when an action has been found.
225            for keystroke_matcher in self.keystroke_matchers.values_mut() {
226                keystroke_matcher.clear_pending();
227            }
228
229            actions
230        } else {
231            vec![]
232        }
233    }
234
235    pub fn has_pending_keystrokes(&self) -> bool {
236        self.keystroke_matchers
237            .iter()
238            .any(|(_, matcher)| matcher.has_pending_keystrokes())
239    }
240
241    pub fn dispatch_path(&self, target: DispatchNodeId) -> SmallVec<[DispatchNodeId; 32]> {
242        let mut dispatch_path: SmallVec<[DispatchNodeId; 32]> = SmallVec::new();
243        let mut current_node_id = Some(target);
244        while let Some(node_id) = current_node_id {
245            dispatch_path.push(node_id);
246            current_node_id = self.nodes[node_id.0].parent;
247        }
248        dispatch_path.reverse(); // Reverse the path so it goes from the root to the focused node.
249        dispatch_path
250    }
251
252    pub fn focus_path(&self, focus_id: FocusId) -> SmallVec<[FocusId; 8]> {
253        let mut focus_path: SmallVec<[FocusId; 8]> = SmallVec::new();
254        let mut current_node_id = self.focusable_node_ids.get(&focus_id).copied();
255        while let Some(node_id) = current_node_id {
256            let node = self.node(node_id);
257            if let Some(focus_id) = node.focus_id {
258                focus_path.push(focus_id);
259            }
260            current_node_id = node.parent;
261        }
262        focus_path.reverse(); // Reverse the path so it goes from the root to the focused node.
263        focus_path
264    }
265
266    pub fn node(&self, node_id: DispatchNodeId) -> &DispatchNode {
267        &self.nodes[node_id.0]
268    }
269
270    fn active_node(&mut self) -> &mut DispatchNode {
271        let active_node_id = self.active_node_id();
272        &mut self.nodes[active_node_id.0]
273    }
274
275    pub fn focusable_node_id(&self, target: FocusId) -> Option<DispatchNodeId> {
276        self.focusable_node_ids.get(&target).copied()
277    }
278
279    pub fn root_node_id(&self) -> DispatchNodeId {
280        debug_assert!(!self.nodes.is_empty());
281        DispatchNodeId(0)
282    }
283
284    fn active_node_id(&self) -> DispatchNodeId {
285        *self.node_stack.last().unwrap()
286    }
287}