keymap.rs

  1mod binding;
  2mod context;
  3
  4pub use binding::*;
  5pub use context::*;
  6
  7use crate::{is_no_action, Action, Keystroke};
  8use collections::HashMap;
  9use smallvec::SmallVec;
 10use std::any::TypeId;
 11
 12/// An opaque identifier of which version of the keymap is currently active.
 13/// The keymap's version is changed whenever bindings are added or removed.
 14#[derive(Copy, Clone, Eq, PartialEq, Default)]
 15pub struct KeymapVersion(usize);
 16
 17/// A collection of key bindings for the user's application.
 18#[derive(Default)]
 19pub struct Keymap {
 20    bindings: Vec<KeyBinding>,
 21    binding_indices_by_action_id: HashMap<TypeId, SmallVec<[usize; 3]>>,
 22    no_action_binding_indices: Vec<usize>,
 23    version: KeymapVersion,
 24}
 25
 26impl Keymap {
 27    /// Create a new keymap with the given bindings.
 28    pub fn new(bindings: Vec<KeyBinding>) -> Self {
 29        let mut this = Self::default();
 30        this.add_bindings(bindings);
 31        this
 32    }
 33
 34    /// Get the current version of the keymap.
 35    pub fn version(&self) -> KeymapVersion {
 36        self.version
 37    }
 38
 39    /// Add more bindings to the keymap.
 40    pub fn add_bindings<T: IntoIterator<Item = KeyBinding>>(&mut self, bindings: T) {
 41        for binding in bindings {
 42            let action_id = binding.action().as_any().type_id();
 43            if is_no_action(&*binding.action) {
 44                self.no_action_binding_indices.push(self.bindings.len());
 45            } else {
 46                self.binding_indices_by_action_id
 47                    .entry(action_id)
 48                    .or_default()
 49                    .push(self.bindings.len());
 50            }
 51            self.bindings.push(binding);
 52        }
 53
 54        self.version.0 += 1;
 55    }
 56
 57    /// Reset this keymap to its initial state.
 58    pub fn clear(&mut self) {
 59        self.bindings.clear();
 60        self.binding_indices_by_action_id.clear();
 61        self.no_action_binding_indices.clear();
 62        self.version.0 += 1;
 63    }
 64
 65    /// Iterate over all bindings, in the order they were added.
 66    pub fn bindings(&self) -> impl DoubleEndedIterator<Item = &KeyBinding> {
 67        self.bindings.iter()
 68    }
 69
 70    /// Iterate over all bindings for the given action, in the order they were added.
 71    pub fn bindings_for_action<'a>(
 72        &'a self,
 73        action: &'a dyn Action,
 74    ) -> impl 'a + DoubleEndedIterator<Item = &'a KeyBinding> {
 75        let action_id = action.type_id();
 76        let binding_indices = self
 77            .binding_indices_by_action_id
 78            .get(&action_id)
 79            .map_or(&[] as _, SmallVec::as_slice)
 80            .iter();
 81
 82        binding_indices.filter_map(|ix| {
 83            let binding = &self.bindings[*ix];
 84            if !binding.action().partial_eq(action) {
 85                return None;
 86            }
 87
 88            for null_ix in &self.no_action_binding_indices {
 89                if null_ix > ix {
 90                    let null_binding = &self.bindings[*null_ix];
 91                    if null_binding.keystrokes == binding.keystrokes {
 92                        let null_binding_matches =
 93                            match (&null_binding.context_predicate, &binding.context_predicate) {
 94                                (None, _) => true,
 95                                (Some(_), None) => false,
 96                                (Some(null_predicate), Some(predicate)) => {
 97                                    null_predicate.is_superset(predicate)
 98                                }
 99                            };
100                        if null_binding_matches {
101                            return None;
102                        }
103                    }
104                }
105            }
106
107            Some(binding)
108        })
109    }
110
111    /// all bindings for input returns all bindings that might match the input
112    /// (without checking context)
113    pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
114        self.bindings()
115            .rev()
116            .filter_map(|binding| {
117                binding.match_keystrokes(input).filter(|pending| !pending)?;
118                Some(binding.clone())
119            })
120            .collect()
121    }
122
123    /// bindings_for_input returns a list of bindings that match the given input,
124    /// and a boolean indicating whether or not more bindings might match if
125    /// the input was longer.
126    ///
127    /// Precedence is defined by the depth in the tree (matches on the Editor take
128    /// precedence over matches on the Pane, then the Workspace, etc.). Bindings with
129    /// no context are treated as the same as the deepest context.
130    ///
131    /// In the case of multiple bindings at the same depth, the ones defined later in the
132    /// keymap take precedence (so user bindings take precedence over built-in bindings).
133    ///
134    /// If a user has disabled a binding with `"x": null` it will not be returned. Disabled
135    /// bindings are evaluated with the same precedence rules so you can disable a rule in
136    /// a given context only.
137    pub fn bindings_for_input(
138        &self,
139        input: &[Keystroke],
140        context_stack: &[KeyContext],
141    ) -> (SmallVec<[KeyBinding; 1]>, bool) {
142        let possibilities = self.bindings().rev().filter_map(|binding| {
143            binding
144                .match_keystrokes(input)
145                .map(|pending| (binding, pending))
146        });
147
148        let mut bindings: SmallVec<[(KeyBinding, usize); 1]> = SmallVec::new();
149        let mut is_pending = None;
150
151        'outer: for (binding, pending) in possibilities {
152            for depth in (0..=context_stack.len()).rev() {
153                if self.binding_enabled(binding, &context_stack[0..depth]) {
154                    if is_pending.is_none() {
155                        is_pending = Some(pending);
156                    }
157                    if !pending {
158                        bindings.push((binding.clone(), depth));
159                        continue 'outer;
160                    }
161                }
162            }
163        }
164        bindings.sort_by(|a, b| a.1.cmp(&b.1).reverse());
165        let bindings = bindings
166            .into_iter()
167            .map_while(|(binding, _)| {
168                if is_no_action(&*binding.action) {
169                    None
170                } else {
171                    Some(binding)
172                }
173            })
174            .collect();
175
176        (bindings, is_pending.unwrap_or_default())
177    }
178
179    /// Check if the given binding is enabled, given a certain key context.
180    fn binding_enabled(&self, binding: &KeyBinding, context: &[KeyContext]) -> bool {
181        // If binding has a context predicate, it must match the current context,
182        if let Some(predicate) = &binding.context_predicate {
183            if !predicate.eval(context) {
184                return false;
185            }
186        }
187
188        true
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195    use crate as gpui;
196    use gpui::{actions, NoAction};
197
198    actions!(
199        keymap_test,
200        [ActionAlpha, ActionBeta, ActionGamma, ActionDelta,]
201    );
202
203    #[test]
204    fn test_keymap() {
205        let bindings = [
206            KeyBinding::new("ctrl-a", ActionAlpha {}, None),
207            KeyBinding::new("ctrl-a", ActionBeta {}, Some("pane")),
208            KeyBinding::new("ctrl-a", ActionGamma {}, Some("editor && mode==full")),
209        ];
210
211        let mut keymap = Keymap::default();
212        keymap.add_bindings(bindings.clone());
213
214        // global bindings are enabled in all contexts
215        assert!(keymap.binding_enabled(&bindings[0], &[]));
216        assert!(keymap.binding_enabled(&bindings[0], &[KeyContext::parse("terminal").unwrap()]));
217
218        // contextual bindings are enabled in contexts that match their predicate
219        assert!(!keymap.binding_enabled(&bindings[1], &[KeyContext::parse("barf x=y").unwrap()]));
220        assert!(keymap.binding_enabled(&bindings[1], &[KeyContext::parse("pane x=y").unwrap()]));
221
222        assert!(!keymap.binding_enabled(&bindings[2], &[KeyContext::parse("editor").unwrap()]));
223        assert!(keymap.binding_enabled(
224            &bindings[2],
225            &[KeyContext::parse("editor mode=full").unwrap()]
226        ));
227    }
228
229    #[test]
230    fn test_keymap_disabled() {
231        let bindings = [
232            KeyBinding::new("ctrl-a", ActionAlpha {}, Some("editor")),
233            KeyBinding::new("ctrl-b", ActionAlpha {}, Some("editor")),
234            KeyBinding::new("ctrl-a", NoAction {}, Some("editor && mode==full")),
235            KeyBinding::new("ctrl-b", NoAction {}, None),
236        ];
237
238        let mut keymap = Keymap::default();
239        keymap.add_bindings(bindings.clone());
240
241        // binding is only enabled in a specific context
242        assert!(keymap
243            .bindings_for_input(
244                &[Keystroke::parse("ctrl-a").unwrap()],
245                &[KeyContext::parse("barf").unwrap()],
246            )
247            .0
248            .is_empty());
249        assert!(!keymap
250            .bindings_for_input(
251                &[Keystroke::parse("ctrl-a").unwrap()],
252                &[KeyContext::parse("editor").unwrap()],
253            )
254            .0
255            .is_empty());
256
257        // binding is disabled in a more specific context
258        assert!(keymap
259            .bindings_for_input(
260                &[Keystroke::parse("ctrl-a").unwrap()],
261                &[KeyContext::parse("editor mode=full").unwrap()],
262            )
263            .0
264            .is_empty());
265
266        // binding is globally disabled
267        assert!(keymap
268            .bindings_for_input(
269                &[Keystroke::parse("ctrl-b").unwrap()],
270                &[KeyContext::parse("barf").unwrap()],
271            )
272            .0
273            .is_empty());
274    }
275
276    #[test]
277    fn test_bindings_for_action() {
278        let bindings = [
279            KeyBinding::new("ctrl-a", ActionAlpha {}, Some("pane")),
280            KeyBinding::new("ctrl-b", ActionBeta {}, Some("editor && mode == full")),
281            KeyBinding::new("ctrl-c", ActionGamma {}, Some("workspace")),
282            KeyBinding::new("ctrl-a", NoAction {}, Some("pane && active")),
283            KeyBinding::new("ctrl-b", NoAction {}, Some("editor")),
284        ];
285
286        let mut keymap = Keymap::default();
287        keymap.add_bindings(bindings.clone());
288
289        assert_bindings(&keymap, &ActionAlpha {}, &["ctrl-a"]);
290        assert_bindings(&keymap, &ActionBeta {}, &[]);
291        assert_bindings(&keymap, &ActionGamma {}, &["ctrl-c"]);
292
293        #[track_caller]
294        fn assert_bindings(keymap: &Keymap, action: &dyn Action, expected: &[&str]) {
295            let actual = keymap
296                .bindings_for_action(action)
297                .map(|binding| binding.keystrokes[0].unparse())
298                .collect::<Vec<_>>();
299            assert_eq!(actual, expected, "{:?}", action);
300        }
301    }
302}