Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T05:37:00.044Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

keymap.rs

928 lines · 34.8 KB · rust
1mod binding;
2mod context;
3
4pub use binding::*;
5pub use context::*;
6
7use crate::{Action, AsKeystroke, Keystroke, Unbind, is_no_action, is_unbind};
8use collections::{HashSet, TypeIdHashMap};
9use smallvec::SmallVec;
10
11/// An opaque identifier of which version of the keymap is currently active.
12/// The keymap's version is changed whenever bindings are added or removed.
13#[derive(Copy, Clone, Eq, PartialEq, Default)]
14pub struct KeymapVersion(usize);
15
16/// A collection of key bindings for the user's application.
17#[derive(Default)]
18pub struct Keymap {
19    bindings: Vec<KeyBinding>,
20    binding_indices_by_action_id: TypeIdHashMap<SmallVec<[usize; 3]>>,
21    disabled_binding_indices: Vec<usize>,
22    version: KeymapVersion,
23}
24
25/// Index of a binding within a keymap.
26#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
27pub struct BindingIndex(usize);
28
29fn disabled_binding_matches_context(disabled_binding: &KeyBinding, binding: &KeyBinding) -> bool {
30    match (
31        &disabled_binding.context_predicate,
32        &binding.context_predicate,
33    ) {
34        (None, _) => true,
35        (Some(_), None) => false,
36        (Some(disabled_predicate), Some(predicate)) => disabled_predicate.is_superset(predicate),
37    }
38}
39
40fn binding_is_unbound(disabled_binding: &KeyBinding, binding: &KeyBinding) -> bool {
41    disabled_binding.keystrokes == binding.keystrokes
42        && disabled_binding
43            .action()
44            .as_any()
45            .downcast_ref::<Unbind>()
46            .is_some_and(|unbind| unbind.0.as_ref() == binding.action.name())
47}
48
49impl Keymap {
50    /// Create a new keymap with the given bindings.
51    pub fn new(bindings: Vec<KeyBinding>) -> Self {
52        let mut this = Self::default();
53        this.add_bindings(bindings);
54        this
55    }
56
57    /// Get the current version of the keymap.
58    pub fn version(&self) -> KeymapVersion {
59        self.version
60    }
61
62    /// Add more bindings to the keymap.
63    pub fn add_bindings<T: IntoIterator<Item = KeyBinding>>(&mut self, bindings: T) {
64        for binding in bindings {
65            let action_id = binding.action().as_any().type_id();
66            if is_no_action(&*binding.action) || is_unbind(&*binding.action) {
67                self.disabled_binding_indices.push(self.bindings.len());
68            } else {
69                self.binding_indices_by_action_id
70                    .entry(action_id)
71                    .or_default()
72                    .push(self.bindings.len());
73            }
74            self.bindings.push(binding);
75        }
76
77        self.version.0 += 1;
78    }
79
80    /// Reset this keymap to its initial state.
81    pub fn clear(&mut self) {
82        self.bindings.clear();
83        self.binding_indices_by_action_id.clear();
84        self.disabled_binding_indices.clear();
85        self.version.0 += 1;
86    }
87
88    /// Iterate over all bindings, in the order they were added.
89    pub fn bindings(&self) -> impl DoubleEndedIterator<Item = &KeyBinding> + ExactSizeIterator {
90        self.bindings.iter()
91    }
92
93    /// Iterate over all bindings for the given action, in the order they were added. For display,
94    /// the last binding should take precedence.
95    pub fn bindings_for_action<'a>(
96        &'a self,
97        action: &'a dyn Action,
98    ) -> impl 'a + DoubleEndedIterator<Item = &'a KeyBinding> {
99        let action_id = action.type_id();
100        let binding_indices = self
101            .binding_indices_by_action_id
102            .get(&action_id)
103            .map_or(&[] as _, SmallVec::as_slice)
104            .iter();
105
106        binding_indices.filter_map(|ix| {
107            let binding = &self.bindings[*ix];
108            if !binding.action().partial_eq(action) {
109                return None;
110            }
111
112            for disabled_ix in &self.disabled_binding_indices {
113                if disabled_ix > ix {
114                    let disabled_binding = &self.bindings[*disabled_ix];
115                    if disabled_binding.keystrokes != binding.keystrokes {
116                        continue;
117                    }
118
119                    if is_no_action(&*disabled_binding.action) {
120                        if disabled_binding_matches_context(disabled_binding, binding) {
121                            return None;
122                        }
123                    } else if is_unbind(&*disabled_binding.action)
124                        && disabled_binding_matches_context(disabled_binding, binding)
125                        && binding_is_unbound(disabled_binding, binding)
126                    {
127                        return None;
128                    }
129                }
130            }
131
132            Some(binding)
133        })
134    }
135
136    /// Returns all bindings that might match the input without checking context. The bindings
137    /// returned in precedence order (reverse of the order they were added to the keymap).
138    pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
139        self.bindings()
140            .rev()
141            .filter(|binding| {
142                binding
143                    .match_keystrokes(input)
144                    .is_some_and(|pending| !pending)
145            })
146            .cloned()
147            .collect()
148    }
149
150    /// Returns a list of bindings that match the given input, and a boolean indicating whether or
151    /// not more bindings might match if the input was longer. Bindings are returned in precedence
152    /// order (higher precedence first, reverse of the order they were added to the keymap).
153    ///
154    /// Precedence is defined by the depth in the tree (matches on the Editor take precedence over
155    /// matches on the Pane, then the Workspace, etc.). Bindings with no context are treated as the
156    /// same as the deepest context.
157    ///
158    /// In the case of multiple bindings at the same depth, the ones added to the keymap later take
159    /// precedence. User bindings are added after built-in bindings so that they take precedence.
160    ///
161    /// If a binding has been disabled with `"x": null` it will not be returned. Disabled bindings
162    /// are evaluated with the same precedence rules so you can disable a rule in a given context
163    /// only. A disabled binding only suppresses bindings from sources with equal or weaker
164    /// precedence: a base keymap null hides default bindings, but user bindings still apply.
165    pub fn bindings_for_input(
166        &self,
167        input: &[impl AsKeystroke],
168        context_stack: &[KeyContext],
169    ) -> (SmallVec<[KeyBinding; 1]>, bool) {
170        let mut matched_bindings = SmallVec::<[(usize, BindingIndex, &KeyBinding); 1]>::new();
171        let mut pending_bindings = SmallVec::<[(BindingIndex, &KeyBinding); 1]>::new();
172
173        for (ix, binding) in self.bindings().enumerate().rev() {
174            let Some(depth) = self.binding_enabled(binding, context_stack) else {
175                continue;
176            };
177            let Some(pending) = binding.match_keystrokes(input) else {
178                continue;
179            };
180
181            if !pending {
182                matched_bindings.push((depth, BindingIndex(ix), binding));
183            } else {
184                pending_bindings.push((BindingIndex(ix), binding));
185            }
186        }
187
188        matched_bindings.sort_by(|(depth_a, ix_a, _), (depth_b, ix_b, _)| {
189            depth_b.cmp(depth_a).then(ix_b.cmp(ix_a))
190        });
191
192        let mut bindings: SmallVec<[_; 1]> = SmallVec::new();
193        let mut first_binding_index = None;
194        let mut unbound_bindings: Vec<&KeyBinding> = Vec::new();
195        // A `NoAction` binding suppresses out-ranked bindings from sources with
196        // equal or weaker precedence, while bindings from stronger sources (a
197        // smaller meta, e.g. a user binding vs a base keymap null) still apply.
198        // Bindings without a meta are treated as user bindings.
199        let mut no_action_meta: Option<u32> = None;
200
201        for (_, ix, binding) in matched_bindings {
202            let meta = binding.meta.map_or(0, |meta| meta.0);
203            if is_no_action(&*binding.action) {
204                no_action_meta = Some(no_action_meta.map_or(meta, |existing| existing.min(meta)));
205                continue;
206            }
207
208            if no_action_meta.is_some_and(|no_action_meta| meta >= no_action_meta) {
209                continue;
210            }
211
212            if is_unbind(&*binding.action) {
213                unbound_bindings.push(binding);
214                continue;
215            }
216
217            if unbound_bindings
218                .iter()
219                .any(|disabled_binding| binding_is_unbound(disabled_binding, binding))
220            {
221                continue;
222            }
223
224            bindings.push(binding.clone());
225            first_binding_index.get_or_insert(ix);
226        }
227
228        let mut pending = HashSet::default();
229        for (ix, binding) in pending_bindings.into_iter().rev() {
230            if let Some(binding_ix) = first_binding_index
231                && binding_ix > ix
232            {
233                continue;
234            }
235            if is_no_action(&*binding.action) || is_unbind(&*binding.action) {
236                pending.remove(&&binding.keystrokes);
237                continue;
238            }
239            pending.insert(&binding.keystrokes);
240        }
241
242        (bindings, !pending.is_empty())
243    }
244    /// Check if the given binding is enabled, given a certain key context.
245    /// Returns the deepest depth at which the binding matches, or None if it doesn't match.
246    fn binding_enabled(&self, binding: &KeyBinding, contexts: &[KeyContext]) -> Option<usize> {
247        if let Some(predicate) = &binding.context_predicate {
248            predicate.depth_of(contexts)
249        } else {
250            Some(contexts.len())
251        }
252    }
253
254    /// Find the bindings that can follow the current input sequence.
255    pub fn possible_next_bindings_for_input(
256        &self,
257        input: &[Keystroke],
258        context_stack: &[KeyContext],
259    ) -> Vec<KeyBinding> {
260        let mut bindings = self
261            .bindings()
262            .enumerate()
263            .rev()
264            .filter_map(|(ix, binding)| {
265                let depth = self.binding_enabled(binding, context_stack)?;
266                let pending = binding.match_keystrokes(input);
267                match pending {
268                    None => None,
269                    Some(is_pending) => {
270                        if !is_pending
271                            || is_no_action(&*binding.action)
272                            || is_unbind(&*binding.action)
273                        {
274                            return None;
275                        }
276                        Some((depth, BindingIndex(ix), binding))
277                    }
278                }
279            })
280            .collect::<Vec<_>>();
281
282        bindings.sort_by(|(depth_a, ix_a, _), (depth_b, ix_b, _)| {
283            depth_b.cmp(depth_a).then(ix_b.cmp(ix_a))
284        });
285
286        bindings
287            .into_iter()
288            .map(|(_, _, binding)| binding.clone())
289            .collect::<Vec<_>>()
290    }
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296    use crate as gpui;
297    use gpui::{NoAction, Unbind};
298
299    actions!(
300        test_only,
301        [ActionAlpha, ActionBeta, ActionGamma, ActionDelta,]
302    );
303
304    #[test]
305    fn test_keymap() {
306        let bindings = [
307            KeyBinding::new("ctrl-a", ActionAlpha {}, None),
308            KeyBinding::new("ctrl-a", ActionBeta {}, Some("pane")),
309            KeyBinding::new("ctrl-a", ActionGamma {}, Some("editor && mode==full")),
310        ];
311
312        let mut keymap = Keymap::default();
313        keymap.add_bindings(bindings.clone());
314
315        // global bindings are enabled in all contexts
316        assert_eq!(keymap.binding_enabled(&bindings[0], &[]), Some(0));
317        assert_eq!(
318            keymap.binding_enabled(&bindings[0], &[KeyContext::parse("terminal").unwrap()]),
319            Some(1)
320        );
321
322        // contextual bindings are enabled in contexts that match their predicate
323        assert_eq!(
324            keymap.binding_enabled(&bindings[1], &[KeyContext::parse("barf x=y").unwrap()]),
325            None
326        );
327        assert_eq!(
328            keymap.binding_enabled(&bindings[1], &[KeyContext::parse("pane x=y").unwrap()]),
329            Some(1)
330        );
331
332        assert_eq!(
333            keymap.binding_enabled(&bindings[2], &[KeyContext::parse("editor").unwrap()]),
334            None
335        );
336        assert_eq!(
337            keymap.binding_enabled(
338                &bindings[2],
339                &[KeyContext::parse("editor mode=full").unwrap()]
340            ),
341            Some(1)
342        );
343    }
344
345    #[test]
346    fn test_depth_precedence() {
347        let bindings = [
348            KeyBinding::new("ctrl-a", ActionBeta {}, Some("pane")),
349            KeyBinding::new("ctrl-a", ActionGamma {}, Some("editor")),
350        ];
351
352        let mut keymap = Keymap::default();
353        keymap.add_bindings(bindings);
354
355        let (result, pending) = keymap.bindings_for_input(
356            &[Keystroke::parse("ctrl-a").unwrap()],
357            &[
358                KeyContext::parse("pane").unwrap(),
359                KeyContext::parse("editor").unwrap(),
360            ],
361        );
362
363        assert!(!pending);
364        assert_eq!(result.len(), 2);
365        assert!(result[0].action.partial_eq(&ActionGamma {}));
366        assert!(result[1].action.partial_eq(&ActionBeta {}));
367    }
368
369    #[test]
370    fn test_keymap_disabled() {
371        let bindings = [
372            KeyBinding::new("ctrl-a", ActionAlpha {}, Some("editor")),
373            KeyBinding::new("ctrl-b", ActionAlpha {}, Some("editor")),
374            KeyBinding::new("ctrl-a", NoAction {}, Some("editor && mode==full")),
375            KeyBinding::new("ctrl-b", NoAction {}, None),
376        ];
377
378        let mut keymap = Keymap::default();
379        keymap.add_bindings(bindings);
380
381        // binding is only enabled in a specific context
382        assert!(
383            keymap
384                .bindings_for_input(
385                    &[Keystroke::parse("ctrl-a").unwrap()],
386                    &[KeyContext::parse("barf").unwrap()],
387                )
388                .0
389                .is_empty()
390        );
391        assert!(
392            !keymap
393                .bindings_for_input(
394                    &[Keystroke::parse("ctrl-a").unwrap()],
395                    &[KeyContext::parse("editor").unwrap()],
396                )
397                .0
398                .is_empty()
399        );
400
401        // binding is disabled in a more specific context
402        assert!(
403            keymap
404                .bindings_for_input(
405                    &[Keystroke::parse("ctrl-a").unwrap()],
406                    &[KeyContext::parse("editor mode=full").unwrap()],
407                )
408                .0
409                .is_empty()
410        );
411
412        // binding is globally disabled
413        assert!(
414            keymap
415                .bindings_for_input(
416                    &[Keystroke::parse("ctrl-b").unwrap()],
417                    &[KeyContext::parse("barf").unwrap()],
418                )
419                .0
420                .is_empty()
421        );
422    }
423
424    #[test]
425    /// Tests for https://github.com/zed-industries/zed/issues/30259
426    fn test_multiple_keystroke_binding_disabled() {
427        let bindings = [
428            KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
429            KeyBinding::new("space w w", NoAction {}, Some("editor")),
430        ];
431
432        let mut keymap = Keymap::default();
433        keymap.add_bindings(bindings);
434
435        let space = || Keystroke::parse("space").unwrap();
436        let w = || Keystroke::parse("w").unwrap();
437
438        let space_w = [space(), w()];
439        let space_w_w = [space(), w(), w()];
440
441        let workspace_context = || [KeyContext::parse("workspace").unwrap()];
442
443        let editor_workspace_context = || {
444            [
445                KeyContext::parse("workspace").unwrap(),
446                KeyContext::parse("editor").unwrap(),
447            ]
448        };
449
450        // Ensure `space` results in pending input on the workspace, but not editor
451        let space_workspace = keymap.bindings_for_input(&[space()], &workspace_context());
452        assert!(space_workspace.0.is_empty());
453        assert!(space_workspace.1);
454
455        let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
456        assert!(space_editor.0.is_empty());
457        assert!(!space_editor.1);
458
459        // Ensure `space w` results in pending input on the workspace, but not editor
460        let space_w_workspace = keymap.bindings_for_input(&space_w, &workspace_context());
461        assert!(space_w_workspace.0.is_empty());
462        assert!(space_w_workspace.1);
463
464        let space_w_editor = keymap.bindings_for_input(&space_w, &editor_workspace_context());
465        assert!(space_w_editor.0.is_empty());
466        assert!(!space_w_editor.1);
467
468        // Ensure `space w w` results in the binding in the workspace, but not in the editor
469        let space_w_w_workspace = keymap.bindings_for_input(&space_w_w, &workspace_context());
470        assert!(!space_w_w_workspace.0.is_empty());
471        assert!(!space_w_w_workspace.1);
472
473        let space_w_w_editor = keymap.bindings_for_input(&space_w_w, &editor_workspace_context());
474        assert!(space_w_w_editor.0.is_empty());
475        assert!(!space_w_w_editor.1);
476
477        // Now test what happens if we have another binding defined AFTER the NoAction
478        // that should result in pending
479        let bindings = [
480            KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
481            KeyBinding::new("space w w", NoAction {}, Some("editor")),
482            KeyBinding::new("space w x", ActionAlpha {}, Some("editor")),
483        ];
484        let mut keymap = Keymap::default();
485        keymap.add_bindings(bindings);
486
487        let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
488        assert!(space_editor.0.is_empty());
489        assert!(space_editor.1);
490
491        // Now test what happens if we have another binding defined BEFORE the NoAction
492        // that should result in pending
493        let bindings = [
494            KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
495            KeyBinding::new("space w x", ActionAlpha {}, Some("editor")),
496            KeyBinding::new("space w w", NoAction {}, Some("editor")),
497        ];
498        let mut keymap = Keymap::default();
499        keymap.add_bindings(bindings);
500
501        let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
502        assert!(space_editor.0.is_empty());
503        assert!(space_editor.1);
504
505        // Now test what happens if we have another binding defined at a higher context
506        // that should result in pending
507        let bindings = [
508            KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
509            KeyBinding::new("space w x", ActionAlpha {}, Some("workspace")),
510            KeyBinding::new("space w w", NoAction {}, Some("editor")),
511        ];
512        let mut keymap = Keymap::default();
513        keymap.add_bindings(bindings);
514
515        let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
516        assert!(space_editor.0.is_empty());
517        assert!(space_editor.1);
518    }
519
520    #[test]
521    fn test_override_multikey() {
522        let bindings = [
523            KeyBinding::new("ctrl-w left", ActionAlpha {}, Some("editor")),
524            KeyBinding::new("ctrl-w", NoAction {}, Some("editor")),
525        ];
526
527        let mut keymap = Keymap::default();
528        keymap.add_bindings(bindings);
529
530        // Ensure `space` results in pending input on the workspace, but not editor
531        let (result, pending) = keymap.bindings_for_input(
532            &[Keystroke::parse("ctrl-w").unwrap()],
533            &[KeyContext::parse("editor").unwrap()],
534        );
535        assert!(result.is_empty());
536        assert!(pending);
537
538        let bindings = [
539            KeyBinding::new("ctrl-w left", ActionAlpha {}, Some("editor")),
540            KeyBinding::new("ctrl-w", ActionBeta {}, Some("editor")),
541        ];
542
543        let mut keymap = Keymap::default();
544        keymap.add_bindings(bindings);
545
546        // Ensure `space` results in pending input on the workspace, but not editor
547        let (result, pending) = keymap.bindings_for_input(
548            &[Keystroke::parse("ctrl-w").unwrap()],
549            &[KeyContext::parse("editor").unwrap()],
550        );
551        assert_eq!(result.len(), 1);
552        assert!(!pending);
553    }
554
555    #[test]
556    fn test_simple_disable() {
557        let bindings = [
558            KeyBinding::new("ctrl-x", ActionAlpha {}, Some("editor")),
559            KeyBinding::new("ctrl-x", NoAction {}, Some("editor")),
560        ];
561
562        let mut keymap = Keymap::default();
563        keymap.add_bindings(bindings);
564
565        // Ensure `space` results in pending input on the workspace, but not editor
566        let (result, pending) = keymap.bindings_for_input(
567            &[Keystroke::parse("ctrl-x").unwrap()],
568            &[KeyContext::parse("editor").unwrap()],
569        );
570        assert!(result.is_empty());
571        assert!(!pending);
572    }
573
574    #[test]
575    fn test_disable_weaker_sources_only() {
576        const USER: KeyBindingMetaIndex = KeyBindingMetaIndex(0);
577        const VIM: KeyBindingMetaIndex = KeyBindingMetaIndex(1);
578        const BASE: KeyBindingMetaIndex = KeyBindingMetaIndex(2);
579        const DEFAULT: KeyBindingMetaIndex = KeyBindingMetaIndex(3);
580
581        let editor_context = || [KeyContext::parse("editor").unwrap()];
582        let ctrl_x = || [Keystroke::parse("ctrl-x").unwrap()];
583
584        // A base keymap null disables a default binding in the same context.
585        let mut keymap = Keymap::default();
586        keymap.add_bindings([
587            KeyBinding::new("ctrl-x", ActionAlpha {}, Some("editor")).with_meta(DEFAULT),
588            KeyBinding::new("ctrl-x", NoAction {}, Some("editor")).with_meta(BASE),
589        ]);
590        let (result, _) = keymap.bindings_for_input(&ctrl_x(), &editor_context());
591        assert!(result.is_empty());
592
593        // A user binding is not affected by base keymap or default nulls.
594        let mut keymap = Keymap::default();
595        keymap.add_bindings([
596            KeyBinding::new("ctrl-x", NoAction {}, Some("editor")).with_meta(DEFAULT),
597            KeyBinding::new("ctrl-x", NoAction {}, Some("editor")).with_meta(BASE),
598            KeyBinding::new("ctrl-x", ActionBeta {}, None).with_meta(USER),
599        ]);
600        let (result, _) = keymap.bindings_for_input(&ctrl_x(), &editor_context());
601        assert_eq!(result.len(), 1);
602        assert!(result[0].action.partial_eq(&ActionBeta {}));
603
604        // A user binding at a shallower context is not disabled by a deeper
605        // base keymap null.
606        let mut keymap = Keymap::default();
607        keymap.add_bindings([
608            KeyBinding::new("ctrl-x", NoAction {}, Some("editor")).with_meta(BASE),
609            KeyBinding::new("ctrl-x", ActionBeta {}, Some("workspace")).with_meta(USER),
610        ]);
611        let (result, _) = keymap.bindings_for_input(
612            &ctrl_x(),
613            &[
614                KeyContext::parse("workspace").unwrap(),
615                KeyContext::parse("editor").unwrap(),
616            ],
617        );
618        assert_eq!(result.len(), 1);
619        assert!(result[0].action.partial_eq(&ActionBeta {}));
620
621        // A vim binding survives a base keymap null, and a user null disables
622        // everything.
623        let mut keymap = Keymap::default();
624        keymap.add_bindings([
625            KeyBinding::new("ctrl-x", ActionAlpha {}, Some("editor")).with_meta(DEFAULT),
626            KeyBinding::new("ctrl-x", NoAction {}, Some("editor")).with_meta(BASE),
627            KeyBinding::new("ctrl-x", ActionGamma {}, Some("editor")).with_meta(VIM),
628        ]);
629        let (result, _) = keymap.bindings_for_input(&ctrl_x(), &editor_context());
630        assert_eq!(result.len(), 1);
631        assert!(result[0].action.partial_eq(&ActionGamma {}));
632
633        let mut keymap = Keymap::default();
634        keymap.add_bindings([
635            KeyBinding::new("ctrl-x", ActionAlpha {}, Some("editor")).with_meta(DEFAULT),
636            KeyBinding::new("ctrl-x", ActionGamma {}, Some("editor")).with_meta(VIM),
637            KeyBinding::new("ctrl-x", NoAction {}, Some("editor")).with_meta(USER),
638        ]);
639        let (result, _) = keymap.bindings_for_input(&ctrl_x(), &editor_context());
640        assert!(result.is_empty());
641    }
642
643    #[test]
644    fn test_fail_to_disable() {
645        // disabled at the wrong level
646        let bindings = [
647            KeyBinding::new("ctrl-x", ActionAlpha {}, Some("editor")),
648            KeyBinding::new("ctrl-x", NoAction {}, Some("workspace")),
649        ];
650
651        let mut keymap = Keymap::default();
652        keymap.add_bindings(bindings);
653
654        // Ensure `space` results in pending input on the workspace, but not editor
655        let (result, pending) = keymap.bindings_for_input(
656            &[Keystroke::parse("ctrl-x").unwrap()],
657            &[
658                KeyContext::parse("workspace").unwrap(),
659                KeyContext::parse("editor").unwrap(),
660            ],
661        );
662        assert_eq!(result.len(), 1);
663        assert!(!pending);
664    }
665
666    #[test]
667    fn test_disable_deeper() {
668        let bindings = [
669            KeyBinding::new("ctrl-x", ActionAlpha {}, Some("workspace")),
670            KeyBinding::new("ctrl-x", NoAction {}, Some("editor")),
671        ];
672
673        let mut keymap = Keymap::default();
674        keymap.add_bindings(bindings);
675
676        // Ensure `space` results in pending input on the workspace, but not editor
677        let (result, pending) = keymap.bindings_for_input(
678            &[Keystroke::parse("ctrl-x").unwrap()],
679            &[
680                KeyContext::parse("workspace").unwrap(),
681                KeyContext::parse("editor").unwrap(),
682            ],
683        );
684        assert_eq!(result.len(), 0);
685        assert!(!pending);
686    }
687
688    #[test]
689    fn test_pending_match_enabled() {
690        let bindings = [
691            KeyBinding::new("ctrl-x", ActionBeta, Some("vim_mode == normal")),
692            KeyBinding::new("ctrl-x 0", ActionAlpha, Some("Workspace")),
693        ];
694        let mut keymap = Keymap::default();
695        keymap.add_bindings(bindings);
696
697        let matched = keymap.bindings_for_input(
698            &[Keystroke::parse("ctrl-x")].map(Result::unwrap),
699            &[
700                KeyContext::parse("Workspace"),
701                KeyContext::parse("Pane"),
702                KeyContext::parse("Editor vim_mode=normal"),
703            ]
704            .map(Result::unwrap),
705        );
706        assert_eq!(matched.0.len(), 1);
707        assert!(matched.0[0].action.partial_eq(&ActionBeta));
708        assert!(matched.1);
709    }
710
711    #[test]
712    fn test_pending_match_enabled_extended() {
713        let bindings = [
714            KeyBinding::new("ctrl-x", ActionBeta, Some("vim_mode == normal")),
715            KeyBinding::new("ctrl-x 0", NoAction, Some("Workspace")),
716        ];
717        let mut keymap = Keymap::default();
718        keymap.add_bindings(bindings);
719
720        let matched = keymap.bindings_for_input(
721            &[Keystroke::parse("ctrl-x")].map(Result::unwrap),
722            &[
723                KeyContext::parse("Workspace"),
724                KeyContext::parse("Pane"),
725                KeyContext::parse("Editor vim_mode=normal"),
726            ]
727            .map(Result::unwrap),
728        );
729        assert_eq!(matched.0.len(), 1);
730        assert!(matched.0[0].action.partial_eq(&ActionBeta));
731        assert!(!matched.1);
732        let bindings = [
733            KeyBinding::new("ctrl-x", ActionBeta, Some("Workspace")),
734            KeyBinding::new("ctrl-x 0", NoAction, Some("vim_mode == normal")),
735        ];
736        let mut keymap = Keymap::default();
737        keymap.add_bindings(bindings);
738
739        let matched = keymap.bindings_for_input(
740            &[Keystroke::parse("ctrl-x")].map(Result::unwrap),
741            &[
742                KeyContext::parse("Workspace"),
743                KeyContext::parse("Pane"),
744                KeyContext::parse("Editor vim_mode=normal"),
745            ]
746            .map(Result::unwrap),
747        );
748        assert_eq!(matched.0.len(), 1);
749        assert!(matched.0[0].action.partial_eq(&ActionBeta));
750        assert!(!matched.1);
751    }
752
753    #[test]
754    fn test_overriding_prefix() {
755        let bindings = [
756            KeyBinding::new("ctrl-x 0", ActionAlpha, Some("Workspace")),
757            KeyBinding::new("ctrl-x", ActionBeta, Some("vim_mode == normal")),
758        ];
759        let mut keymap = Keymap::default();
760        keymap.add_bindings(bindings);
761
762        let matched = keymap.bindings_for_input(
763            &[Keystroke::parse("ctrl-x")].map(Result::unwrap),
764            &[
765                KeyContext::parse("Workspace"),
766                KeyContext::parse("Pane"),
767                KeyContext::parse("Editor vim_mode=normal"),
768            ]
769            .map(Result::unwrap),
770        );
771        assert_eq!(matched.0.len(), 1);
772        assert!(matched.0[0].action.partial_eq(&ActionBeta));
773        assert!(!matched.1);
774    }
775
776    #[test]
777    fn test_context_precedence_with_same_source() {
778        // Test case: User has both Workspace and Editor bindings for the same key
779        // Editor binding should take precedence over Workspace binding
780        let bindings = [
781            KeyBinding::new("cmd-r", ActionAlpha {}, Some("Workspace")),
782            KeyBinding::new("cmd-r", ActionBeta {}, Some("Editor")),
783        ];
784
785        let mut keymap = Keymap::default();
786        keymap.add_bindings(bindings);
787
788        // Test with context stack: [Workspace, Editor] (Editor is deeper)
789        let (result, _) = keymap.bindings_for_input(
790            &[Keystroke::parse("cmd-r").unwrap()],
791            &[
792                KeyContext::parse("Workspace").unwrap(),
793                KeyContext::parse("Editor").unwrap(),
794            ],
795        );
796
797        // Both bindings should be returned, but Editor binding should be first (highest precedence)
798        assert_eq!(result.len(), 2);
799        assert!(result[0].action.partial_eq(&ActionBeta {})); // Editor binding first
800        assert!(result[1].action.partial_eq(&ActionAlpha {})); // Workspace binding second
801    }
802
803    #[test]
804    fn test_bindings_for_action() {
805        let bindings = [
806            KeyBinding::new("ctrl-a", ActionAlpha {}, Some("pane")),
807            KeyBinding::new("ctrl-b", ActionBeta {}, Some("editor && mode == full")),
808            KeyBinding::new("ctrl-c", ActionGamma {}, Some("workspace")),
809            KeyBinding::new("ctrl-a", NoAction {}, Some("pane && active")),
810            KeyBinding::new("ctrl-b", NoAction {}, Some("editor")),
811        ];
812
813        let mut keymap = Keymap::default();
814        keymap.add_bindings(bindings);
815
816        assert_bindings(&keymap, &ActionAlpha {}, &["ctrl-a"]);
817        assert_bindings(&keymap, &ActionBeta {}, &[]);
818        assert_bindings(&keymap, &ActionGamma {}, &["ctrl-c"]);
819
820        #[track_caller]
821        fn assert_bindings(keymap: &Keymap, action: &dyn Action, expected: &[&str]) {
822            let actual = keymap
823                .bindings_for_action(action)
824                .map(|binding| binding.keystrokes[0].inner().unparse())
825                .collect::<Vec<_>>();
826            assert_eq!(actual, expected, "{:?}", action);
827        }
828    }
829
830    #[test]
831    fn test_targeted_unbind_ignores_target_context() {
832        let bindings = [
833            KeyBinding::new("tab", ActionAlpha {}, Some("Editor")),
834            KeyBinding::new("tab", ActionBeta {}, Some("Editor && showing_completions")),
835            KeyBinding::new(
836                "tab",
837                Unbind("test_only::ActionAlpha".into()),
838                Some("Editor && edit_prediction"),
839            ),
840        ];
841
842        let mut keymap = Keymap::default();
843        keymap.add_bindings(bindings);
844
845        let (result, pending) = keymap.bindings_for_input(
846            &[Keystroke::parse("tab").unwrap()],
847            &[KeyContext::parse("Editor showing_completions edit_prediction").unwrap()],
848        );
849
850        assert!(!pending);
851        assert_eq!(result.len(), 1);
852        assert!(result[0].action.partial_eq(&ActionBeta {}));
853    }
854
855    #[test]
856    fn test_bindings_for_action_keeps_binding_for_narrower_targeted_unbind() {
857        let bindings = [
858            KeyBinding::new("tab", ActionAlpha {}, Some("Editor")),
859            KeyBinding::new(
860                "tab",
861                Unbind("test_only::ActionAlpha".into()),
862                Some("Editor && edit_prediction"),
863            ),
864            KeyBinding::new("tab", ActionBeta {}, Some("Editor && showing_completions")),
865        ];
866
867        let mut keymap = Keymap::default();
868        keymap.add_bindings(bindings);
869
870        assert_bindings(&keymap, &ActionAlpha {}, &["tab"]);
871        assert_bindings(&keymap, &ActionBeta {}, &["tab"]);
872
873        #[track_caller]
874        fn assert_bindings(keymap: &Keymap, action: &dyn Action, expected: &[&str]) {
875            let actual = keymap
876                .bindings_for_action(action)
877                .map(|binding| binding.keystrokes[0].inner().unparse())
878                .collect::<Vec<_>>();
879            assert_eq!(actual, expected, "{:?}", action);
880        }
881    }
882
883    #[test]
884    fn test_bindings_for_action_removes_binding_for_broader_targeted_unbind() {
885        let bindings = [
886            KeyBinding::new("tab", ActionAlpha {}, Some("Editor && edit_prediction")),
887            KeyBinding::new(
888                "tab",
889                Unbind("test_only::ActionAlpha".into()),
890                Some("Editor"),
891            ),
892        ];
893
894        let mut keymap = Keymap::default();
895        keymap.add_bindings(bindings);
896
897        assert!(keymap.bindings_for_action(&ActionAlpha {}).next().is_none());
898    }
899
900    #[test]
901    fn test_source_precedence_sorting() {
902        // KeybindSource precedence: User (0) > Vim (1) > Base (2) > Default (3)
903        // Test that user keymaps take precedence over default keymaps at the same context depth
904        let mut keymap = Keymap::default();
905
906        // Add a default keymap binding first
907        let mut default_binding = KeyBinding::new("cmd-r", ActionAlpha {}, Some("Editor"));
908        default_binding.set_meta(KeyBindingMetaIndex(3)); // Default source
909        keymap.add_bindings([default_binding]);
910
911        // Add a user keymap binding
912        let mut user_binding = KeyBinding::new("cmd-r", ActionBeta {}, Some("Editor"));
913        user_binding.set_meta(KeyBindingMetaIndex(0)); // User source
914        keymap.add_bindings([user_binding]);
915
916        // Test with Editor context stack
917        let (result, _) = keymap.bindings_for_input(
918            &[Keystroke::parse("cmd-r").unwrap()],
919            &[KeyContext::parse("Editor").unwrap()],
920        );
921
922        // User binding should take precedence over default binding
923        assert_eq!(result.len(), 2);
924        assert!(result[0].action.partial_eq(&ActionBeta {}));
925        assert!(result[1].action.partial_eq(&ActionAlpha {}));
926    }
927}
928
Served at tenant.openagents/omega Member data and write actions are omitted.