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    /// WARN: Assumes the bindings are in the order they were added to the keymap
193    /// returns the last binding for the given bindings, which
194    /// should be the user's binding in their keymap.json if they've set one,
195    /// otherwise, the last declared binding for this action in the base keymaps
196    /// (with Vim mode bindings being considered as declared later if Vim mode
197    /// is enabled)
198    ///
199    /// If you are considering changing the behavior of this function
200    /// (especially to fix a user reported issue) see issues #23621, #24931,
201    /// and possibly others as evidence that it has swapped back and forth a
202    /// couple times. The decision as of now is to pick a side and leave it
203    /// as is, until we have a better way to decide which binding to display
204    /// that is consistent and not confusing.
205    pub fn binding_to_display_from_bindings<'a>(
206        bindings: impl IntoIterator<Item = &'a KeyBinding>,
207    ) -> Option<&'a KeyBinding> {
208        return bindings.into_iter().last();
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215    use crate as gpui;
216    use gpui::{actions, NoAction};
217
218    actions!(
219        keymap_test,
220        [ActionAlpha, ActionBeta, ActionGamma, ActionDelta,]
221    );
222
223    #[test]
224    fn test_keymap() {
225        let bindings = [
226            KeyBinding::new("ctrl-a", ActionAlpha {}, None),
227            KeyBinding::new("ctrl-a", ActionBeta {}, Some("pane")),
228            KeyBinding::new("ctrl-a", ActionGamma {}, Some("editor && mode==full")),
229        ];
230
231        let mut keymap = Keymap::default();
232        keymap.add_bindings(bindings.clone());
233
234        // global bindings are enabled in all contexts
235        assert!(keymap.binding_enabled(&bindings[0], &[]));
236        assert!(keymap.binding_enabled(&bindings[0], &[KeyContext::parse("terminal").unwrap()]));
237
238        // contextual bindings are enabled in contexts that match their predicate
239        assert!(!keymap.binding_enabled(&bindings[1], &[KeyContext::parse("barf x=y").unwrap()]));
240        assert!(keymap.binding_enabled(&bindings[1], &[KeyContext::parse("pane x=y").unwrap()]));
241
242        assert!(!keymap.binding_enabled(&bindings[2], &[KeyContext::parse("editor").unwrap()]));
243        assert!(keymap.binding_enabled(
244            &bindings[2],
245            &[KeyContext::parse("editor mode=full").unwrap()]
246        ));
247    }
248
249    #[test]
250    fn test_keymap_disabled() {
251        let bindings = [
252            KeyBinding::new("ctrl-a", ActionAlpha {}, Some("editor")),
253            KeyBinding::new("ctrl-b", ActionAlpha {}, Some("editor")),
254            KeyBinding::new("ctrl-a", NoAction {}, Some("editor && mode==full")),
255            KeyBinding::new("ctrl-b", NoAction {}, None),
256        ];
257
258        let mut keymap = Keymap::default();
259        keymap.add_bindings(bindings.clone());
260
261        // binding is only enabled in a specific context
262        assert!(keymap
263            .bindings_for_input(
264                &[Keystroke::parse("ctrl-a").unwrap()],
265                &[KeyContext::parse("barf").unwrap()],
266            )
267            .0
268            .is_empty());
269        assert!(!keymap
270            .bindings_for_input(
271                &[Keystroke::parse("ctrl-a").unwrap()],
272                &[KeyContext::parse("editor").unwrap()],
273            )
274            .0
275            .is_empty());
276
277        // binding is disabled in a more specific context
278        assert!(keymap
279            .bindings_for_input(
280                &[Keystroke::parse("ctrl-a").unwrap()],
281                &[KeyContext::parse("editor mode=full").unwrap()],
282            )
283            .0
284            .is_empty());
285
286        // binding is globally disabled
287        assert!(keymap
288            .bindings_for_input(
289                &[Keystroke::parse("ctrl-b").unwrap()],
290                &[KeyContext::parse("barf").unwrap()],
291            )
292            .0
293            .is_empty());
294    }
295
296    #[test]
297    fn test_bindings_for_action() {
298        let bindings = [
299            KeyBinding::new("ctrl-a", ActionAlpha {}, Some("pane")),
300            KeyBinding::new("ctrl-b", ActionBeta {}, Some("editor && mode == full")),
301            KeyBinding::new("ctrl-c", ActionGamma {}, Some("workspace")),
302            KeyBinding::new("ctrl-a", NoAction {}, Some("pane && active")),
303            KeyBinding::new("ctrl-b", NoAction {}, Some("editor")),
304        ];
305
306        let mut keymap = Keymap::default();
307        keymap.add_bindings(bindings.clone());
308
309        assert_bindings(&keymap, &ActionAlpha {}, &["ctrl-a"]);
310        assert_bindings(&keymap, &ActionBeta {}, &[]);
311        assert_bindings(&keymap, &ActionGamma {}, &["ctrl-c"]);
312
313        #[track_caller]
314        fn assert_bindings(keymap: &Keymap, action: &dyn Action, expected: &[&str]) {
315            let actual = keymap
316                .bindings_for_action(action)
317                .map(|binding| binding.keystrokes[0].unparse())
318                .collect::<Vec<_>>();
319            assert_eq!(actual, expected, "{:?}", action);
320        }
321    }
322}