Skip to main content

gpui/keymap/
context.rs

1use crate::SharedString;
2use anyhow::{Context as _, Result};
3use std::fmt;
4
5/// A datastructure for resolving whether an action should be dispatched
6/// at this point in the element tree. Contains a set of identifiers
7/// and/or key value pairs representing the current context for the
8/// keymap.
9#[derive(Clone, Default, Eq, PartialEq, Hash)]
10pub struct KeyContext(Vec<ContextEntry>);
11
12#[derive(Clone, Debug, Eq, PartialEq, Hash)]
13/// An entry in a KeyContext
14pub struct ContextEntry {
15    /// The key (or name if no value)
16    pub key: SharedString,
17    /// The value
18    pub value: Option<SharedString>,
19}
20
21impl<'a> TryFrom<&'a str> for KeyContext {
22    type Error = anyhow::Error;
23
24    fn try_from(value: &'a str) -> Result<Self> {
25        Self::parse(value)
26    }
27}
28
29impl KeyContext {
30    /// Initializes a key context with the supplied host operating system.
31    pub fn new_with_defaults(os: crate::OperatingSystem) -> Self {
32        let mut context = Self::default();
33        context.set(
34            "os",
35            match os {
36                crate::OperatingSystem::Mac => "macos",
37                crate::OperatingSystem::Linux | crate::OperatingSystem::FreeBsd => "linux",
38                crate::OperatingSystem::Windows => "windows",
39                crate::OperatingSystem::Ios => "ios",
40                crate::OperatingSystem::Android => "android",
41                crate::OperatingSystem::Unknown => "unknown",
42            },
43        );
44        context
45    }
46
47    /// Returns the primary context entry (usually the name of the component)
48    pub fn primary(&self) -> Option<&ContextEntry> {
49        self.0.iter().find(|p| p.value.is_none())
50    }
51
52    /// Returns everything except the primary context entry.
53    pub fn secondary(&self) -> impl Iterator<Item = &ContextEntry> {
54        let primary = self.primary();
55        self.0.iter().filter(move |&p| Some(p) != primary)
56    }
57
58    /// Parse a key context from a string.
59    /// The key context format is very simple:
60    /// - either a single identifier, such as `StatusBar`
61    /// - or a key value pair, such as `mode = visible`
62    /// - separated by whitespace, such as `StatusBar mode = visible`
63    pub fn parse(source: &str) -> Result<Self> {
64        let mut context = Self::default();
65        let source = skip_whitespace(source);
66        Self::parse_expr(source, &mut context)?;
67        Ok(context)
68    }
69
70    fn parse_expr(mut source: &str, context: &mut Self) -> Result<()> {
71        if source.is_empty() {
72            return Ok(());
73        }
74
75        let key = source
76            .chars()
77            .take_while(|c| is_identifier_char(*c))
78            .collect::<String>();
79        source = skip_whitespace(&source[key.len()..]);
80        if let Some(suffix) = source.strip_prefix('=') {
81            source = skip_whitespace(suffix);
82            let value = source
83                .chars()
84                .take_while(|c| is_identifier_char(*c))
85                .collect::<String>();
86            source = skip_whitespace(&source[value.len()..]);
87            context.set(key, value);
88        } else {
89            context.add(key);
90        }
91
92        Self::parse_expr(source, context)
93    }
94
95    /// Check if this context is empty.
96    pub fn is_empty(&self) -> bool {
97        self.0.is_empty()
98    }
99
100    /// Clear this context.
101    pub fn clear(&mut self) {
102        self.0.clear();
103    }
104
105    /// Extend this context with another context.
106    pub fn extend(&mut self, other: &Self) {
107        for entry in &other.0 {
108            if !self.contains(&entry.key) {
109                self.0.push(entry.clone());
110            }
111        }
112    }
113
114    /// Add an identifier to this context, if it's not already in this context.
115    pub fn add<I: Into<SharedString>>(&mut self, identifier: I) {
116        let key = identifier.into();
117
118        if !self.contains(&key) {
119            self.0.push(ContextEntry { key, value: None })
120        }
121    }
122
123    /// Set a key value pair in this context, if it's not already set.
124    pub fn set<S1: Into<SharedString>, S2: Into<SharedString>>(&mut self, key: S1, value: S2) {
125        let key = key.into();
126        if !self.contains(&key) {
127            self.0.push(ContextEntry {
128                key,
129                value: Some(value.into()),
130            })
131        }
132    }
133
134    /// Check if this context contains a given identifier or key.
135    pub fn contains(&self, key: &str) -> bool {
136        self.0.iter().any(|entry| entry.key.as_ref() == key)
137    }
138
139    /// Get the associated value for a given identifier or key.
140    pub fn get(&self, key: &str) -> Option<&SharedString> {
141        self.0
142            .iter()
143            .find(|entry| entry.key.as_ref() == key)?
144            .value
145            .as_ref()
146    }
147}
148
149impl fmt::Debug for KeyContext {
150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151        let mut entries = self.0.iter().peekable();
152        while let Some(entry) = entries.next() {
153            if let Some(ref value) = entry.value {
154                write!(f, "{}={}", entry.key, value)?;
155            } else {
156                write!(f, "{}", entry.key)?;
157            }
158            if entries.peek().is_some() {
159                write!(f, " ")?;
160            }
161        }
162        Ok(())
163    }
164}
165
166/// A datastructure for resolving whether an action should be dispatched
167/// Representing a small language for describing which contexts correspond
168/// to which actions.
169#[derive(Clone, Debug, Eq, PartialEq, Hash)]
170pub enum KeyBindingContextPredicate {
171    /// A predicate that will match a given identifier.
172    Identifier(SharedString),
173    /// A predicate that will match a given key-value pair.
174    Equal(SharedString, SharedString),
175    /// A predicate that will match a given key-value pair not being present.
176    NotEqual(SharedString, SharedString),
177    /// A predicate that will match a given predicate appearing below another predicate.
178    /// in the element tree
179    Descendant(
180        Box<KeyBindingContextPredicate>,
181        Box<KeyBindingContextPredicate>,
182    ),
183    /// Predicate that will invert another predicate.
184    Not(Box<KeyBindingContextPredicate>),
185    /// A predicate that will match if both of its children match.
186    And(
187        Box<KeyBindingContextPredicate>,
188        Box<KeyBindingContextPredicate>,
189    ),
190    /// A predicate that will match if either of its children match.
191    Or(
192        Box<KeyBindingContextPredicate>,
193        Box<KeyBindingContextPredicate>,
194    ),
195}
196
197impl fmt::Display for KeyBindingContextPredicate {
198    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199        match self {
200            Self::Identifier(name) => write!(f, "{name}"),
201            Self::Equal(left, right) => write!(f, "{left} == {right}"),
202            Self::NotEqual(left, right) => write!(f, "{left} != {right}"),
203            Self::Descendant(parent, child) => write!(f, "{parent} > {child}"),
204            Self::Not(pred) => match pred.as_ref() {
205                Self::Identifier(name) => write!(f, "!{name}"),
206                _ => write!(f, "!({pred})"),
207            },
208            Self::And(..) => self.fmt_joined(f, " && ", LogicalOperator::And, |node| {
209                matches!(node, Self::Or(..))
210            }),
211            Self::Or(..) => self.fmt_joined(f, " || ", LogicalOperator::Or, |node| {
212                matches!(node, Self::And(..))
213            }),
214        }
215    }
216}
217
218impl KeyBindingContextPredicate {
219    /// Parse a string in the same format as the keymap's context field.
220    ///
221    /// A basic equivalence check against a set of identifiers can performed by
222    /// simply writing a string:
223    ///
224    /// `StatusBar` -> A predicate that will match a context with the identifier `StatusBar`
225    ///
226    /// You can also specify a key-value pair:
227    ///
228    /// `mode == visible` -> A predicate that will match a context with the key `mode`
229    ///                      with the value `visible`
230    ///
231    /// And a logical operations combining these two checks:
232    ///
233    /// `StatusBar && mode == visible` -> A predicate that will match a context with the
234    ///                                   identifier `StatusBar` and the key `mode`
235    ///                                   with the value `visible`
236    ///
237    ///
238    /// There is also a special child `>` operator that will match a predicate that is
239    /// below another predicate:
240    ///
241    /// `StatusBar > mode == visible` -> A predicate that will match a context identifier `StatusBar`
242    ///                                  and a child context that has the key `mode` with the
243    ///                                  value `visible`
244    ///
245    /// This syntax supports `!=`, `||` and `&&` as logical operators.
246    /// You can also preface an operation or check with a `!` to negate it.
247    pub fn parse(source: &str) -> Result<Self> {
248        let source = skip_whitespace(source);
249        let (predicate, rest) = Self::parse_expr(source, 0)?;
250        if let Some(next) = rest.chars().next() {
251            anyhow::bail!("unexpected character '{next:?}'");
252        } else {
253            Ok(predicate)
254        }
255    }
256
257    /// Find the deepest depth at which the predicate matches.
258    pub fn depth_of(&self, contexts: &[KeyContext]) -> Option<usize> {
259        for depth in (0..=contexts.len()).rev() {
260            let context_slice = &contexts[0..depth];
261            if self.eval_inner(context_slice, contexts) {
262                return Some(depth);
263            }
264        }
265        None
266    }
267
268    /// Eval a predicate against a set of contexts, arranged from lowest to highest.
269    pub fn eval(&self, contexts: &[KeyContext]) -> bool {
270        self.eval_inner(contexts, contexts)
271    }
272
273    /// Eval a predicate against a set of contexts, arranged from lowest to highest.
274    pub fn eval_inner(&self, contexts: &[KeyContext], all_contexts: &[KeyContext]) -> bool {
275        let Some(context) = contexts.last() else {
276            return false;
277        };
278        match self {
279            Self::Identifier(name) => context.contains(name),
280            Self::Equal(left, right) => context
281                .get(left)
282                .map(|value| value == right)
283                .unwrap_or(false),
284            Self::NotEqual(left, right) => context
285                .get(left)
286                .map(|value| value != right)
287                .unwrap_or(true),
288            Self::Not(pred) => {
289                for i in 0..all_contexts.len() {
290                    if pred.eval_inner(&all_contexts[..=i], all_contexts) {
291                        return false;
292                    }
293                }
294                true
295            }
296            // Workspace > Pane > Editor
297            //
298            // Pane > (Pane > Editor) // should match?
299            // (Pane > Pane) > Editor // should not match?
300            // Pane > !Workspace <-- should match?
301            // !Workspace        <-- shouldn't match?
302            Self::Descendant(parent, child) => {
303                for i in 0..contexts.len() - 1 {
304                    // [Workspace >  Pane], [Editor]
305                    if parent.eval_inner(&contexts[..=i], all_contexts) {
306                        if !child.eval_inner(&contexts[i + 1..], &contexts[i + 1..]) {
307                            return false;
308                        }
309                        return true;
310                    }
311                }
312                false
313            }
314            Self::And(left, right) => {
315                left.eval_inner(contexts, all_contexts) && right.eval_inner(contexts, all_contexts)
316            }
317            Self::Or(left, right) => {
318                left.eval_inner(contexts, all_contexts) || right.eval_inner(contexts, all_contexts)
319            }
320        }
321    }
322
323    /// Returns whether or not this predicate matches all possible contexts matched by
324    /// the other predicate.
325    pub fn is_superset(&self, other: &Self) -> bool {
326        if self == other {
327            return true;
328        }
329
330        if let KeyBindingContextPredicate::Or(left, right) = self {
331            return left.is_superset(other) || right.is_superset(other);
332        }
333
334        match other {
335            KeyBindingContextPredicate::Descendant(_, child) => self.is_superset(child),
336            KeyBindingContextPredicate::And(left, right) => {
337                self.is_superset(left) || self.is_superset(right)
338            }
339            KeyBindingContextPredicate::Identifier(_) => false,
340            KeyBindingContextPredicate::Equal(_, _) => false,
341            KeyBindingContextPredicate::NotEqual(_, _) => false,
342            KeyBindingContextPredicate::Not(_) => false,
343            KeyBindingContextPredicate::Or(_, _) => false,
344        }
345    }
346
347    fn parse_expr(mut source: &str, min_precedence: u32) -> anyhow::Result<(Self, &str)> {
348        type Op = fn(
349            KeyBindingContextPredicate,
350            KeyBindingContextPredicate,
351        ) -> Result<KeyBindingContextPredicate>;
352
353        let (mut predicate, rest) = Self::parse_primary(source)?;
354        source = rest;
355
356        'parse: loop {
357            for (operator, precedence, constructor) in [
358                (">", PRECEDENCE_CHILD, Self::new_child as Op),
359                ("&&", PRECEDENCE_AND, Self::new_and as Op),
360                ("||", PRECEDENCE_OR, Self::new_or as Op),
361                ("==", PRECEDENCE_EQ, Self::new_eq as Op),
362                ("!=", PRECEDENCE_EQ, Self::new_neq as Op),
363            ] {
364                if source.starts_with(operator) && precedence >= min_precedence {
365                    source = skip_whitespace(&source[operator.len()..]);
366                    let (right, rest) = Self::parse_expr(source, precedence + 1)?;
367                    predicate = constructor(predicate, right)?;
368                    source = rest;
369                    continue 'parse;
370                }
371            }
372            break;
373        }
374
375        Ok((predicate, source))
376    }
377
378    fn parse_primary(mut source: &str) -> anyhow::Result<(Self, &str)> {
379        let next = source.chars().next().context("unexpected end")?;
380        match next {
381            '(' => {
382                source = skip_whitespace(&source[1..]);
383                let (predicate, rest) = Self::parse_expr(source, 0)?;
384                let stripped = rest.strip_prefix(')').context("expected a ')'")?;
385                source = skip_whitespace(stripped);
386                Ok((predicate, source))
387            }
388            '!' => {
389                let source = skip_whitespace(&source[1..]);
390                let (predicate, source) = Self::parse_expr(source, PRECEDENCE_NOT)?;
391                Ok((KeyBindingContextPredicate::Not(Box::new(predicate)), source))
392            }
393            _ if is_identifier_char(next) => {
394                let len = source
395                    .find(|c: char| !is_identifier_char(c) && !is_vim_operator_char(c))
396                    .unwrap_or(source.len());
397                let (identifier, rest) = source.split_at(len);
398                source = skip_whitespace(rest);
399                Ok((
400                    KeyBindingContextPredicate::Identifier(identifier.to_string().into()),
401                    source,
402                ))
403            }
404            _ if is_vim_operator_char(next) => {
405                let (operator, rest) = source.split_at(1);
406                source = skip_whitespace(rest);
407                Ok((
408                    KeyBindingContextPredicate::Identifier(operator.to_string().into()),
409                    source,
410                ))
411            }
412            _ => anyhow::bail!("unexpected character '{next:?}'"),
413        }
414    }
415
416    fn new_or(self, other: Self) -> Result<Self> {
417        Ok(Self::Or(Box::new(self), Box::new(other)))
418    }
419
420    fn new_and(self, other: Self) -> Result<Self> {
421        Ok(Self::And(Box::new(self), Box::new(other)))
422    }
423
424    fn new_child(self, other: Self) -> Result<Self> {
425        Ok(Self::Descendant(Box::new(self), Box::new(other)))
426    }
427
428    fn new_eq(self, other: Self) -> Result<Self> {
429        if let (Self::Identifier(left), Self::Identifier(right)) = (self, other) {
430            Ok(Self::Equal(left, right))
431        } else {
432            anyhow::bail!("operands of == must be identifiers");
433        }
434    }
435
436    fn new_neq(self, other: Self) -> Result<Self> {
437        if let (Self::Identifier(left), Self::Identifier(right)) = (self, other) {
438            Ok(Self::NotEqual(left, right))
439        } else {
440            anyhow::bail!("operands of != must be identifiers");
441        }
442    }
443
444    fn fmt_joined(
445        &self,
446        f: &mut fmt::Formatter<'_>,
447        separator: &str,
448        operator: LogicalOperator,
449        needs_parens: impl Fn(&Self) -> bool + Copy,
450    ) -> fmt::Result {
451        let mut first = true;
452        self.fmt_joined_inner(f, separator, operator, needs_parens, &mut first)
453    }
454
455    fn fmt_joined_inner(
456        &self,
457        f: &mut fmt::Formatter<'_>,
458        separator: &str,
459        operator: LogicalOperator,
460        needs_parens: impl Fn(&Self) -> bool + Copy,
461        first: &mut bool,
462    ) -> fmt::Result {
463        match (operator, self) {
464            (LogicalOperator::And, Self::And(left, right))
465            | (LogicalOperator::Or, Self::Or(left, right)) => {
466                left.fmt_joined_inner(f, separator, operator, needs_parens, first)?;
467                right.fmt_joined_inner(f, separator, operator, needs_parens, first)
468            }
469            (_, node) => {
470                if !*first {
471                    f.write_str(separator)?;
472                }
473                *first = false;
474
475                if needs_parens(node) {
476                    write!(f, "({node})")
477                } else {
478                    write!(f, "{node}")
479                }
480            }
481        }
482    }
483}
484
485#[derive(Clone, Copy)]
486enum LogicalOperator {
487    And,
488    Or,
489}
490
491const PRECEDENCE_CHILD: u32 = 1;
492const PRECEDENCE_OR: u32 = 2;
493const PRECEDENCE_AND: u32 = 3;
494const PRECEDENCE_EQ: u32 = 4;
495const PRECEDENCE_NOT: u32 = 5;
496
497fn is_identifier_char(c: char) -> bool {
498    c.is_alphanumeric() || c == '_' || c == '-'
499}
500
501fn is_vim_operator_char(c: char) -> bool {
502    c == '>' || c == '<' || c == '~' || c == '"' || c == '?'
503}
504
505fn skip_whitespace(source: &str) -> &str {
506    let len = source
507        .find(|c: char| !c.is_whitespace())
508        .unwrap_or(source.len());
509    &source[len..]
510}
511
512#[cfg(test)]
513mod tests {
514    use core::slice;
515
516    use super::*;
517    use crate as gpui;
518    use KeyBindingContextPredicate::*;
519
520    #[test]
521    fn test_actions_definition() {
522        {
523            actions!(test_only, [A, B, C, D, E, F, G]);
524        }
525
526        {
527            actions!(
528                test_only,
529                [
530                    H, I, J, K, L, M, N, // Don't wrap, test the trailing comma
531                ]
532            );
533        }
534    }
535
536    #[test]
537    fn test_parse_context() {
538        let mut expected = KeyContext::default();
539        expected.add("baz");
540        expected.set("foo", "bar");
541        assert_eq!(KeyContext::parse("baz foo=bar").unwrap(), expected);
542        assert_eq!(KeyContext::parse("baz foo = bar").unwrap(), expected);
543        assert_eq!(
544            KeyContext::parse("  baz foo   =   bar baz").unwrap(),
545            expected
546        );
547        assert_eq!(KeyContext::parse(" baz foo = bar").unwrap(), expected);
548    }
549
550    #[test]
551    fn test_parse_identifiers() {
552        // Identifiers
553        assert_eq!(
554            KeyBindingContextPredicate::parse("abc12").unwrap(),
555            Identifier("abc12".into())
556        );
557        assert_eq!(
558            KeyBindingContextPredicate::parse("_1a").unwrap(),
559            Identifier("_1a".into())
560        );
561    }
562
563    #[test]
564    fn test_parse_negations() {
565        assert_eq!(
566            KeyBindingContextPredicate::parse("!abc").unwrap(),
567            Not(Box::new(Identifier("abc".into())))
568        );
569        assert_eq!(
570            KeyBindingContextPredicate::parse(" ! ! abc").unwrap(),
571            Not(Box::new(Not(Box::new(Identifier("abc".into())))))
572        );
573    }
574
575    #[test]
576    fn test_parse_equality_operators() {
577        assert_eq!(
578            KeyBindingContextPredicate::parse("a == b").unwrap(),
579            Equal("a".into(), "b".into())
580        );
581        assert_eq!(
582            KeyBindingContextPredicate::parse("c!=d").unwrap(),
583            NotEqual("c".into(), "d".into())
584        );
585        assert_eq!(
586            KeyBindingContextPredicate::parse("c == !d")
587                .unwrap_err()
588                .to_string(),
589            "operands of == must be identifiers"
590        );
591    }
592
593    #[test]
594    fn test_parse_boolean_operators() {
595        assert_eq!(
596            KeyBindingContextPredicate::parse("a || b").unwrap(),
597            Or(
598                Box::new(Identifier("a".into())),
599                Box::new(Identifier("b".into()))
600            )
601        );
602        assert_eq!(
603            KeyBindingContextPredicate::parse("a || !b && c").unwrap(),
604            Or(
605                Box::new(Identifier("a".into())),
606                Box::new(And(
607                    Box::new(Not(Box::new(Identifier("b".into())))),
608                    Box::new(Identifier("c".into()))
609                ))
610            )
611        );
612        assert_eq!(
613            KeyBindingContextPredicate::parse("a && b || c&&d").unwrap(),
614            Or(
615                Box::new(And(
616                    Box::new(Identifier("a".into())),
617                    Box::new(Identifier("b".into()))
618                )),
619                Box::new(And(
620                    Box::new(Identifier("c".into())),
621                    Box::new(Identifier("d".into()))
622                ))
623            )
624        );
625        assert_eq!(
626            KeyBindingContextPredicate::parse("a == b && c || d == e && f").unwrap(),
627            Or(
628                Box::new(And(
629                    Box::new(Equal("a".into(), "b".into())),
630                    Box::new(Identifier("c".into()))
631                )),
632                Box::new(And(
633                    Box::new(Equal("d".into(), "e".into())),
634                    Box::new(Identifier("f".into()))
635                ))
636            )
637        );
638        assert_eq!(
639            KeyBindingContextPredicate::parse("a && b && c && d").unwrap(),
640            And(
641                Box::new(And(
642                    Box::new(And(
643                        Box::new(Identifier("a".into())),
644                        Box::new(Identifier("b".into()))
645                    )),
646                    Box::new(Identifier("c".into())),
647                )),
648                Box::new(Identifier("d".into()))
649            ),
650        );
651    }
652
653    #[test]
654    fn test_parse_parenthesized_expressions() {
655        assert_eq!(
656            KeyBindingContextPredicate::parse("a && (b == c || d != e)").unwrap(),
657            And(
658                Box::new(Identifier("a".into())),
659                Box::new(Or(
660                    Box::new(Equal("b".into(), "c".into())),
661                    Box::new(NotEqual("d".into(), "e".into())),
662                )),
663            ),
664        );
665        assert_eq!(
666            KeyBindingContextPredicate::parse(" ( a || b ) ").unwrap(),
667            Or(
668                Box::new(Identifier("a".into())),
669                Box::new(Identifier("b".into())),
670            )
671        );
672    }
673
674    #[test]
675    fn test_is_superset() {
676        assert_is_superset("editor", "editor", true);
677        assert_is_superset("editor", "workspace", false);
678
679        assert_is_superset("editor", "editor && vim_mode", true);
680        assert_is_superset("editor", "mode == full && editor", true);
681        assert_is_superset("editor && mode == full", "editor", false);
682
683        assert_is_superset("editor", "something > editor", true);
684        assert_is_superset("editor", "editor > menu", false);
685
686        assert_is_superset("foo || bar || baz", "bar", true);
687        assert_is_superset("foo || bar || baz", "quux", false);
688
689        #[track_caller]
690        fn assert_is_superset(a: &str, b: &str, result: bool) {
691            let a = KeyBindingContextPredicate::parse(a).unwrap();
692            let b = KeyBindingContextPredicate::parse(b).unwrap();
693            assert_eq!(a.is_superset(&b), result, "({a:?}).is_superset({b:?})");
694        }
695    }
696
697    #[test]
698    fn test_child_operator() {
699        let predicate = KeyBindingContextPredicate::parse("parent > child").unwrap();
700
701        let parent_context = KeyContext::try_from("parent").unwrap();
702        let child_context = KeyContext::try_from("child").unwrap();
703
704        let contexts = vec![parent_context.clone(), child_context.clone()];
705        assert!(predicate.eval(&contexts));
706
707        let grandparent_context = KeyContext::try_from("grandparent").unwrap();
708
709        let contexts = vec![
710            grandparent_context,
711            parent_context.clone(),
712            child_context.clone(),
713        ];
714        assert!(predicate.eval(&contexts));
715
716        let other_context = KeyContext::try_from("other").unwrap();
717
718        let contexts = vec![other_context.clone(), child_context.clone()];
719        assert!(!predicate.eval(&contexts));
720
721        let contexts = vec![parent_context.clone(), other_context, child_context.clone()];
722        assert!(predicate.eval(&contexts));
723
724        assert!(!predicate.eval(&[]));
725        assert!(!predicate.eval(slice::from_ref(&child_context)));
726        assert!(!predicate.eval(&[parent_context]));
727
728        let zany_predicate = KeyBindingContextPredicate::parse("child > child").unwrap();
729        assert!(!zany_predicate.eval(slice::from_ref(&child_context)));
730        assert!(zany_predicate.eval(&[child_context.clone(), child_context]));
731    }
732
733    #[test]
734    fn test_not_operator() {
735        let not_predicate = KeyBindingContextPredicate::parse("!editor").unwrap();
736        let editor_context = KeyContext::try_from("editor").unwrap();
737        let workspace_context = KeyContext::try_from("workspace").unwrap();
738        let parent_context = KeyContext::try_from("parent").unwrap();
739        let child_context = KeyContext::try_from("child").unwrap();
740
741        assert!(not_predicate.eval(slice::from_ref(&workspace_context)));
742        assert!(!not_predicate.eval(slice::from_ref(&editor_context)));
743        assert!(!not_predicate.eval(&[editor_context.clone(), workspace_context.clone()]));
744        assert!(!not_predicate.eval(&[workspace_context.clone(), editor_context.clone()]));
745
746        let complex_not = KeyBindingContextPredicate::parse("!editor && workspace").unwrap();
747        assert!(complex_not.eval(slice::from_ref(&workspace_context)));
748        assert!(!complex_not.eval(&[editor_context.clone(), workspace_context.clone()]));
749
750        let not_mode_predicate = KeyBindingContextPredicate::parse("!(mode == full)").unwrap();
751        let mut mode_context = KeyContext::default();
752        mode_context.set("mode", "full");
753        assert!(!not_mode_predicate.eval(&[mode_context.clone()]));
754
755        let mut other_mode_context = KeyContext::default();
756        other_mode_context.set("mode", "partial");
757        assert!(not_mode_predicate.eval(&[other_mode_context]));
758
759        let not_descendant = KeyBindingContextPredicate::parse("!(parent > child)").unwrap();
760        assert!(not_descendant.eval(slice::from_ref(&parent_context)));
761        assert!(not_descendant.eval(slice::from_ref(&child_context)));
762        assert!(!not_descendant.eval(&[parent_context.clone(), child_context.clone()]));
763
764        let not_descendant = KeyBindingContextPredicate::parse("parent > !child").unwrap();
765        assert!(!not_descendant.eval(slice::from_ref(&parent_context)));
766        assert!(!not_descendant.eval(slice::from_ref(&child_context)));
767        assert!(!not_descendant.eval(&[parent_context, child_context]));
768
769        let double_not = KeyBindingContextPredicate::parse("!!editor").unwrap();
770        assert!(double_not.eval(slice::from_ref(&editor_context)));
771        assert!(!double_not.eval(slice::from_ref(&workspace_context)));
772
773        // Test complex descendant cases
774        let workspace_context = KeyContext::try_from("Workspace").unwrap();
775        let pane_context = KeyContext::try_from("Pane").unwrap();
776        let editor_context = KeyContext::try_from("Editor").unwrap();
777
778        // Workspace > Pane > Editor
779        let workspace_pane_editor = vec![
780            workspace_context.clone(),
781            pane_context.clone(),
782            editor_context.clone(),
783        ];
784
785        // Pane > (Pane > Editor) - should not match
786        let pane_pane_editor = KeyBindingContextPredicate::parse("Pane > (Pane > Editor)").unwrap();
787        assert!(!pane_pane_editor.eval(&workspace_pane_editor));
788
789        let workspace_pane_editor_predicate =
790            KeyBindingContextPredicate::parse("Workspace > Pane > Editor").unwrap();
791        assert!(workspace_pane_editor_predicate.eval(&workspace_pane_editor));
792
793        // (Pane > Pane) > Editor - should not match
794        let pane_pane_then_editor =
795            KeyBindingContextPredicate::parse("(Pane > Pane) > Editor").unwrap();
796        assert!(!pane_pane_then_editor.eval(&workspace_pane_editor));
797
798        // Pane > !Workspace - should match
799        let pane_not_workspace = KeyBindingContextPredicate::parse("Pane > !Workspace").unwrap();
800        assert!(pane_not_workspace.eval(&[pane_context.clone(), editor_context.clone()]));
801        assert!(!pane_not_workspace.eval(&[pane_context.clone(), workspace_context.clone()]));
802
803        // !Workspace - shouldn't match when Workspace is in the context
804        let not_workspace = KeyBindingContextPredicate::parse("!Workspace").unwrap();
805        assert!(!not_workspace.eval(slice::from_ref(&workspace_context)));
806        assert!(not_workspace.eval(slice::from_ref(&pane_context)));
807        assert!(not_workspace.eval(slice::from_ref(&editor_context)));
808        assert!(!not_workspace.eval(&workspace_pane_editor));
809    }
810
811    // MARK: - Display
812
813    #[test]
814    fn test_context_display() {
815        fn ident(s: &str) -> Box<KeyBindingContextPredicate> {
816            Box::new(Identifier(SharedString::new(s)))
817        }
818        fn eq(a: &str, b: &str) -> Box<KeyBindingContextPredicate> {
819            Box::new(Equal(SharedString::new(a), SharedString::new(b)))
820        }
821        fn not_eq(a: &str, b: &str) -> Box<KeyBindingContextPredicate> {
822            Box::new(NotEqual(SharedString::new(a), SharedString::new(b)))
823        }
824        fn and(
825            a: Box<KeyBindingContextPredicate>,
826            b: Box<KeyBindingContextPredicate>,
827        ) -> Box<KeyBindingContextPredicate> {
828            Box::new(And(a, b))
829        }
830        fn or(
831            a: Box<KeyBindingContextPredicate>,
832            b: Box<KeyBindingContextPredicate>,
833        ) -> Box<KeyBindingContextPredicate> {
834            Box::new(Or(a, b))
835        }
836        fn descendant(
837            a: Box<KeyBindingContextPredicate>,
838            b: Box<KeyBindingContextPredicate>,
839        ) -> Box<KeyBindingContextPredicate> {
840            Box::new(Descendant(a, b))
841        }
842        fn not(a: Box<KeyBindingContextPredicate>) -> Box<KeyBindingContextPredicate> {
843            Box::new(Not(a))
844        }
845
846        let test_cases = [
847            (ident("a"), "a"),
848            (eq("a", "b"), "a == b"),
849            (not_eq("a", "b"), "a != b"),
850            (descendant(ident("a"), ident("b")), "a > b"),
851            (not(ident("a")), "!a"),
852            (not_eq("a", "b"), "a != b"),
853            (descendant(ident("a"), ident("b")), "a > b"),
854            (not(and(ident("a"), ident("b"))), "!(a && b)"),
855            (not(or(ident("a"), ident("b"))), "!(a || b)"),
856            (and(ident("a"), ident("b")), "a && b"),
857            (and(and(ident("a"), ident("b")), ident("c")), "a && b && c"),
858            (or(ident("a"), ident("b")), "a || b"),
859            (or(or(ident("a"), ident("b")), ident("c")), "a || b || c"),
860            (or(ident("a"), and(ident("b"), ident("c"))), "a || (b && c)"),
861            (
862                and(
863                    and(
864                        and(ident("a"), eq("b", "c")),
865                        not(descendant(ident("d"), ident("e"))),
866                    ),
867                    eq("f", "g"),
868                ),
869                "a && b == c && !(d > e) && f == g",
870            ),
871            (
872                and(and(ident("a"), or(ident("b"), ident("c"))), ident("d")),
873                "a && (b || c) && d",
874            ),
875            (
876                or(or(ident("a"), and(ident("b"), ident("c"))), ident("d")),
877                "a || (b && c) || d",
878            ),
879        ];
880
881        for (predicate, expected) in test_cases {
882            let actual = predicate.to_string();
883            assert_eq!(actual, expected);
884            let parsed = KeyBindingContextPredicate::parse(&actual).unwrap();
885            assert_eq!(parsed, *predicate);
886        }
887    }
888}