1use crate::Action;
2use anyhow::{anyhow, Result};
3use smallvec::SmallVec;
4use std::{
5 any::{Any, TypeId},
6 collections::{HashMap, HashSet},
7 fmt::Debug,
8};
9use tree_sitter::{Language, Node, Parser};
10
11extern "C" {
12 fn tree_sitter_context_predicate() -> Language;
13}
14
15pub struct Matcher {
16 pending: HashMap<usize, Pending>,
17 keymap: Keymap,
18}
19
20#[derive(Default)]
21struct Pending {
22 keystrokes: Vec<Keystroke>,
23 context: Option<Context>,
24}
25
26#[derive(Default)]
27pub struct Keymap {
28 bindings: Vec<Binding>,
29 binding_indices_by_action_type: HashMap<TypeId, SmallVec<[usize; 3]>>,
30}
31
32pub struct Binding {
33 keystrokes: SmallVec<[Keystroke; 2]>,
34 action: Box<dyn Action>,
35 context_predicate: Option<ContextPredicate>,
36}
37
38#[derive(Clone, Debug, Eq, PartialEq)]
39pub struct Keystroke {
40 pub ctrl: bool,
41 pub alt: bool,
42 pub shift: bool,
43 pub cmd: bool,
44 pub key: String,
45}
46
47#[derive(Clone, Debug, Default, Eq, PartialEq)]
48pub struct Context {
49 pub set: HashSet<String>,
50 pub map: HashMap<String, String>,
51}
52
53#[derive(Debug, Eq, PartialEq)]
54enum ContextPredicate {
55 Identifier(String),
56 Equal(String, String),
57 NotEqual(String, String),
58 Not(Box<ContextPredicate>),
59 And(Box<ContextPredicate>, Box<ContextPredicate>),
60 Or(Box<ContextPredicate>, Box<ContextPredicate>),
61}
62
63trait ActionArg {
64 fn boxed_clone(&self) -> Box<dyn Any>;
65}
66
67impl<T> ActionArg for T
68where
69 T: 'static + Any + Clone,
70{
71 fn boxed_clone(&self) -> Box<dyn Any> {
72 Box::new(self.clone())
73 }
74}
75
76pub enum MatchResult {
77 None,
78 Pending,
79 Action(Box<dyn Action>),
80}
81
82impl Debug for MatchResult {
83 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84 match self {
85 MatchResult::None => f.debug_struct("MatchResult::None").finish(),
86 MatchResult::Pending => f.debug_struct("MatchResult::Pending").finish(),
87 MatchResult::Action(action) => f
88 .debug_tuple("MatchResult::Action")
89 .field(&action.name())
90 .finish(),
91 }
92 }
93}
94
95impl Matcher {
96 pub fn new(keymap: Keymap) -> Self {
97 Self {
98 pending: HashMap::new(),
99 keymap,
100 }
101 }
102
103 pub fn set_keymap(&mut self, keymap: Keymap) {
104 self.pending.clear();
105 self.keymap = keymap;
106 }
107
108 pub fn add_bindings<T: IntoIterator<Item = Binding>>(&mut self, bindings: T) {
109 self.pending.clear();
110 self.keymap.add_bindings(bindings);
111 }
112
113 pub fn clear_bindings(&mut self) {
114 self.pending.clear();
115 self.keymap.clear();
116 }
117
118 pub fn bindings_for_action_type(&self, action_type: TypeId) -> impl Iterator<Item = &Binding> {
119 self.keymap.bindings_for_action_type(action_type)
120 }
121
122 pub fn clear_pending(&mut self) {
123 self.pending.clear();
124 }
125
126 pub fn has_pending_keystrokes(&self) -> bool {
127 !self.pending.is_empty()
128 }
129
130 pub fn push_keystroke(
131 &mut self,
132 keystroke: Keystroke,
133 view_id: usize,
134 cx: &Context,
135 ) -> MatchResult {
136 let pending = self.pending.entry(view_id).or_default();
137
138 if let Some(pending_ctx) = pending.context.as_ref() {
139 if pending_ctx != cx {
140 pending.keystrokes.clear();
141 }
142 }
143
144 pending.keystrokes.push(keystroke);
145
146 let mut retain_pending = false;
147 for binding in self.keymap.bindings.iter().rev() {
148 if binding.keystrokes.starts_with(&pending.keystrokes)
149 && binding
150 .context_predicate
151 .as_ref()
152 .map(|c| c.eval(cx))
153 .unwrap_or(true)
154 {
155 if binding.keystrokes.len() == pending.keystrokes.len() {
156 self.pending.remove(&view_id);
157 return MatchResult::Action(binding.action.boxed_clone());
158 } else {
159 retain_pending = true;
160 pending.context = Some(cx.clone());
161 }
162 }
163 }
164
165 if retain_pending {
166 MatchResult::Pending
167 } else {
168 self.pending.remove(&view_id);
169 MatchResult::None
170 }
171 }
172
173 pub fn keystrokes_for_action(
174 &self,
175 action: &dyn Action,
176 cx: &Context,
177 ) -> Option<SmallVec<[Keystroke; 2]>> {
178 for binding in self.keymap.bindings.iter().rev() {
179 if binding.action.eq(action)
180 && binding
181 .context_predicate
182 .as_ref()
183 .map_or(true, |predicate| predicate.eval(cx))
184 {
185 return Some(binding.keystrokes.clone());
186 }
187 }
188 None
189 }
190}
191
192impl Default for Matcher {
193 fn default() -> Self {
194 Self::new(Keymap::default())
195 }
196}
197
198impl Keymap {
199 pub fn new(bindings: Vec<Binding>) -> Self {
200 let mut binding_indices_by_action_type = HashMap::new();
201 for (ix, binding) in bindings.iter().enumerate() {
202 binding_indices_by_action_type
203 .entry(binding.action.as_any().type_id())
204 .or_insert_with(|| SmallVec::new())
205 .push(ix);
206 }
207 Self {
208 binding_indices_by_action_type,
209 bindings,
210 }
211 }
212
213 fn bindings_for_action_type<'a>(
214 &'a self,
215 action_type: TypeId,
216 ) -> impl Iterator<Item = &'a Binding> {
217 self.binding_indices_by_action_type
218 .get(&action_type)
219 .map(SmallVec::as_slice)
220 .unwrap_or(&[])
221 .iter()
222 .map(|ix| &self.bindings[*ix])
223 }
224
225 fn add_bindings<T: IntoIterator<Item = Binding>>(&mut self, bindings: T) {
226 for binding in bindings {
227 self.binding_indices_by_action_type
228 .entry(binding.action.as_any().type_id())
229 .or_default()
230 .push(self.bindings.len());
231 self.bindings.push(binding);
232 }
233 }
234
235 fn clear(&mut self) {
236 self.bindings.clear();
237 self.binding_indices_by_action_type.clear();
238 }
239}
240
241impl Binding {
242 pub fn new<A: Action>(keystrokes: &str, action: A, context: Option<&str>) -> Self {
243 Self::load(keystrokes, Box::new(action), context).unwrap()
244 }
245
246 pub fn load(keystrokes: &str, action: Box<dyn Action>, context: Option<&str>) -> Result<Self> {
247 let context = if let Some(context) = context {
248 Some(ContextPredicate::parse(context)?)
249 } else {
250 None
251 };
252
253 let keystrokes = keystrokes
254 .split_whitespace()
255 .map(|key| Keystroke::parse(key))
256 .collect::<Result<_>>()?;
257
258 Ok(Self {
259 keystrokes,
260 action,
261 context_predicate: context,
262 })
263 }
264
265 pub fn keystrokes(&self) -> &[Keystroke] {
266 &self.keystrokes
267 }
268
269 pub fn action(&self) -> &dyn Action {
270 self.action.as_ref()
271 }
272}
273
274impl Keystroke {
275 pub fn parse(source: &str) -> anyhow::Result<Self> {
276 let mut ctrl = false;
277 let mut alt = false;
278 let mut shift = false;
279 let mut cmd = false;
280 let mut key = None;
281
282 let mut components = source.split("-").peekable();
283 while let Some(component) = components.next() {
284 match component {
285 "ctrl" => ctrl = true,
286 "alt" => alt = true,
287 "shift" => shift = true,
288 "cmd" => cmd = true,
289 _ => {
290 if let Some(component) = components.peek() {
291 if component.is_empty() && source.ends_with('-') {
292 key = Some(String::from("-"));
293 break;
294 } else {
295 return Err(anyhow!("Invalid keystroke `{}`", source));
296 }
297 } else {
298 key = Some(String::from(component));
299 }
300 }
301 }
302 }
303
304 Ok(Keystroke {
305 ctrl,
306 alt,
307 shift,
308 cmd,
309 key: key.unwrap(),
310 })
311 }
312
313 pub fn modified(&self) -> bool {
314 self.ctrl || self.alt || self.shift || self.cmd
315 }
316}
317
318impl std::fmt::Display for Keystroke {
319 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
320 if self.ctrl {
321 write!(f, "{}", "^")?;
322 }
323 if self.alt {
324 write!(f, "{}", "⎇")?;
325 }
326 if self.cmd {
327 write!(f, "{}", "⌘")?;
328 }
329 if self.shift {
330 write!(f, "{}", "⇧")?;
331 }
332 let key = match self.key.as_str() {
333 "backspace" => "⌫",
334 "up" => "↑",
335 "down" => "↓",
336 "left" => "←",
337 "right" => "→",
338 "tab" => "⇥",
339 "escape" => "⎋",
340 key => key,
341 };
342 write!(f, "{}", key)
343 }
344}
345
346impl Context {
347 pub fn extend(&mut self, other: &Context) {
348 for v in &other.set {
349 self.set.insert(v.clone());
350 }
351 for (k, v) in &other.map {
352 self.map.insert(k.clone(), v.clone());
353 }
354 }
355}
356
357impl ContextPredicate {
358 fn parse(source: &str) -> anyhow::Result<Self> {
359 let mut parser = Parser::new();
360 let language = unsafe { tree_sitter_context_predicate() };
361 parser.set_language(language).unwrap();
362 let source = source.as_bytes();
363 let tree = parser.parse(source, None).unwrap();
364 Self::from_node(tree.root_node(), source)
365 }
366
367 fn from_node(node: Node, source: &[u8]) -> anyhow::Result<Self> {
368 let parse_error = "error parsing context predicate";
369 let kind = node.kind();
370
371 match kind {
372 "source" => Self::from_node(node.child(0).ok_or(anyhow!(parse_error))?, source),
373 "identifier" => Ok(Self::Identifier(node.utf8_text(source)?.into())),
374 "not" => {
375 let child = Self::from_node(
376 node.child_by_field_name("expression")
377 .ok_or(anyhow!(parse_error))?,
378 source,
379 )?;
380 Ok(Self::Not(Box::new(child)))
381 }
382 "and" | "or" => {
383 let left = Box::new(Self::from_node(
384 node.child_by_field_name("left")
385 .ok_or(anyhow!(parse_error))?,
386 source,
387 )?);
388 let right = Box::new(Self::from_node(
389 node.child_by_field_name("right")
390 .ok_or(anyhow!(parse_error))?,
391 source,
392 )?);
393 if kind == "and" {
394 Ok(Self::And(left, right))
395 } else {
396 Ok(Self::Or(left, right))
397 }
398 }
399 "equal" | "not_equal" => {
400 let left = node
401 .child_by_field_name("left")
402 .ok_or(anyhow!(parse_error))?
403 .utf8_text(source)?
404 .into();
405 let right = node
406 .child_by_field_name("right")
407 .ok_or(anyhow!(parse_error))?
408 .utf8_text(source)?
409 .into();
410 if kind == "equal" {
411 Ok(Self::Equal(left, right))
412 } else {
413 Ok(Self::NotEqual(left, right))
414 }
415 }
416 "parenthesized" => Self::from_node(
417 node.child_by_field_name("expression")
418 .ok_or(anyhow!(parse_error))?,
419 source,
420 ),
421 _ => Err(anyhow!(parse_error)),
422 }
423 }
424
425 fn eval(&self, cx: &Context) -> bool {
426 match self {
427 Self::Identifier(name) => cx.set.contains(name.as_str()),
428 Self::Equal(left, right) => cx
429 .map
430 .get(left)
431 .map(|value| value == right)
432 .unwrap_or(false),
433 Self::NotEqual(left, right) => {
434 cx.map.get(left).map(|value| value != right).unwrap_or(true)
435 }
436 Self::Not(pred) => !pred.eval(cx),
437 Self::And(left, right) => left.eval(cx) && right.eval(cx),
438 Self::Or(left, right) => left.eval(cx) || right.eval(cx),
439 }
440 }
441}
442
443#[cfg(test)]
444mod tests {
445 use serde::Deserialize;
446
447 use crate::{actions, impl_actions};
448
449 use super::*;
450
451 #[test]
452 fn test_keystroke_parsing() -> anyhow::Result<()> {
453 assert_eq!(
454 Keystroke::parse("ctrl-p")?,
455 Keystroke {
456 key: "p".into(),
457 ctrl: true,
458 alt: false,
459 shift: false,
460 cmd: false,
461 }
462 );
463
464 assert_eq!(
465 Keystroke::parse("alt-shift-down")?,
466 Keystroke {
467 key: "down".into(),
468 ctrl: false,
469 alt: true,
470 shift: true,
471 cmd: false,
472 }
473 );
474
475 assert_eq!(
476 Keystroke::parse("shift-cmd--")?,
477 Keystroke {
478 key: "-".into(),
479 ctrl: false,
480 alt: false,
481 shift: true,
482 cmd: true,
483 }
484 );
485
486 Ok(())
487 }
488
489 #[test]
490 fn test_context_predicate_parsing() -> anyhow::Result<()> {
491 use ContextPredicate::*;
492
493 assert_eq!(
494 ContextPredicate::parse("a && (b == c || d != e)")?,
495 And(
496 Box::new(Identifier("a".into())),
497 Box::new(Or(
498 Box::new(Equal("b".into(), "c".into())),
499 Box::new(NotEqual("d".into(), "e".into())),
500 ))
501 )
502 );
503
504 assert_eq!(
505 ContextPredicate::parse("!a")?,
506 Not(Box::new(Identifier("a".into())),)
507 );
508
509 Ok(())
510 }
511
512 #[test]
513 fn test_context_predicate_eval() -> anyhow::Result<()> {
514 let predicate = ContextPredicate::parse("a && b || c == d")?;
515
516 let mut context = Context::default();
517 context.set.insert("a".into());
518 assert!(!predicate.eval(&context));
519
520 context.set.insert("b".into());
521 assert!(predicate.eval(&context));
522
523 context.set.remove("b");
524 context.map.insert("c".into(), "x".into());
525 assert!(!predicate.eval(&context));
526
527 context.map.insert("c".into(), "d".into());
528 assert!(predicate.eval(&context));
529
530 let predicate = ContextPredicate::parse("!a")?;
531 assert!(predicate.eval(&Context::default()));
532
533 Ok(())
534 }
535
536 #[test]
537 fn test_matcher() -> anyhow::Result<()> {
538 #[derive(Clone, Deserialize, PartialEq, Eq, Debug)]
539 pub struct A(pub String);
540 impl_actions!(test, [A]);
541 actions!(test, [B, Ab]);
542
543 #[derive(Clone, Debug, Eq, PartialEq)]
544 struct ActionArg {
545 a: &'static str,
546 }
547
548 let keymap = Keymap::new(vec![
549 Binding::new("a", A("x".to_string()), Some("a")),
550 Binding::new("b", B, Some("a")),
551 Binding::new("a b", Ab, Some("a || b")),
552 ]);
553
554 let mut ctx_a = Context::default();
555 ctx_a.set.insert("a".into());
556
557 let mut ctx_b = Context::default();
558 ctx_b.set.insert("b".into());
559
560 let mut matcher = Matcher::new(keymap);
561
562 // Basic match
563 assert_eq!(
564 downcast(&matcher.test_keystroke("a", 1, &ctx_a)),
565 Some(&A("x".to_string()))
566 );
567
568 // Multi-keystroke match
569 assert!(matcher.test_keystroke("a", 1, &ctx_b).is_none());
570 assert_eq!(downcast(&matcher.test_keystroke("b", 1, &ctx_b)), Some(&Ab));
571
572 // Failed matches don't interfere with matching subsequent keys
573 assert!(matcher.test_keystroke("x", 1, &ctx_a).is_none());
574 assert_eq!(
575 downcast(&matcher.test_keystroke("a", 1, &ctx_a)),
576 Some(&A("x".to_string()))
577 );
578
579 // Pending keystrokes are cleared when the context changes
580 assert!(&matcher.test_keystroke("a", 1, &ctx_b).is_none());
581 assert_eq!(downcast(&matcher.test_keystroke("b", 1, &ctx_a)), Some(&B));
582
583 let mut ctx_c = Context::default();
584 ctx_c.set.insert("c".into());
585
586 // Pending keystrokes are maintained per-view
587 assert!(matcher.test_keystroke("a", 1, &ctx_b).is_none());
588 assert!(matcher.test_keystroke("a", 2, &ctx_c).is_none());
589 assert_eq!(downcast(&matcher.test_keystroke("b", 1, &ctx_b)), Some(&Ab));
590
591 Ok(())
592 }
593
594 fn downcast<'a, A: Action>(action: &'a Option<Box<dyn Action>>) -> Option<&'a A> {
595 action
596 .as_ref()
597 .and_then(|action| action.as_any().downcast_ref())
598 }
599
600 impl Matcher {
601 fn test_keystroke(
602 &mut self,
603 keystroke: &str,
604 view_id: usize,
605 cx: &Context,
606 ) -> Option<Box<dyn Action>> {
607 if let MatchResult::Action(action) =
608 self.push_keystroke(Keystroke::parse(keystroke).unwrap(), view_id, cx)
609 {
610 Some(action.boxed_clone())
611 } else {
612 None
613 }
614 }
615 }
616}