keymap_matcher.rs

  1mod binding;
  2mod keymap;
  3mod keymap_context;
  4mod keystroke;
  5
  6use std::{any::TypeId, fmt::Debug};
  7
  8use collections::{BTreeMap, HashMap};
  9use smallvec::SmallVec;
 10
 11use crate::Action;
 12
 13pub use binding::{Binding, BindingMatchResult};
 14pub use keymap::Keymap;
 15pub use keymap_context::{KeymapContext, KeymapContextPredicate};
 16pub use keystroke::Keystroke;
 17
 18pub struct KeymapMatcher {
 19    pub contexts: Vec<KeymapContext>,
 20    pending_views: HashMap<usize, KeymapContext>,
 21    pending_keystrokes: Vec<Keystroke>,
 22    keymap: Keymap,
 23}
 24
 25impl KeymapMatcher {
 26    pub fn new(keymap: Keymap) -> Self {
 27        Self {
 28            contexts: Vec::new(),
 29            pending_views: Default::default(),
 30            pending_keystrokes: Vec::new(),
 31            keymap,
 32        }
 33    }
 34
 35    pub fn set_keymap(&mut self, keymap: Keymap) {
 36        self.clear_pending();
 37        self.keymap = keymap;
 38    }
 39
 40    pub fn add_bindings<T: IntoIterator<Item = Binding>>(&mut self, bindings: T) {
 41        self.clear_pending();
 42        self.keymap.add_bindings(bindings);
 43    }
 44
 45    pub fn clear_bindings(&mut self) {
 46        self.clear_pending();
 47        self.keymap.clear();
 48    }
 49
 50    pub fn bindings_for_action_type(&self, action_type: TypeId) -> impl Iterator<Item = &Binding> {
 51        self.keymap.bindings_for_action_type(action_type)
 52    }
 53
 54    pub fn clear_pending(&mut self) {
 55        self.pending_keystrokes.clear();
 56        self.pending_views.clear();
 57    }
 58
 59    pub fn has_pending_keystrokes(&self) -> bool {
 60        !self.pending_keystrokes.is_empty()
 61    }
 62
 63    /// Pushes a keystroke onto the matcher.
 64    /// The result of the new keystroke is returned:
 65    ///     MatchResult::None =>
 66    ///         No match is valid for this key given any pending keystrokes.
 67    ///     MatchResult::Pending =>
 68    ///         There exist bindings which are still waiting for more keys.
 69    ///     MatchResult::Complete(matches) =>
 70    ///         1 or more bindings have recieved the necessary key presses.
 71    ///         The order of the matched actions is by order in the keymap file first and
 72    ///         position of the matching view second.
 73    pub fn push_keystroke(
 74        &mut self,
 75        keystroke: Keystroke,
 76        mut dispatch_path: Vec<(usize, KeymapContext)>,
 77    ) -> MatchResult {
 78        let mut any_pending = false;
 79        // Collect matched bindings into an ordered list using the position in the matching binding first,
 80        // and then the order the binding matched in the view tree second.
 81        // The key is the reverse position of the binding in the bindings list so that later bindings
 82        // match before earlier ones in the user's config
 83        let mut matched_bindings: BTreeMap<usize, Vec<(usize, Box<dyn Action>)>> =
 84            Default::default();
 85
 86        let first_keystroke = self.pending_keystrokes.is_empty();
 87        self.pending_keystrokes.push(keystroke.clone());
 88
 89        self.contexts.clear();
 90        self.contexts
 91            .extend(dispatch_path.iter_mut().map(|e| std::mem::take(&mut e.1)));
 92
 93        // Find the bindings which map the pending keystrokes and current context
 94        for (i, (view_id, _)) in dispatch_path.iter().enumerate() {
 95            // Don't require pending view entry if there are no pending keystrokes
 96            if !first_keystroke && !self.pending_views.contains_key(view_id) {
 97                continue;
 98            }
 99
100            // If there is a previous view context, invalidate that view if it
101            // has changed
102            if let Some(previous_view_context) = self.pending_views.remove(view_id) {
103                if previous_view_context != self.contexts[i] {
104                    continue;
105                }
106            }
107
108            for (order, binding) in self.keymap.bindings().iter().rev().enumerate() {
109                match binding.match_keys_and_context(&self.pending_keystrokes, &self.contexts[i..])
110                {
111                    BindingMatchResult::Complete(action) => {
112                        matched_bindings
113                            .entry(order)
114                            .or_default()
115                            .push((*view_id, action));
116                    }
117                    BindingMatchResult::Partial => {
118                        self.pending_views
119                            .insert(*view_id, self.contexts[i].clone());
120                        any_pending = true;
121                    }
122                    _ => {}
123                }
124            }
125        }
126
127        if !any_pending {
128            self.clear_pending();
129        }
130
131        if !matched_bindings.is_empty() {
132            // Collect the sorted matched bindings into the final vec for ease of use
133            // Matched bindings are in order by precedence
134            MatchResult::Matches(matched_bindings.into_values().flatten().collect())
135        } else if any_pending {
136            MatchResult::Pending
137        } else {
138            MatchResult::None
139        }
140    }
141
142    pub fn keystrokes_for_action(
143        &self,
144        action: &dyn Action,
145        contexts: &[KeymapContext],
146    ) -> Option<SmallVec<[Keystroke; 2]>> {
147        self.keymap
148            .bindings()
149            .iter()
150            .rev()
151            .find_map(|binding| binding.keystrokes_for_action(action, contexts))
152    }
153}
154
155impl Default for KeymapMatcher {
156    fn default() -> Self {
157        Self::new(Keymap::default())
158    }
159}
160
161pub enum MatchResult {
162    None,
163    Pending,
164    Matches(Vec<(usize, Box<dyn Action>)>),
165}
166
167impl Debug for MatchResult {
168    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169        match self {
170            MatchResult::None => f.debug_struct("MatchResult::None").finish(),
171            MatchResult::Pending => f.debug_struct("MatchResult::Pending").finish(),
172            MatchResult::Matches(matches) => f
173                .debug_list()
174                .entries(
175                    matches
176                        .iter()
177                        .map(|(view_id, action)| format!("{view_id}, {}", action.name())),
178                )
179                .finish(),
180        }
181    }
182}
183
184impl PartialEq for MatchResult {
185    fn eq(&self, other: &Self) -> bool {
186        match (self, other) {
187            (MatchResult::None, MatchResult::None) => true,
188            (MatchResult::Pending, MatchResult::Pending) => true,
189            (MatchResult::Matches(matches), MatchResult::Matches(other_matches)) => {
190                matches.len() == other_matches.len()
191                    && matches.iter().zip(other_matches.iter()).all(
192                        |((view_id, action), (other_view_id, other_action))| {
193                            view_id == other_view_id && action.eq(other_action.as_ref())
194                        },
195                    )
196            }
197            _ => false,
198        }
199    }
200}
201
202impl Eq for MatchResult {}
203
204impl Clone for MatchResult {
205    fn clone(&self) -> Self {
206        match self {
207            MatchResult::None => MatchResult::None,
208            MatchResult::Pending => MatchResult::Pending,
209            MatchResult::Matches(matches) => MatchResult::Matches(
210                matches
211                    .iter()
212                    .map(|(view_id, action)| (*view_id, Action::boxed_clone(action.as_ref())))
213                    .collect(),
214            ),
215        }
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use anyhow::Result;
222    use serde::Deserialize;
223
224    use crate::{actions, impl_actions, keymap_matcher::KeymapContext};
225
226    use super::*;
227
228    #[test]
229    fn test_push_keystroke() -> Result<()> {
230        actions!(test, [B, AB, C, D, DA]);
231
232        let mut context1 = KeymapContext::default();
233        context1.set.insert("1".into());
234
235        let mut context2 = KeymapContext::default();
236        context2.set.insert("2".into());
237
238        let dispatch_path = vec![(2, context2), (1, context1)];
239
240        let keymap = Keymap::new(vec![
241            Binding::new("a b", AB, Some("1")),
242            Binding::new("b", B, Some("2")),
243            Binding::new("c", C, Some("2")),
244            Binding::new("d", D, Some("1")),
245            Binding::new("d", D, Some("2")),
246            Binding::new("d a", DA, Some("2")),
247        ]);
248
249        let mut matcher = KeymapMatcher::new(keymap);
250
251        // Binding with pending prefix always takes precedence
252        assert_eq!(
253            matcher.push_keystroke(Keystroke::parse("a")?, dispatch_path.clone()),
254            MatchResult::Pending,
255        );
256        // B alone doesn't match because a was pending, so AB is returned instead
257        assert_eq!(
258            matcher.push_keystroke(Keystroke::parse("b")?, dispatch_path.clone()),
259            MatchResult::Matches(vec![(1, Box::new(AB))]),
260        );
261        assert!(!matcher.has_pending_keystrokes());
262
263        // Without an a prefix, B is dispatched like expected
264        assert_eq!(
265            matcher.push_keystroke(Keystroke::parse("b")?, dispatch_path.clone()),
266            MatchResult::Matches(vec![(2, Box::new(B))]),
267        );
268        assert!(!matcher.has_pending_keystrokes());
269
270        // If a is prefixed, C will not be dispatched because there
271        // was a pending binding for it
272        assert_eq!(
273            matcher.push_keystroke(Keystroke::parse("a")?, dispatch_path.clone()),
274            MatchResult::Pending,
275        );
276        assert_eq!(
277            matcher.push_keystroke(Keystroke::parse("c")?, dispatch_path.clone()),
278            MatchResult::None,
279        );
280        assert!(!matcher.has_pending_keystrokes());
281
282        // If a single keystroke matches multiple bindings in the tree
283        // all of them are returned so that we can fallback if the action
284        // handler decides to propagate the action
285        assert_eq!(
286            matcher.push_keystroke(Keystroke::parse("d")?, dispatch_path.clone()),
287            MatchResult::Matches(vec![(2, Box::new(D)), (1, Box::new(D))]),
288        );
289        // If none of the d action handlers consume the binding, a pending
290        // binding may then be used
291        assert_eq!(
292            matcher.push_keystroke(Keystroke::parse("a")?, dispatch_path.clone()),
293            MatchResult::Matches(vec![(2, Box::new(DA))]),
294        );
295        assert!(!matcher.has_pending_keystrokes());
296
297        Ok(())
298    }
299
300    #[test]
301    fn test_keystroke_parsing() -> Result<()> {
302        assert_eq!(
303            Keystroke::parse("ctrl-p")?,
304            Keystroke {
305                key: "p".into(),
306                ctrl: true,
307                alt: false,
308                shift: false,
309                cmd: false,
310                function: false,
311            }
312        );
313
314        assert_eq!(
315            Keystroke::parse("alt-shift-down")?,
316            Keystroke {
317                key: "down".into(),
318                ctrl: false,
319                alt: true,
320                shift: true,
321                cmd: false,
322                function: false,
323            }
324        );
325
326        assert_eq!(
327            Keystroke::parse("shift-cmd--")?,
328            Keystroke {
329                key: "-".into(),
330                ctrl: false,
331                alt: false,
332                shift: true,
333                cmd: true,
334                function: false,
335            }
336        );
337
338        Ok(())
339    }
340
341    #[test]
342    fn test_context_predicate_parsing() -> Result<()> {
343        use KeymapContextPredicate::*;
344
345        assert_eq!(
346            KeymapContextPredicate::parse("a && (b == c || d != e)")?,
347            And(
348                Box::new(Identifier("a".into())),
349                Box::new(Or(
350                    Box::new(Equal("b".into(), "c".into())),
351                    Box::new(NotEqual("d".into(), "e".into())),
352                ))
353            )
354        );
355
356        assert_eq!(
357            KeymapContextPredicate::parse("!a")?,
358            Not(Box::new(Identifier("a".into())),)
359        );
360
361        Ok(())
362    }
363
364    #[test]
365    fn test_context_predicate_eval() {
366        let predicate = KeymapContextPredicate::parse("a && b || c == d").unwrap();
367
368        let mut context = KeymapContext::default();
369        context.set.insert("a".into());
370        assert!(!predicate.eval(&[context]));
371
372        let mut context = KeymapContext::default();
373        context.set.insert("a".into());
374        context.set.insert("b".into());
375        assert!(predicate.eval(&[context]));
376
377        let mut context = KeymapContext::default();
378        context.set.insert("a".into());
379        context.map.insert("c".into(), "x".into());
380        assert!(!predicate.eval(&[context]));
381
382        let mut context = KeymapContext::default();
383        context.set.insert("a".into());
384        context.map.insert("c".into(), "d".into());
385        assert!(predicate.eval(&[context]));
386
387        let predicate = KeymapContextPredicate::parse("!a").unwrap();
388        assert!(predicate.eval(&[KeymapContext::default()]));
389    }
390
391    #[test]
392    fn test_context_child_predicate_eval() {
393        let predicate = KeymapContextPredicate::parse("a && b > c").unwrap();
394        let contexts = [
395            context_set(&["e", "f"]),
396            context_set(&["c", "d"]), // match this context
397            context_set(&["a", "b"]),
398        ];
399
400        assert!(!predicate.eval(&contexts[0..]));
401        assert!(predicate.eval(&contexts[1..]));
402        assert!(!predicate.eval(&contexts[2..]));
403
404        let predicate = KeymapContextPredicate::parse("a && b > c && !d > e").unwrap();
405        let contexts = [
406            context_set(&["f"]),
407            context_set(&["e"]), // only match this context
408            context_set(&["c"]),
409            context_set(&["a", "b"]),
410            context_set(&["e"]),
411            context_set(&["c", "d"]),
412            context_set(&["a", "b"]),
413        ];
414
415        assert!(!predicate.eval(&contexts[0..]));
416        assert!(predicate.eval(&contexts[1..]));
417        assert!(!predicate.eval(&contexts[2..]));
418        assert!(!predicate.eval(&contexts[3..]));
419        assert!(!predicate.eval(&contexts[4..]));
420        assert!(!predicate.eval(&contexts[5..]));
421        assert!(!predicate.eval(&contexts[6..]));
422
423        fn context_set(names: &[&str]) -> KeymapContext {
424            KeymapContext {
425                set: names.iter().copied().map(str::to_string).collect(),
426                ..Default::default()
427            }
428        }
429    }
430
431    #[test]
432    fn test_matcher() -> Result<()> {
433        #[derive(Clone, Deserialize, PartialEq, Eq, Debug)]
434        pub struct A(pub String);
435        impl_actions!(test, [A]);
436        actions!(test, [B, Ab]);
437
438        #[derive(Clone, Debug, Eq, PartialEq)]
439        struct ActionArg {
440            a: &'static str,
441        }
442
443        let keymap = Keymap::new(vec![
444            Binding::new("a", A("x".to_string()), Some("a")),
445            Binding::new("b", B, Some("a")),
446            Binding::new("a b", Ab, Some("a || b")),
447        ]);
448
449        let mut context_a = KeymapContext::default();
450        context_a.set.insert("a".into());
451
452        let mut context_b = KeymapContext::default();
453        context_b.set.insert("b".into());
454
455        let mut matcher = KeymapMatcher::new(keymap);
456
457        // Basic match
458        assert_eq!(
459            matcher.push_keystroke(Keystroke::parse("a")?, vec![(1, context_a.clone())]),
460            MatchResult::Matches(vec![(1, Box::new(A("x".to_string())))])
461        );
462        matcher.clear_pending();
463
464        // Multi-keystroke match
465        assert_eq!(
466            matcher.push_keystroke(Keystroke::parse("a")?, vec![(1, context_b.clone())]),
467            MatchResult::Pending
468        );
469        assert_eq!(
470            matcher.push_keystroke(Keystroke::parse("b")?, vec![(1, context_b.clone())]),
471            MatchResult::Matches(vec![(1, Box::new(Ab))])
472        );
473        matcher.clear_pending();
474
475        // Failed matches don't interfere with matching subsequent keys
476        assert_eq!(
477            matcher.push_keystroke(Keystroke::parse("x")?, vec![(1, context_a.clone())]),
478            MatchResult::None
479        );
480        assert_eq!(
481            matcher.push_keystroke(Keystroke::parse("a")?, vec![(1, context_a.clone())]),
482            MatchResult::Matches(vec![(1, Box::new(A("x".to_string())))])
483        );
484        matcher.clear_pending();
485
486        // Pending keystrokes are cleared when the context changes
487        assert_eq!(
488            matcher.push_keystroke(Keystroke::parse("a")?, vec![(1, context_b.clone())]),
489            MatchResult::Pending
490        );
491        assert_eq!(
492            matcher.push_keystroke(Keystroke::parse("b")?, vec![(1, context_a.clone())]),
493            MatchResult::None
494        );
495        matcher.clear_pending();
496
497        let mut context_c = KeymapContext::default();
498        context_c.set.insert("c".into());
499
500        // Pending keystrokes are maintained per-view
501        assert_eq!(
502            matcher.push_keystroke(
503                Keystroke::parse("a")?,
504                vec![(1, context_b.clone()), (2, context_c.clone())]
505            ),
506            MatchResult::Pending
507        );
508        assert_eq!(
509            matcher.push_keystroke(Keystroke::parse("b")?, vec![(1, context_b.clone())]),
510            MatchResult::Matches(vec![(1, Box::new(Ab))])
511        );
512
513        Ok(())
514    }
515}