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. For display,
 71    /// the last binding should take precedence.
 72    pub fn bindings_for_action<'a>(
 73        &'a self,
 74        action: &'a dyn Action,
 75    ) -> impl 'a + DoubleEndedIterator<Item = &'a KeyBinding> {
 76        let action_id = action.type_id();
 77        let binding_indices = self
 78            .binding_indices_by_action_id
 79            .get(&action_id)
 80            .map_or(&[] as _, SmallVec::as_slice)
 81            .iter();
 82
 83        binding_indices.filter_map(|ix| {
 84            let binding = &self.bindings[*ix];
 85            if !binding.action().partial_eq(action) {
 86                return None;
 87            }
 88
 89            for null_ix in &self.no_action_binding_indices {
 90                if null_ix > ix {
 91                    let null_binding = &self.bindings[*null_ix];
 92                    if null_binding.keystrokes == binding.keystrokes {
 93                        let null_binding_matches =
 94                            match (&null_binding.context_predicate, &binding.context_predicate) {
 95                                (None, _) => true,
 96                                (Some(_), None) => false,
 97                                (Some(null_predicate), Some(predicate)) => {
 98                                    null_predicate.is_superset(predicate)
 99                                }
100                            };
101                        if null_binding_matches {
102                            return None;
103                        }
104                    }
105                }
106            }
107
108            Some(binding)
109        })
110    }
111
112    /// Returns all bindings that might match the input without checking context. The bindings
113    /// returned in precedence order (reverse of the order they were added to the keymap).
114    pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
115        self.bindings()
116            .rev()
117            .filter_map(|binding| {
118                binding.match_keystrokes(input).filter(|pending| !pending)?;
119                Some(binding.clone())
120            })
121            .collect()
122    }
123
124    /// Returns a list of bindings that match the given input, and a boolean indicating whether or
125    /// not more bindings might match if the input was longer. Bindings are returned in precedence
126    /// order.
127    ///
128    /// Precedence is defined by the depth in the tree (matches on the Editor take precedence over
129    /// matches on the Pane, then the Workspace, etc.). Bindings with no context are treated as the
130    /// same as the deepest context.
131    ///
132    /// In the case of multiple bindings at the same depth, the ones added to the keymap later take
133    /// precedence. User bindings are added after built-in bindings so that they take precedence.
134    ///
135    /// If a user has disabled a binding with `"x": null` it will not be returned. Disabled bindings
136    /// are evaluated with the same precedence rules so you can disable a rule in a given context
137    /// only.
138    pub fn bindings_for_input(
139        &self,
140        input: &[Keystroke],
141        context_stack: &[KeyContext],
142    ) -> (SmallVec<[KeyBinding; 1]>, bool) {
143        let possibilities = self.bindings().rev().filter_map(|binding| {
144            binding
145                .match_keystrokes(input)
146                .map(|pending| (binding, pending))
147        });
148
149        let mut bindings: SmallVec<[(KeyBinding, usize); 1]> = SmallVec::new();
150        let mut is_pending = None;
151
152        'outer: for (binding, pending) in possibilities {
153            for depth in (0..=context_stack.len()).rev() {
154                if self.binding_enabled(binding, &context_stack[0..depth]) {
155                    if is_pending.is_none() {
156                        is_pending = Some(pending);
157                    }
158                    if !pending {
159                        bindings.push((binding.clone(), depth));
160                        continue 'outer;
161                    }
162                }
163            }
164        }
165        bindings.sort_by(|a, b| a.1.cmp(&b.1).reverse());
166        let bindings = bindings
167            .into_iter()
168            .map_while(|(binding, _)| {
169                if is_no_action(&*binding.action) {
170                    None
171                } else {
172                    Some(binding)
173                }
174            })
175            .collect();
176
177        (bindings, is_pending.unwrap_or_default())
178    }
179
180    /// Check if the given binding is enabled, given a certain key context.
181    fn binding_enabled(&self, binding: &KeyBinding, context: &[KeyContext]) -> bool {
182        // If binding has a context predicate, it must match the current context,
183        if let Some(predicate) = &binding.context_predicate {
184            if !predicate.eval(context) {
185                return false;
186            }
187        }
188
189        true
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196    use crate as gpui;
197    use gpui::{actions, NoAction};
198
199    actions!(
200        keymap_test,
201        [ActionAlpha, ActionBeta, ActionGamma, ActionDelta,]
202    );
203
204    #[test]
205    fn test_keymap() {
206        let bindings = [
207            KeyBinding::new("ctrl-a", ActionAlpha {}, None),
208            KeyBinding::new("ctrl-a", ActionBeta {}, Some("pane")),
209            KeyBinding::new("ctrl-a", ActionGamma {}, Some("editor && mode==full")),
210        ];
211
212        let mut keymap = Keymap::default();
213        keymap.add_bindings(bindings.clone());
214
215        // global bindings are enabled in all contexts
216        assert!(keymap.binding_enabled(&bindings[0], &[]));
217        assert!(keymap.binding_enabled(&bindings[0], &[KeyContext::parse("terminal").unwrap()]));
218
219        // contextual bindings are enabled in contexts that match their predicate
220        assert!(!keymap.binding_enabled(&bindings[1], &[KeyContext::parse("barf x=y").unwrap()]));
221        assert!(keymap.binding_enabled(&bindings[1], &[KeyContext::parse("pane x=y").unwrap()]));
222
223        assert!(!keymap.binding_enabled(&bindings[2], &[KeyContext::parse("editor").unwrap()]));
224        assert!(keymap.binding_enabled(
225            &bindings[2],
226            &[KeyContext::parse("editor mode=full").unwrap()]
227        ));
228    }
229
230    #[test]
231    fn test_keymap_disabled() {
232        let bindings = [
233            KeyBinding::new("ctrl-a", ActionAlpha {}, Some("editor")),
234            KeyBinding::new("ctrl-b", ActionAlpha {}, Some("editor")),
235            KeyBinding::new("ctrl-a", NoAction {}, Some("editor && mode==full")),
236            KeyBinding::new("ctrl-b", NoAction {}, None),
237        ];
238
239        let mut keymap = Keymap::default();
240        keymap.add_bindings(bindings.clone());
241
242        // binding is only enabled in a specific context
243        assert!(keymap
244            .bindings_for_input(
245                &[Keystroke::parse("ctrl-a").unwrap()],
246                &[KeyContext::parse("barf").unwrap()],
247            )
248            .0
249            .is_empty());
250        assert!(!keymap
251            .bindings_for_input(
252                &[Keystroke::parse("ctrl-a").unwrap()],
253                &[KeyContext::parse("editor").unwrap()],
254            )
255            .0
256            .is_empty());
257
258        // binding is disabled in a more specific context
259        assert!(keymap
260            .bindings_for_input(
261                &[Keystroke::parse("ctrl-a").unwrap()],
262                &[KeyContext::parse("editor mode=full").unwrap()],
263            )
264            .0
265            .is_empty());
266
267        // binding is globally disabled
268        assert!(keymap
269            .bindings_for_input(
270                &[Keystroke::parse("ctrl-b").unwrap()],
271                &[KeyContext::parse("barf").unwrap()],
272            )
273            .0
274            .is_empty());
275    }
276
277    #[test]
278    fn test_bindings_for_action() {
279        let bindings = [
280            KeyBinding::new("ctrl-a", ActionAlpha {}, Some("pane")),
281            KeyBinding::new("ctrl-b", ActionBeta {}, Some("editor && mode == full")),
282            KeyBinding::new("ctrl-c", ActionGamma {}, Some("workspace")),
283            KeyBinding::new("ctrl-a", NoAction {}, Some("pane && active")),
284            KeyBinding::new("ctrl-b", NoAction {}, Some("editor")),
285        ];
286
287        let mut keymap = Keymap::default();
288        keymap.add_bindings(bindings.clone());
289
290        assert_bindings(&keymap, &ActionAlpha {}, &["ctrl-a"]);
291        assert_bindings(&keymap, &ActionBeta {}, &[]);
292        assert_bindings(&keymap, &ActionGamma {}, &["ctrl-c"]);
293
294        #[track_caller]
295        fn assert_bindings(keymap: &Keymap, action: &dyn Action, expected: &[&str]) {
296            let actual = keymap
297                .bindings_for_action(action)
298                .map(|binding| binding.keystrokes[0].unparse())
299                .collect::<Vec<_>>();
300            assert_eq!(actual, expected, "{:?}", action);
301        }
302    }
303}