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.id() == action.id()
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 todo!()
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
270impl Keystroke {
271 pub fn parse(source: &str) -> anyhow::Result<Self> {
272 let mut ctrl = false;
273 let mut alt = false;
274 let mut shift = false;
275 let mut cmd = false;
276 let mut key = None;
277
278 let mut components = source.split("-").peekable();
279 while let Some(component) = components.next() {
280 match component {
281 "ctrl" => ctrl = true,
282 "alt" => alt = true,
283 "shift" => shift = true,
284 "cmd" => cmd = true,
285 _ => {
286 if let Some(component) = components.peek() {
287 if component.is_empty() && source.ends_with('-') {
288 key = Some(String::from("-"));
289 break;
290 } else {
291 return Err(anyhow!("Invalid keystroke `{}`", source));
292 }
293 } else {
294 key = Some(String::from(component));
295 }
296 }
297 }
298 }
299
300 Ok(Keystroke {
301 ctrl,
302 alt,
303 shift,
304 cmd,
305 key: key.unwrap(),
306 })
307 }
308
309 pub fn modified(&self) -> bool {
310 self.ctrl || self.alt || self.shift || self.cmd
311 }
312}
313
314impl Context {
315 pub fn extend(&mut self, other: &Context) {
316 for v in &other.set {
317 self.set.insert(v.clone());
318 }
319 for (k, v) in &other.map {
320 self.map.insert(k.clone(), v.clone());
321 }
322 }
323}
324
325impl ContextPredicate {
326 fn parse(source: &str) -> anyhow::Result<Self> {
327 let mut parser = Parser::new();
328 let language = unsafe { tree_sitter_context_predicate() };
329 parser.set_language(language).unwrap();
330 let source = source.as_bytes();
331 let tree = parser.parse(source, None).unwrap();
332 Self::from_node(tree.root_node(), source)
333 }
334
335 fn from_node(node: Node, source: &[u8]) -> anyhow::Result<Self> {
336 let parse_error = "error parsing context predicate";
337 let kind = node.kind();
338
339 match kind {
340 "source" => Self::from_node(node.child(0).ok_or(anyhow!(parse_error))?, source),
341 "identifier" => Ok(Self::Identifier(node.utf8_text(source)?.into())),
342 "not" => {
343 let child = Self::from_node(
344 node.child_by_field_name("expression")
345 .ok_or(anyhow!(parse_error))?,
346 source,
347 )?;
348 Ok(Self::Not(Box::new(child)))
349 }
350 "and" | "or" => {
351 let left = Box::new(Self::from_node(
352 node.child_by_field_name("left")
353 .ok_or(anyhow!(parse_error))?,
354 source,
355 )?);
356 let right = Box::new(Self::from_node(
357 node.child_by_field_name("right")
358 .ok_or(anyhow!(parse_error))?,
359 source,
360 )?);
361 if kind == "and" {
362 Ok(Self::And(left, right))
363 } else {
364 Ok(Self::Or(left, right))
365 }
366 }
367 "equal" | "not_equal" => {
368 let left = node
369 .child_by_field_name("left")
370 .ok_or(anyhow!(parse_error))?
371 .utf8_text(source)?
372 .into();
373 let right = node
374 .child_by_field_name("right")
375 .ok_or(anyhow!(parse_error))?
376 .utf8_text(source)?
377 .into();
378 if kind == "equal" {
379 Ok(Self::Equal(left, right))
380 } else {
381 Ok(Self::NotEqual(left, right))
382 }
383 }
384 "parenthesized" => Self::from_node(
385 node.child_by_field_name("expression")
386 .ok_or(anyhow!(parse_error))?,
387 source,
388 ),
389 _ => Err(anyhow!(parse_error)),
390 }
391 }
392
393 fn eval(&self, cx: &Context) -> bool {
394 match self {
395 Self::Identifier(name) => cx.set.contains(name.as_str()),
396 Self::Equal(left, right) => cx
397 .map
398 .get(left)
399 .map(|value| value == right)
400 .unwrap_or(false),
401 Self::NotEqual(left, right) => {
402 cx.map.get(left).map(|value| value != right).unwrap_or(true)
403 }
404 Self::Not(pred) => !pred.eval(cx),
405 Self::And(left, right) => left.eval(cx) && right.eval(cx),
406 Self::Or(left, right) => left.eval(cx) || right.eval(cx),
407 }
408 }
409}
410
411#[cfg(test)]
412mod tests {
413 use serde::Deserialize;
414
415 use crate::{actions, impl_actions};
416
417 use super::*;
418
419 #[test]
420 fn test_keystroke_parsing() -> anyhow::Result<()> {
421 assert_eq!(
422 Keystroke::parse("ctrl-p")?,
423 Keystroke {
424 key: "p".into(),
425 ctrl: true,
426 alt: false,
427 shift: false,
428 cmd: false,
429 }
430 );
431
432 assert_eq!(
433 Keystroke::parse("alt-shift-down")?,
434 Keystroke {
435 key: "down".into(),
436 ctrl: false,
437 alt: true,
438 shift: true,
439 cmd: false,
440 }
441 );
442
443 assert_eq!(
444 Keystroke::parse("shift-cmd--")?,
445 Keystroke {
446 key: "-".into(),
447 ctrl: false,
448 alt: false,
449 shift: true,
450 cmd: true,
451 }
452 );
453
454 Ok(())
455 }
456
457 #[test]
458 fn test_context_predicate_parsing() -> anyhow::Result<()> {
459 use ContextPredicate::*;
460
461 assert_eq!(
462 ContextPredicate::parse("a && (b == c || d != e)")?,
463 And(
464 Box::new(Identifier("a".into())),
465 Box::new(Or(
466 Box::new(Equal("b".into(), "c".into())),
467 Box::new(NotEqual("d".into(), "e".into())),
468 ))
469 )
470 );
471
472 assert_eq!(
473 ContextPredicate::parse("!a")?,
474 Not(Box::new(Identifier("a".into())),)
475 );
476
477 Ok(())
478 }
479
480 #[test]
481 fn test_context_predicate_eval() -> anyhow::Result<()> {
482 let predicate = ContextPredicate::parse("a && b || c == d")?;
483
484 let mut context = Context::default();
485 context.set.insert("a".into());
486 assert!(!predicate.eval(&context));
487
488 context.set.insert("b".into());
489 assert!(predicate.eval(&context));
490
491 context.set.remove("b");
492 context.map.insert("c".into(), "x".into());
493 assert!(!predicate.eval(&context));
494
495 context.map.insert("c".into(), "d".into());
496 assert!(predicate.eval(&context));
497
498 let predicate = ContextPredicate::parse("!a")?;
499 assert!(predicate.eval(&Context::default()));
500
501 Ok(())
502 }
503
504 #[test]
505 fn test_matcher() -> anyhow::Result<()> {
506 #[derive(Clone, Deserialize, PartialEq, Eq, Debug)]
507 pub struct A(pub String);
508 impl_actions!(test, [A]);
509 actions!(test, [B, Ab]);
510
511 #[derive(Clone, Debug, Eq, PartialEq)]
512 struct ActionArg {
513 a: &'static str,
514 }
515
516 let keymap = Keymap::new(vec![
517 Binding::new("a", A("x".to_string()), Some("a")),
518 Binding::new("b", B, Some("a")),
519 Binding::new("a b", Ab, Some("a || b")),
520 ]);
521
522 let mut ctx_a = Context::default();
523 ctx_a.set.insert("a".into());
524
525 let mut ctx_b = Context::default();
526 ctx_b.set.insert("b".into());
527
528 let mut matcher = Matcher::new(keymap);
529
530 // Basic match
531 assert_eq!(
532 downcast(&matcher.test_keystroke("a", 1, &ctx_a)),
533 Some(&A("x".to_string()))
534 );
535
536 // Multi-keystroke match
537 assert!(matcher.test_keystroke("a", 1, &ctx_b).is_none());
538 assert_eq!(downcast(&matcher.test_keystroke("b", 1, &ctx_b)), Some(&Ab));
539
540 // Failed matches don't interfere with matching subsequent keys
541 assert!(matcher.test_keystroke("x", 1, &ctx_a).is_none());
542 assert_eq!(
543 downcast(&matcher.test_keystroke("a", 1, &ctx_a)),
544 Some(&A("x".to_string()))
545 );
546
547 // Pending keystrokes are cleared when the context changes
548 assert!(&matcher.test_keystroke("a", 1, &ctx_b).is_none());
549 assert_eq!(downcast(&matcher.test_keystroke("b", 1, &ctx_a)), Some(&B));
550
551 let mut ctx_c = Context::default();
552 ctx_c.set.insert("c".into());
553
554 // Pending keystrokes are maintained per-view
555 assert!(matcher.test_keystroke("a", 1, &ctx_b).is_none());
556 assert!(matcher.test_keystroke("a", 2, &ctx_c).is_none());
557 assert_eq!(downcast(&matcher.test_keystroke("b", 1, &ctx_b)), Some(&Ab));
558
559 Ok(())
560 }
561
562 fn downcast<'a, A: Action>(action: &'a Option<Box<dyn Action>>) -> Option<&'a A> {
563 action
564 .as_ref()
565 .and_then(|action| action.as_any().downcast_ref())
566 }
567
568 impl Matcher {
569 fn test_keystroke(
570 &mut self,
571 keystroke: &str,
572 view_id: usize,
573 cx: &Context,
574 ) -> Option<Box<dyn Action>> {
575 if let MatchResult::Action(action) =
576 self.push_keystroke(Keystroke::parse(keystroke).unwrap(), view_id, cx)
577 {
578 Some(action.boxed_clone())
579 } else {
580 None
581 }
582 }
583 }
584}