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