kova_native_input/
keymap.rs1use crate::{Keystroke, KeystrokeParseError};
10use std::any::{Any, TypeId};
11use std::fmt::Debug;
12
13pub trait Action: Any + Debug {
24 fn boxed_clone(&self) -> Box<dyn Action>;
25 fn name(&self) -> &'static str;
26 fn as_any(&self) -> &dyn Any;
27 fn action_type(&self) -> TypeId;
28}
29
30impl<T: Any + Clone + Debug> Action for T {
31 fn boxed_clone(&self) -> Box<dyn Action> {
32 Box::new(self.clone())
33 }
34
35 fn name(&self) -> &'static str {
36 std::any::type_name::<T>()
37 }
38
39 fn as_any(&self) -> &dyn Any {
40 self
41 }
42
43 fn action_type(&self) -> TypeId {
44 TypeId::of::<T>()
45 }
46}
47
48#[macro_export]
54macro_rules! actions {
55 ($($name:ident),* $(,)?) => {
56 $(
57 #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
58 pub struct $name;
59 )*
60 };
61}
62
63#[derive(Debug)]
65pub struct KeyBinding {
66 pub keystrokes: Vec<Keystroke>,
67 pub action: Box<dyn Action>,
68 pub context: Option<&'static str>,
71}
72
73impl Clone for KeyBinding {
74 fn clone(&self) -> Self {
75 KeyBinding {
76 keystrokes: self.keystrokes.clone(),
77 action: self.action.boxed_clone(),
78 context: self.context,
79 }
80 }
81}
82
83impl KeyBinding {
84 pub fn new(keystrokes: &str, action: impl Action) -> KeyBinding {
87 Self::try_new(keystrokes, action).unwrap_or_else(|e| panic!("{e}"))
88 }
89
90 pub fn try_new(
91 keystrokes: &str,
92 action: impl Action,
93 ) -> Result<KeyBinding, KeystrokeParseError> {
94 let keystrokes = keystrokes
95 .split_whitespace()
96 .map(Keystroke::parse)
97 .collect::<Result<Vec<_>, _>>()?;
98 if keystrokes.is_empty() {
99 return Err(KeystrokeParseError(String::new()));
100 }
101 Ok(KeyBinding {
102 keystrokes,
103 action: Box::new(action),
104 context: None,
105 })
106 }
107
108 pub fn context(mut self, context: &'static str) -> Self {
109 self.context = Some(context);
110 self
111 }
112}
113
114#[derive(Debug)]
116pub enum KeymapMatch {
117 None,
119 Pending,
121 Matched(Vec<Box<dyn Action>>),
123}
124
125#[derive(Default)]
127pub struct Keymap {
128 bindings: Vec<KeyBinding>,
129 pending: Vec<Keystroke>,
130}
131
132impl Keymap {
133 pub fn new() -> Self {
134 Self::default()
135 }
136
137 pub fn add(&mut self, binding: KeyBinding) {
138 self.bindings.push(binding);
139 }
140
141 pub fn extend(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
142 self.bindings.extend(bindings);
143 }
144
145 pub fn bindings(&self) -> &[KeyBinding] {
146 &self.bindings
147 }
148
149 pub fn bindings_for(&self, action: &dyn Action) -> impl Iterator<Item = &KeyBinding> {
151 let ty = action.action_type();
152 self.bindings
153 .iter()
154 .filter(move |b| b.action.action_type() == ty)
155 }
156
157 pub fn has_pending(&self) -> bool {
158 !self.pending.is_empty()
159 }
160
161 pub fn clear_pending(&mut self) {
162 self.pending.clear();
163 }
164
165 pub fn feed(&mut self, keystroke: &Keystroke, contexts: &[&'static str]) -> KeymapMatch {
168 let mut sequence = self.pending.clone();
169 sequence.push(keystroke.clone());
170
171 let active = |b: &KeyBinding| b.context.is_none_or(|c| contexts.contains(&c));
172 let mut complete: Vec<(&KeyBinding, usize)> = Vec::new();
173 let mut is_prefix = false;
174 for (index, binding) in self.bindings.iter().enumerate() {
175 if !active(binding) || binding.keystrokes.len() < sequence.len() {
176 continue;
177 }
178 let prefix_matches = sequence
179 .iter()
180 .zip(&binding.keystrokes)
181 .all(|(pressed, bound)| pressed.matches(bound));
182 if !prefix_matches {
183 continue;
184 }
185 if binding.keystrokes.len() == sequence.len() {
186 complete.push((binding, index));
187 } else {
188 is_prefix = true;
189 }
190 }
191
192 if is_prefix {
193 self.pending = sequence;
194 return KeymapMatch::Pending;
195 }
196 self.pending.clear();
197 if complete.is_empty() {
198 return KeymapMatch::None;
199 }
200 complete.sort_by_key(|(b, index)| (b.context.is_none(), std::cmp::Reverse(*index)));
203 KeymapMatch::Matched(
204 complete
205 .into_iter()
206 .map(|(b, _)| b.action.boxed_clone())
207 .collect(),
208 )
209 }
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215 use crate::{Key, Modifiers};
216
217 crate::actions!(Save, SaveAll, Undo, EditorUndo);
218
219 fn ks(s: &str) -> Keystroke {
220 Keystroke::parse(s).unwrap()
221 }
222
223 #[test]
224 fn single_and_chorded_bindings() {
225 let mut km = Keymap::new();
226 km.add(KeyBinding::new("ctrl-s", Save));
227 km.add(KeyBinding::new("ctrl-k s", SaveAll));
228
229 match km.feed(&ks("ctrl-s"), &[]) {
230 KeymapMatch::Matched(a) => assert_eq!(a[0].action_type(), TypeId::of::<Save>()),
231 other => panic!("{other:?}"),
232 }
233 assert!(matches!(km.feed(&ks("ctrl-k"), &[]), KeymapMatch::Pending));
234 match km.feed(&ks("s"), &[]) {
235 KeymapMatch::Matched(a) => assert_eq!(a[0].action_type(), TypeId::of::<SaveAll>()),
236 other => panic!("{other:?}"),
237 }
238 assert!(matches!(km.feed(&ks("x"), &[]), KeymapMatch::None));
239 }
240
241 #[test]
242 fn context_bindings_take_precedence() {
243 let mut km = Keymap::new();
244 km.add(KeyBinding::new("ctrl-z", Undo));
245 km.add(KeyBinding::new("ctrl-z", EditorUndo).context("Editor"));
246 match km.feed(&ks("ctrl-z"), &["Editor"]) {
247 KeymapMatch::Matched(a) => {
248 assert_eq!(a[0].action_type(), TypeId::of::<EditorUndo>());
249 assert_eq!(a[1].action_type(), TypeId::of::<Undo>());
250 }
251 other => panic!("{other:?}"),
252 }
253 match km.feed(&ks("ctrl-z"), &[]) {
254 KeymapMatch::Matched(a) => assert_eq!(a.len(), 1),
255 other => panic!("{other:?}"),
256 }
257 let _ = Keystroke::new(Modifiers::NONE, Key::Unidentified);
258 }
259}