keymap.rs

  1mod binding;
  2mod context;
  3
  4pub use binding::*;
  5pub use context::*;
  6
  7use crate::{Action, Keystroke, is_no_action};
  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
 26/// Index of a binding within a keymap.
 27#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
 28pub struct BindingIndex(usize);
 29
 30impl Keymap {
 31    /// Create a new keymap with the given bindings.
 32    pub fn new(bindings: Vec<KeyBinding>) -> Self {
 33        let mut this = Self::default();
 34        this.add_bindings(bindings);
 35        this
 36    }
 37
 38    /// Get the current version of the keymap.
 39    pub fn version(&self) -> KeymapVersion {
 40        self.version
 41    }
 42
 43    /// Add more bindings to the keymap.
 44    pub fn add_bindings<T: IntoIterator<Item = KeyBinding>>(&mut self, bindings: T) {
 45        for binding in bindings {
 46            let action_id = binding.action().as_any().type_id();
 47            if is_no_action(&*binding.action) {
 48                self.no_action_binding_indices.push(self.bindings.len());
 49            } else {
 50                self.binding_indices_by_action_id
 51                    .entry(action_id)
 52                    .or_default()
 53                    .push(self.bindings.len());
 54            }
 55            self.bindings.push(binding);
 56        }
 57
 58        self.version.0 += 1;
 59    }
 60
 61    /// Reset this keymap to its initial state.
 62    pub fn clear(&mut self) {
 63        self.bindings.clear();
 64        self.binding_indices_by_action_id.clear();
 65        self.no_action_binding_indices.clear();
 66        self.version.0 += 1;
 67    }
 68
 69    /// Iterate over all bindings, in the order they were added.
 70    pub fn bindings(&self) -> impl DoubleEndedIterator<Item = &KeyBinding> + ExactSizeIterator {
 71        self.bindings.iter()
 72    }
 73
 74    /// Iterate over all bindings for the given action, in the order they were added. For display,
 75    /// the last binding should take precedence.
 76    pub fn bindings_for_action<'a>(
 77        &'a self,
 78        action: &'a dyn Action,
 79    ) -> impl 'a + DoubleEndedIterator<Item = &'a KeyBinding> {
 80        self.bindings_for_action_with_indices(action)
 81            .map(|(_, binding)| binding)
 82    }
 83
 84    /// Like `bindings_for_action_with_indices`, but also returns the binding indices.
 85    pub fn bindings_for_action_with_indices<'a>(
 86        &'a self,
 87        action: &'a dyn Action,
 88    ) -> impl 'a + DoubleEndedIterator<Item = (BindingIndex, &'a KeyBinding)> {
 89        let action_id = action.type_id();
 90        let binding_indices = self
 91            .binding_indices_by_action_id
 92            .get(&action_id)
 93            .map_or(&[] as _, SmallVec::as_slice)
 94            .iter();
 95
 96        binding_indices.filter_map(|ix| {
 97            let binding = &self.bindings[*ix];
 98            if !binding.action().partial_eq(action) {
 99                return None;
100            }
101
102            for null_ix in &self.no_action_binding_indices {
103                if null_ix > ix {
104                    let null_binding = &self.bindings[*null_ix];
105                    if null_binding.keystrokes == binding.keystrokes {
106                        let null_binding_matches =
107                            match (&null_binding.context_predicate, &binding.context_predicate) {
108                                (None, _) => true,
109                                (Some(_), None) => false,
110                                (Some(null_predicate), Some(predicate)) => {
111                                    null_predicate.is_superset(predicate)
112                                }
113                            };
114                        if null_binding_matches {
115                            return None;
116                        }
117                    }
118                }
119            }
120
121            Some((BindingIndex(*ix), binding))
122        })
123    }
124
125    /// Returns all bindings that might match the input without checking context. The bindings
126    /// returned in precedence order (reverse of the order they were added to the keymap).
127    pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
128        self.bindings()
129            .rev()
130            .filter_map(|binding| {
131                binding.match_keystrokes(input).filter(|pending| !pending)?;
132                Some(binding.clone())
133            })
134            .collect()
135    }
136
137    /// Returns a list of bindings that match the given input, and a boolean indicating whether or
138    /// not more bindings might match if the input was longer. Bindings are returned in precedence
139    /// order (higher precedence first, reverse of the order they were added to the keymap).
140    ///
141    /// Precedence is defined by the depth in the tree (matches on the Editor take precedence over
142    /// matches on the Pane, then the Workspace, etc.). Bindings with no context are treated as the
143    /// same as the deepest context.
144    ///
145    /// In the case of multiple bindings at the same depth, the ones added to the keymap later take
146    /// precedence. User bindings are added after built-in bindings so that they take precedence.
147    ///
148    /// If a user has disabled a binding with `"x": null` it will not be returned. Disabled bindings
149    /// are evaluated with the same precedence rules so you can disable a rule in a given context
150    /// only.
151    pub fn bindings_for_input(
152        &self,
153        input: &[Keystroke],
154        context_stack: &[KeyContext],
155    ) -> (SmallVec<[KeyBinding; 1]>, bool) {
156        let (bindings, pending) = self.bindings_for_input_with_indices(input, context_stack);
157        let bindings = bindings
158            .into_iter()
159            .map(|(_, binding)| binding)
160            .collect::<SmallVec<[KeyBinding; 1]>>();
161        (bindings, pending)
162    }
163
164    /// Like `bindings_for_input`, but also returns the binding indices.
165    pub fn bindings_for_input_with_indices(
166        &self,
167        input: &[Keystroke],
168        context_stack: &[KeyContext],
169    ) -> (SmallVec<[(BindingIndex, KeyBinding); 1]>, bool) {
170        let mut possibilities = self
171            .bindings()
172            .enumerate()
173            .rev()
174            .filter_map(|(ix, binding)| {
175                let depth = self.binding_enabled(binding, &context_stack)?;
176                let pending = binding.match_keystrokes(input)?;
177                Some((depth, BindingIndex(ix), binding, pending))
178            })
179            .collect::<Vec<_>>();
180        possibilities.sort_by(|(depth_a, ix_a, _, _), (depth_b, ix_b, _, _)| {
181            depth_b.cmp(depth_a).then(ix_b.cmp(ix_a))
182        });
183
184        let mut bindings: SmallVec<[(BindingIndex, KeyBinding, usize); 1]> = SmallVec::new();
185
186        // (pending, is_no_action, depth, keystrokes)
187        let mut pending_info_opt: Option<(bool, bool, usize, &[Keystroke])> = None;
188
189        'outer: for (depth, binding_index, binding, pending) in possibilities {
190            let is_no_action = is_no_action(&*binding.action);
191            // We only want to consider a binding pending if it has an action
192            // This, however, means that if we have both a NoAction binding and a binding
193            // with an action at the same depth, we should still set is_pending to true.
194            if let Some(pending_info) = pending_info_opt.as_mut() {
195                let (already_pending, pending_is_no_action, pending_depth, pending_keystrokes) =
196                    *pending_info;
197
198                // We only want to change the pending status if it's not already pending AND if
199                // the existing pending status was set by a NoAction binding. This avoids a NoAction
200                // binding erroneously setting the pending status to true when a binding with an action
201                // already set it to false
202                //
203                // We also want to change the pending status if the keystrokes don't match,
204                // meaning it's different keystrokes than the NoAction that set pending to false
205                if pending
206                    && !already_pending
207                    && pending_is_no_action
208                    && (pending_depth == depth || pending_keystrokes != binding.keystrokes())
209                {
210                    pending_info.0 = !is_no_action;
211                }
212            } else {
213                pending_info_opt = Some((
214                    pending && !is_no_action,
215                    is_no_action,
216                    depth,
217                    binding.keystrokes(),
218                ));
219            }
220
221            if !pending {
222                bindings.push((binding_index, binding.clone(), depth));
223                continue 'outer;
224            }
225        }
226        // sort by descending depth
227        bindings.sort_by(|a, b| a.2.cmp(&b.2).reverse());
228        let bindings = bindings
229            .into_iter()
230            .map_while(|(binding_index, binding, _)| {
231                if is_no_action(&*binding.action) {
232                    None
233                } else {
234                    Some((binding_index, binding))
235                }
236            })
237            .collect();
238
239        (bindings, pending_info_opt.unwrap_or_default().0)
240    }
241
242    /// Check if the given binding is enabled, given a certain key context.
243    /// Returns the deepest depth at which the binding matches, or None if it doesn't match.
244    fn binding_enabled(&self, binding: &KeyBinding, contexts: &[KeyContext]) -> Option<usize> {
245        if let Some(predicate) = &binding.context_predicate {
246            predicate.depth_of(contexts)
247        } else {
248            Some(contexts.len())
249        }
250    }
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256    use crate as gpui;
257    use gpui::NoAction;
258
259    actions!(
260        test_only,
261        [ActionAlpha, ActionBeta, ActionGamma, ActionDelta,]
262    );
263
264    #[test]
265    fn test_keymap() {
266        let bindings = [
267            KeyBinding::new("ctrl-a", ActionAlpha {}, None),
268            KeyBinding::new("ctrl-a", ActionBeta {}, Some("pane")),
269            KeyBinding::new("ctrl-a", ActionGamma {}, Some("editor && mode==full")),
270        ];
271
272        let mut keymap = Keymap::default();
273        keymap.add_bindings(bindings.clone());
274
275        // global bindings are enabled in all contexts
276        assert_eq!(keymap.binding_enabled(&bindings[0], &[]), Some(0));
277        assert_eq!(
278            keymap.binding_enabled(&bindings[0], &[KeyContext::parse("terminal").unwrap()]),
279            Some(1)
280        );
281
282        // contextual bindings are enabled in contexts that match their predicate
283        assert_eq!(
284            keymap.binding_enabled(&bindings[1], &[KeyContext::parse("barf x=y").unwrap()]),
285            None
286        );
287        assert_eq!(
288            keymap.binding_enabled(&bindings[1], &[KeyContext::parse("pane x=y").unwrap()]),
289            Some(1)
290        );
291
292        assert_eq!(
293            keymap.binding_enabled(&bindings[2], &[KeyContext::parse("editor").unwrap()]),
294            None
295        );
296        assert_eq!(
297            keymap.binding_enabled(
298                &bindings[2],
299                &[KeyContext::parse("editor mode=full").unwrap()]
300            ),
301            Some(1)
302        );
303    }
304
305    #[test]
306    fn test_keymap_disabled() {
307        let bindings = [
308            KeyBinding::new("ctrl-a", ActionAlpha {}, Some("editor")),
309            KeyBinding::new("ctrl-b", ActionAlpha {}, Some("editor")),
310            KeyBinding::new("ctrl-a", NoAction {}, Some("editor && mode==full")),
311            KeyBinding::new("ctrl-b", NoAction {}, None),
312        ];
313
314        let mut keymap = Keymap::default();
315        keymap.add_bindings(bindings.clone());
316
317        // binding is only enabled in a specific context
318        assert!(
319            keymap
320                .bindings_for_input(
321                    &[Keystroke::parse("ctrl-a").unwrap()],
322                    &[KeyContext::parse("barf").unwrap()],
323                )
324                .0
325                .is_empty()
326        );
327        assert!(
328            !keymap
329                .bindings_for_input(
330                    &[Keystroke::parse("ctrl-a").unwrap()],
331                    &[KeyContext::parse("editor").unwrap()],
332                )
333                .0
334                .is_empty()
335        );
336
337        // binding is disabled in a more specific context
338        assert!(
339            keymap
340                .bindings_for_input(
341                    &[Keystroke::parse("ctrl-a").unwrap()],
342                    &[KeyContext::parse("editor mode=full").unwrap()],
343                )
344                .0
345                .is_empty()
346        );
347
348        // binding is globally disabled
349        assert!(
350            keymap
351                .bindings_for_input(
352                    &[Keystroke::parse("ctrl-b").unwrap()],
353                    &[KeyContext::parse("barf").unwrap()],
354                )
355                .0
356                .is_empty()
357        );
358    }
359
360    #[test]
361    /// Tests for https://github.com/zed-industries/zed/issues/30259
362    fn test_multiple_keystroke_binding_disabled() {
363        let bindings = [
364            KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
365            KeyBinding::new("space w w", NoAction {}, Some("editor")),
366        ];
367
368        let mut keymap = Keymap::default();
369        keymap.add_bindings(bindings.clone());
370
371        let space = || Keystroke::parse("space").unwrap();
372        let w = || Keystroke::parse("w").unwrap();
373
374        let space_w = [space(), w()];
375        let space_w_w = [space(), w(), w()];
376
377        let workspace_context = || [KeyContext::parse("workspace").unwrap()];
378
379        let editor_workspace_context = || {
380            [
381                KeyContext::parse("workspace").unwrap(),
382                KeyContext::parse("editor").unwrap(),
383            ]
384        };
385
386        // Ensure `space` results in pending input on the workspace, but not editor
387        let space_workspace = keymap.bindings_for_input(&[space()], &workspace_context());
388        assert!(space_workspace.0.is_empty());
389        assert_eq!(space_workspace.1, true);
390
391        let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
392        assert!(space_editor.0.is_empty());
393        assert_eq!(space_editor.1, false);
394
395        // Ensure `space w` results in pending input on the workspace, but not editor
396        let space_w_workspace = keymap.bindings_for_input(&space_w, &workspace_context());
397        assert!(space_w_workspace.0.is_empty());
398        assert_eq!(space_w_workspace.1, true);
399
400        let space_w_editor = keymap.bindings_for_input(&space_w, &editor_workspace_context());
401        assert!(space_w_editor.0.is_empty());
402        assert_eq!(space_w_editor.1, false);
403
404        // Ensure `space w w` results in the binding in the workspace, but not in the editor
405        let space_w_w_workspace = keymap.bindings_for_input(&space_w_w, &workspace_context());
406        assert!(!space_w_w_workspace.0.is_empty());
407        assert_eq!(space_w_w_workspace.1, false);
408
409        let space_w_w_editor = keymap.bindings_for_input(&space_w_w, &editor_workspace_context());
410        assert!(space_w_w_editor.0.is_empty());
411        assert_eq!(space_w_w_editor.1, false);
412
413        // Now test what happens if we have another binding defined AFTER the NoAction
414        // that should result in pending
415        let bindings = [
416            KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
417            KeyBinding::new("space w w", NoAction {}, Some("editor")),
418            KeyBinding::new("space w x", ActionAlpha {}, Some("editor")),
419        ];
420        let mut keymap = Keymap::default();
421        keymap.add_bindings(bindings.clone());
422
423        let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
424        assert!(space_editor.0.is_empty());
425        assert_eq!(space_editor.1, true);
426
427        // Now test what happens if we have another binding defined BEFORE the NoAction
428        // that should result in pending
429        let bindings = [
430            KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
431            KeyBinding::new("space w x", ActionAlpha {}, Some("editor")),
432            KeyBinding::new("space w w", NoAction {}, Some("editor")),
433        ];
434        let mut keymap = Keymap::default();
435        keymap.add_bindings(bindings.clone());
436
437        let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
438        assert!(space_editor.0.is_empty());
439        assert_eq!(space_editor.1, true);
440
441        // Now test what happens if we have another binding defined at a higher context
442        // that should result in pending
443        let bindings = [
444            KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
445            KeyBinding::new("space w x", ActionAlpha {}, Some("workspace")),
446            KeyBinding::new("space w w", NoAction {}, Some("editor")),
447        ];
448        let mut keymap = Keymap::default();
449        keymap.add_bindings(bindings.clone());
450
451        let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
452        assert!(space_editor.0.is_empty());
453        assert_eq!(space_editor.1, true);
454    }
455
456    #[test]
457    fn test_bindings_for_action() {
458        let bindings = [
459            KeyBinding::new("ctrl-a", ActionAlpha {}, Some("pane")),
460            KeyBinding::new("ctrl-b", ActionBeta {}, Some("editor && mode == full")),
461            KeyBinding::new("ctrl-c", ActionGamma {}, Some("workspace")),
462            KeyBinding::new("ctrl-a", NoAction {}, Some("pane && active")),
463            KeyBinding::new("ctrl-b", NoAction {}, Some("editor")),
464        ];
465
466        let mut keymap = Keymap::default();
467        keymap.add_bindings(bindings.clone());
468
469        assert_bindings(&keymap, &ActionAlpha {}, &["ctrl-a"]);
470        assert_bindings(&keymap, &ActionBeta {}, &[]);
471        assert_bindings(&keymap, &ActionGamma {}, &["ctrl-c"]);
472
473        #[track_caller]
474        fn assert_bindings(keymap: &Keymap, action: &dyn Action, expected: &[&str]) {
475            let actual = keymap
476                .bindings_for_action(action)
477                .map(|binding| binding.keystrokes[0].unparse())
478                .collect::<Vec<_>>();
479            assert_eq!(actual, expected, "{:?}", action);
480        }
481    }
482}