1mod binding;
2mod context;
3
4pub use binding::*;
5pub use context::*;
6
7use crate::{Action, Keystroke, NoAction};
8use collections::HashMap;
9use smallvec::SmallVec;
10use std::any::{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 version: KeymapVersion,
23}
24
25impl Keymap {
26 /// Create a new keymap with the given bindings.
27 pub fn new(bindings: Vec<KeyBinding>) -> Self {
28 let mut this = Self::default();
29 this.add_bindings(bindings);
30 this
31 }
32
33 /// Get the current version of the keymap.
34 pub fn version(&self) -> KeymapVersion {
35 self.version
36 }
37
38 /// Add more bindings to the keymap.
39 pub fn add_bindings<T: IntoIterator<Item = KeyBinding>>(&mut self, bindings: T) {
40 for binding in bindings {
41 let action_id = binding.action().as_any().type_id();
42 self.binding_indices_by_action_id
43 .entry(action_id)
44 .or_default()
45 .push(self.bindings.len());
46 self.bindings.push(binding);
47 }
48
49 self.version.0 += 1;
50 }
51
52 /// Reset this keymap to its initial state.
53 pub fn clear(&mut self) {
54 self.bindings.clear();
55 self.binding_indices_by_action_id.clear();
56 self.version.0 += 1;
57 }
58
59 /// Iterate over all bindings, in the order they were added.
60 pub fn bindings(&self) -> impl DoubleEndedIterator<Item = &KeyBinding> {
61 self.bindings.iter()
62 }
63
64 /// Iterate over all bindings for the given action, in the order they were added.
65 pub fn bindings_for_action<'a>(
66 &'a self,
67 action: &'a dyn Action,
68 ) -> impl 'a + DoubleEndedIterator<Item = &'a KeyBinding> {
69 let action_id = action.type_id();
70 self.binding_indices_by_action_id
71 .get(&action_id)
72 .map_or(&[] as _, SmallVec::as_slice)
73 .iter()
74 .map(|ix| &self.bindings[*ix])
75 .filter(move |binding| binding.action().partial_eq(action))
76 }
77
78 /// bindings_for_input returns a list of bindings that match the given input,
79 /// and a boolean indicating whether or not more bindings might match if
80 /// the input was longer.
81 ///
82 /// Precedence is defined by the depth in the tree (matches on the Editor take
83 /// precedence over matches on the Pane, then the Workspace, etc.). Bindings with
84 /// no context are treated as the same as the deepest context.
85 ///
86 /// In the case of multiple bindings at the same depth, the ones defined later in the
87 /// keymap take precedence (so user bindings take precedence over built-in bindings).
88 ///
89 /// If a user has disabled a binding with `"x": null` it will not be returned. Disabled
90 /// bindings are evaluated with the same precedence rules so you can disable a rule in
91 /// a given context only.
92 ///
93 /// In the case of multi-key bindings, the
94 pub fn bindings_for_input(
95 &self,
96 input: &[Keystroke],
97 context_stack: &[KeyContext],
98 ) -> (SmallVec<[KeyBinding; 1]>, bool) {
99 let possibilities = self.bindings().rev().filter_map(|binding| {
100 binding
101 .match_keystrokes(input)
102 .map(|pending| (binding, pending))
103 });
104
105 let mut bindings: SmallVec<[(KeyBinding, usize); 1]> = SmallVec::new();
106 let mut is_pending = None;
107
108 'outer: for (binding, pending) in possibilities {
109 for depth in (0..=context_stack.len()).rev() {
110 if self.binding_enabled(binding, &context_stack[0..depth]) {
111 if is_pending.is_none() {
112 is_pending = Some(pending);
113 }
114 if !pending {
115 bindings.push((binding.clone(), depth));
116 continue 'outer;
117 }
118 }
119 }
120 }
121 bindings.sort_by(|a, b| a.1.cmp(&b.1).reverse());
122 let bindings = bindings
123 .into_iter()
124 .map_while(|(binding, _)| {
125 if binding.action.as_any().type_id() == (NoAction {}).type_id() {
126 None
127 } else {
128 Some(binding)
129 }
130 })
131 .collect();
132
133 (bindings, is_pending.unwrap_or_default())
134 }
135
136 /// Check if the given binding is enabled, given a certain key context.
137 fn binding_enabled(&self, binding: &KeyBinding, context: &[KeyContext]) -> bool {
138 // If binding has a context predicate, it must match the current context,
139 if let Some(predicate) = &binding.context_predicate {
140 if !predicate.eval(context) {
141 return false;
142 }
143 }
144
145 true
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152 use crate as gpui;
153 use gpui::actions;
154
155 actions!(
156 keymap_test,
157 [ActionAlpha, ActionBeta, ActionGamma, ActionDelta,]
158 );
159
160 #[test]
161 fn test_keymap() {
162 let bindings = [
163 KeyBinding::new("ctrl-a", ActionAlpha {}, None),
164 KeyBinding::new("ctrl-a", ActionBeta {}, Some("pane")),
165 KeyBinding::new("ctrl-a", ActionGamma {}, Some("editor && mode==full")),
166 ];
167
168 let mut keymap = Keymap::default();
169 keymap.add_bindings(bindings.clone());
170
171 // global bindings are enabled in all contexts
172 assert!(keymap.binding_enabled(&bindings[0], &[]));
173 assert!(keymap.binding_enabled(&bindings[0], &[KeyContext::parse("terminal").unwrap()]));
174
175 // contextual bindings are enabled in contexts that match their predicate
176 assert!(!keymap.binding_enabled(&bindings[1], &[KeyContext::parse("barf x=y").unwrap()]));
177 assert!(keymap.binding_enabled(&bindings[1], &[KeyContext::parse("pane x=y").unwrap()]));
178
179 assert!(!keymap.binding_enabled(&bindings[2], &[KeyContext::parse("editor").unwrap()]));
180 assert!(keymap.binding_enabled(
181 &bindings[2],
182 &[KeyContext::parse("editor mode=full").unwrap()]
183 ));
184 }
185
186 #[test]
187 fn test_keymap_disabled() {
188 let bindings = [
189 KeyBinding::new("ctrl-a", ActionAlpha {}, Some("editor")),
190 KeyBinding::new("ctrl-b", ActionAlpha {}, Some("editor")),
191 KeyBinding::new("ctrl-a", NoAction {}, Some("editor && mode==full")),
192 KeyBinding::new("ctrl-b", NoAction {}, None),
193 ];
194
195 let mut keymap = Keymap::default();
196 keymap.add_bindings(bindings.clone());
197
198 // binding is only enabled in a specific context
199 assert!(keymap
200 .bindings_for_input(
201 &[Keystroke::parse("ctrl-a").unwrap()],
202 &[KeyContext::parse("barf").unwrap()],
203 )
204 .0
205 .is_empty());
206 assert!(!keymap
207 .bindings_for_input(
208 &[Keystroke::parse("ctrl-a").unwrap()],
209 &[KeyContext::parse("editor").unwrap()],
210 )
211 .0
212 .is_empty());
213
214 // binding is disabled in a more specific context
215 assert!(keymap
216 .bindings_for_input(
217 &[Keystroke::parse("ctrl-a").unwrap()],
218 &[KeyContext::parse("editor mode=full").unwrap()],
219 )
220 .0
221 .is_empty());
222
223 // binding is globally disabled
224 assert!(keymap
225 .bindings_for_input(
226 &[Keystroke::parse("ctrl-b").unwrap()],
227 &[KeyContext::parse("barf").unwrap()],
228 )
229 .0
230 .is_empty());
231 }
232}