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
 38pub(crate) struct DispatchActionListener {
 39    pub(crate) action_type: TypeId,
 40    pub(crate) listener: ArenaRef<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>,
 41}
 42
 43impl DispatchTree {
 44    pub fn new(keymap: Arc<Mutex<Keymap>>, action_registry: Rc<ActionRegistry>) -> 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            action_registry,
 53        }
 54    }
 55
 56    pub fn clear(&mut self) {
 57        self.node_stack.clear();
 58        self.nodes.clear();
 59        self.context_stack.clear();
 60        self.focusable_node_ids.clear();
 61        self.keystroke_matchers.clear();
 62    }
 63
 64    pub fn push_node(&mut self, context: Option<KeyContext>) {
 65        let parent = self.node_stack.last().copied();
 66        let node_id = DispatchNodeId(self.nodes.len());
 67        self.nodes.push(DispatchNode {
 68            parent,
 69            ..Default::default()
 70        });
 71        self.node_stack.push(node_id);
 72        if let Some(context) = context {
 73            self.active_node().context = Some(context.clone());
 74            self.context_stack.push(context);
 75        }
 76    }
 77
 78    pub fn pop_node(&mut self) {
 79        let node_id = self.node_stack.pop().unwrap();
 80        if self.nodes[node_id.0].context.is_some() {
 81            self.context_stack.pop();
 82        }
 83    }
 84
 85    pub fn clear_pending_keystrokes(&mut self) {
 86        self.keystroke_matchers.clear();
 87    }
 88
 89    /// Preserve keystroke matchers from previous frames to support multi-stroke
 90    /// bindings across multiple frames.
 91    pub fn preserve_pending_keystrokes(&mut self, old_tree: &mut Self, focus_id: Option<FocusId>) {
 92        if let Some(node_id) = focus_id.and_then(|focus_id| self.focusable_node_id(focus_id)) {
 93            let dispatch_path = self.dispatch_path(node_id);
 94
 95            self.context_stack.clear();
 96            for node_id in dispatch_path {
 97                let node = self.node(node_id);
 98                if let Some(context) = node.context.clone() {
 99                    self.context_stack.push(context);
100                }
101
102                if let Some((context_stack, matcher)) = old_tree
103                    .keystroke_matchers
104                    .remove_entry(self.context_stack.as_slice())
105                {
106                    dbg!("preserve matcher", matcher.has_pending_keystrokes());
107
108                    self.keystroke_matchers.insert(context_stack, matcher);
109                }
110            }
111        }
112    }
113
114    pub fn on_key_event(&mut self, listener: KeyListener) {
115        self.active_node().key_listeners.push(listener);
116    }
117
118    pub fn on_action(
119        &mut self,
120        action_type: TypeId,
121        listener: ArenaRef<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>,
122    ) {
123        self.active_node()
124            .action_listeners
125            .push(DispatchActionListener {
126                action_type,
127                listener,
128            });
129    }
130
131    pub fn make_focusable(&mut self, focus_id: FocusId) {
132        let node_id = self.active_node_id();
133        self.active_node().focus_id = Some(focus_id);
134        self.focusable_node_ids.insert(focus_id, node_id);
135    }
136
137    pub fn focus_contains(&self, parent: FocusId, child: FocusId) -> bool {
138        if parent == child {
139            return true;
140        }
141
142        if let Some(parent_node_id) = self.focusable_node_ids.get(&parent) {
143            let mut current_node_id = self.focusable_node_ids.get(&child).copied();
144            while let Some(node_id) = current_node_id {
145                if node_id == *parent_node_id {
146                    return true;
147                }
148                current_node_id = self.nodes[node_id.0].parent;
149            }
150        }
151        false
152    }
153
154    pub fn available_actions(&self, target: DispatchNodeId) -> Vec<Box<dyn Action>> {
155        let mut actions = Vec::<Box<dyn Action>>::new();
156        for node_id in self.dispatch_path(target) {
157            let node = &self.nodes[node_id.0];
158            for DispatchActionListener { action_type, .. } in &node.action_listeners {
159                if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id())
160                {
161                    // Intentionally silence these errors without logging.
162                    // If an action cannot be built by default, it's not available.
163                    let action = self.action_registry.build_action_type(action_type).ok();
164                    if let Some(action) = action {
165                        actions.insert(ix, action);
166                    }
167                }
168            }
169        }
170        actions
171    }
172
173    pub fn is_action_available(&self, action: &dyn Action, target: DispatchNodeId) -> bool {
174        for node_id in self.dispatch_path(target) {
175            let node = &self.nodes[node_id.0];
176            if node
177                .action_listeners
178                .iter()
179                .any(|listener| listener.action_type == action.as_any().type_id())
180            {
181                return true;
182            }
183        }
184        false
185    }
186
187    pub fn bindings_for_action(
188        &self,
189        action: &dyn Action,
190        context_stack: &Vec<KeyContext>,
191    ) -> Vec<KeyBinding> {
192        self.keymap
193            .lock()
194            .bindings_for_action(action.type_id())
195            .filter(|candidate| {
196                if !candidate.action.partial_eq(action) {
197                    return false;
198                }
199                for i in 1..context_stack.len() {
200                    if candidate.matches_context(&context_stack[0..=i]) {
201                        return true;
202                    }
203                }
204                return false;
205            })
206            .cloned()
207            .collect()
208    }
209
210    pub fn dispatch_key(
211        &mut self,
212        keystroke: &Keystroke,
213        context: &[KeyContext],
214    ) -> Vec<Box<dyn Action>> {
215        if !self.keystroke_matchers.contains_key(context) {
216            let keystroke_contexts = context.iter().cloned().collect();
217            self.keystroke_matchers.insert(
218                keystroke_contexts,
219                KeystrokeMatcher::new(self.keymap.clone()),
220            );
221        }
222
223        let keystroke_matcher = self.keystroke_matchers.get_mut(context).unwrap();
224        if let KeyMatch::Some(actions) = keystroke_matcher.match_keystroke(keystroke, context) {
225            // Clear all pending keystrokes when an action has been found.
226            for keystroke_matcher in self.keystroke_matchers.values_mut() {
227                keystroke_matcher.clear_pending();
228            }
229
230            actions
231        } else {
232            vec![]
233        }
234    }
235
236    pub fn has_pending_keystrokes(&self) -> bool {
237        self.keystroke_matchers
238            .iter()
239            .any(|(_, matcher)| matcher.has_pending_keystrokes())
240    }
241
242    pub fn dispatch_path(&self, target: DispatchNodeId) -> SmallVec<[DispatchNodeId; 32]> {
243        let mut dispatch_path: SmallVec<[DispatchNodeId; 32]> = SmallVec::new();
244        let mut current_node_id = Some(target);
245        while let Some(node_id) = current_node_id {
246            dispatch_path.push(node_id);
247            current_node_id = self.nodes[node_id.0].parent;
248        }
249        dispatch_path.reverse(); // Reverse the path so it goes from the root to the focused node.
250        dispatch_path
251    }
252
253    pub fn focus_path(&self, focus_id: FocusId) -> SmallVec<[FocusId; 8]> {
254        let mut focus_path: SmallVec<[FocusId; 8]> = SmallVec::new();
255        let mut current_node_id = self.focusable_node_ids.get(&focus_id).copied();
256        while let Some(node_id) = current_node_id {
257            let node = self.node(node_id);
258            if let Some(focus_id) = node.focus_id {
259                focus_path.push(focus_id);
260            }
261            current_node_id = node.parent;
262        }
263        focus_path.reverse(); // Reverse the path so it goes from the root to the focused node.
264        focus_path
265    }
266
267    pub fn node(&self, node_id: DispatchNodeId) -> &DispatchNode {
268        &self.nodes[node_id.0]
269    }
270
271    pub fn node_mut(&mut self, node_id: DispatchNodeId) -> &mut DispatchNode {
272        &mut self.nodes[node_id.0]
273    }
274
275    fn active_node(&mut self) -> &mut DispatchNode {
276        let active_node_id = self.active_node_id();
277        &mut self.nodes[active_node_id.0]
278    }
279
280    pub fn focusable_node_id(&self, target: FocusId) -> Option<DispatchNodeId> {
281        self.focusable_node_ids.get(&target).copied()
282    }
283
284    pub fn root_node_id(&self) -> DispatchNodeId {
285        debug_assert!(!self.nodes.is_empty());
286        DispatchNodeId(0)
287    }
288
289    fn active_node_id(&self) -> DispatchNodeId {
290        *self.node_stack.last().unwrap()
291    }
292}