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
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(mut bindings: Vec<KeyBinding>) -> Option<KeyBinding> {
206 bindings.pop()
207 }
208
209 /// Returns the first binding present in the iterator, which tends to be the
210 /// default binding without any key context. This is useful for cases where no
211 /// key context is available on binding display. Otherwise, bindings with a
212 /// more specific key context would take precedence and result in a
213 /// potentially invalid keybind being returned.
214 pub fn default_binding_from_bindings_iterator<'a>(
215 mut bindings: impl Iterator<Item = &'a KeyBinding>,
216 ) -> Option<&'a KeyBinding> {
217 bindings.next()
218 }
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224 use crate as gpui;
225 use gpui::{NoAction, actions};
226
227 actions!(
228 keymap_test,
229 [ActionAlpha, ActionBeta, ActionGamma, ActionDelta,]
230 );
231
232 #[test]
233 fn test_keymap() {
234 let bindings = [
235 KeyBinding::new("ctrl-a", ActionAlpha {}, None),
236 KeyBinding::new("ctrl-a", ActionBeta {}, Some("pane")),
237 KeyBinding::new("ctrl-a", ActionGamma {}, Some("editor && mode==full")),
238 ];
239
240 let mut keymap = Keymap::default();
241 keymap.add_bindings(bindings.clone());
242
243 // global bindings are enabled in all contexts
244 assert!(keymap.binding_enabled(&bindings[0], &[]));
245 assert!(keymap.binding_enabled(&bindings[0], &[KeyContext::parse("terminal").unwrap()]));
246
247 // contextual bindings are enabled in contexts that match their predicate
248 assert!(!keymap.binding_enabled(&bindings[1], &[KeyContext::parse("barf x=y").unwrap()]));
249 assert!(keymap.binding_enabled(&bindings[1], &[KeyContext::parse("pane x=y").unwrap()]));
250
251 assert!(!keymap.binding_enabled(&bindings[2], &[KeyContext::parse("editor").unwrap()]));
252 assert!(keymap.binding_enabled(
253 &bindings[2],
254 &[KeyContext::parse("editor mode=full").unwrap()]
255 ));
256 }
257
258 #[test]
259 fn test_keymap_disabled() {
260 let bindings = [
261 KeyBinding::new("ctrl-a", ActionAlpha {}, Some("editor")),
262 KeyBinding::new("ctrl-b", ActionAlpha {}, Some("editor")),
263 KeyBinding::new("ctrl-a", NoAction {}, Some("editor && mode==full")),
264 KeyBinding::new("ctrl-b", NoAction {}, None),
265 ];
266
267 let mut keymap = Keymap::default();
268 keymap.add_bindings(bindings.clone());
269
270 // binding is only enabled in a specific context
271 assert!(
272 keymap
273 .bindings_for_input(
274 &[Keystroke::parse("ctrl-a").unwrap()],
275 &[KeyContext::parse("barf").unwrap()],
276 )
277 .0
278 .is_empty()
279 );
280 assert!(
281 !keymap
282 .bindings_for_input(
283 &[Keystroke::parse("ctrl-a").unwrap()],
284 &[KeyContext::parse("editor").unwrap()],
285 )
286 .0
287 .is_empty()
288 );
289
290 // binding is disabled in a more specific context
291 assert!(
292 keymap
293 .bindings_for_input(
294 &[Keystroke::parse("ctrl-a").unwrap()],
295 &[KeyContext::parse("editor mode=full").unwrap()],
296 )
297 .0
298 .is_empty()
299 );
300
301 // binding is globally disabled
302 assert!(
303 keymap
304 .bindings_for_input(
305 &[Keystroke::parse("ctrl-b").unwrap()],
306 &[KeyContext::parse("barf").unwrap()],
307 )
308 .0
309 .is_empty()
310 );
311 }
312
313 #[test]
314 fn test_bindings_for_action() {
315 let bindings = [
316 KeyBinding::new("ctrl-a", ActionAlpha {}, Some("pane")),
317 KeyBinding::new("ctrl-b", ActionBeta {}, Some("editor && mode == full")),
318 KeyBinding::new("ctrl-c", ActionGamma {}, Some("workspace")),
319 KeyBinding::new("ctrl-a", NoAction {}, Some("pane && active")),
320 KeyBinding::new("ctrl-b", NoAction {}, Some("editor")),
321 ];
322
323 let mut keymap = Keymap::default();
324 keymap.add_bindings(bindings.clone());
325
326 assert_bindings(&keymap, &ActionAlpha {}, &["ctrl-a"]);
327 assert_bindings(&keymap, &ActionBeta {}, &[]);
328 assert_bindings(&keymap, &ActionGamma {}, &["ctrl-c"]);
329
330 #[track_caller]
331 fn assert_bindings(keymap: &Keymap, action: &dyn Action, expected: &[&str]) {
332 let actual = keymap
333 .bindings_for_action(action)
334 .map(|binding| binding.keystrokes[0].unparse())
335 .collect::<Vec<_>>();
336 assert_eq!(actual, expected, "{:?}", action);
337 }
338 }
339}