1use std::rc::Rc;
2
3use collections::HashMap;
4
5use crate::{Action, InvalidKeystrokeError, KeyBindingContextPredicate, Keystroke, SharedString};
6use smallvec::SmallVec;
7
8/// A keybinding and its associated metadata, from the keymap.
9pub struct KeyBinding {
10 pub(crate) action: Box<dyn Action>,
11 pub(crate) keystrokes: SmallVec<[Keystroke; 2]>,
12 pub(crate) context_predicate: Option<Rc<KeyBindingContextPredicate>>,
13 pub(crate) meta: Option<KeyBindingMetaIndex>,
14 /// The json input string used when building the keybinding, if any
15 pub(crate) action_input: Option<SharedString>,
16}
17
18impl Clone for KeyBinding {
19 fn clone(&self) -> Self {
20 KeyBinding {
21 action: self.action.boxed_clone(),
22 keystrokes: self.keystrokes.clone(),
23 context_predicate: self.context_predicate.clone(),
24 meta: self.meta,
25 action_input: self.action_input.clone(),
26 }
27 }
28}
29
30impl KeyBinding {
31 /// Construct a new keybinding from the given data. Panics on parse error.
32 pub fn new<A: Action>(keystrokes: &str, action: A, context: Option<&str>) -> Self {
33 let context_predicate =
34 context.map(|context| KeyBindingContextPredicate::parse(context).unwrap().into());
35 Self::load(keystrokes, Box::new(action), context_predicate, None, None).unwrap()
36 }
37
38 /// Load a keybinding from the given raw data.
39 pub fn load(
40 keystrokes: &str,
41 action: Box<dyn Action>,
42 context_predicate: Option<Rc<KeyBindingContextPredicate>>,
43 key_equivalents: Option<&HashMap<char, char>>,
44 action_input: Option<SharedString>,
45 ) -> std::result::Result<Self, InvalidKeystrokeError> {
46 let mut keystrokes: SmallVec<[Keystroke; 2]> = keystrokes
47 .split_whitespace()
48 .map(Keystroke::parse)
49 .collect::<std::result::Result<_, _>>()?;
50
51 if let Some(equivalents) = key_equivalents {
52 for keystroke in keystrokes.iter_mut() {
53 if keystroke.key.chars().count() == 1
54 && let Some(key) = equivalents.get(&keystroke.key.chars().next().unwrap())
55 {
56 keystroke.key = key.to_string();
57 }
58 }
59 }
60
61 Ok(Self {
62 keystrokes,
63 action,
64 context_predicate,
65 meta: None,
66 action_input,
67 })
68 }
69
70 /// Set the metadata for this binding.
71 pub fn with_meta(mut self, meta: KeyBindingMetaIndex) -> Self {
72 self.meta = Some(meta);
73 self
74 }
75
76 /// Set the metadata for this binding.
77 pub fn set_meta(&mut self, meta: KeyBindingMetaIndex) {
78 self.meta = Some(meta);
79 }
80
81 /// Check if the given keystrokes match this binding.
82 pub fn match_keystrokes(&self, typed: &[Keystroke]) -> Option<bool> {
83 if self.keystrokes.len() < typed.len() {
84 return None;
85 }
86
87 for (target, typed) in self.keystrokes.iter().zip(typed.iter()) {
88 if !typed.should_match(target) {
89 return None;
90 }
91 }
92
93 Some(self.keystrokes.len() > typed.len())
94 }
95
96 /// Get the keystrokes associated with this binding
97 pub fn keystrokes(&self) -> &[Keystroke] {
98 self.keystrokes.as_slice()
99 }
100
101 /// Get the action associated with this binding
102 pub fn action(&self) -> &dyn Action {
103 self.action.as_ref()
104 }
105
106 /// Get the predicate used to match this binding
107 pub fn predicate(&self) -> Option<Rc<KeyBindingContextPredicate>> {
108 self.context_predicate.as_ref().map(|rc| rc.clone())
109 }
110
111 /// Get the metadata for this binding
112 pub fn meta(&self) -> Option<KeyBindingMetaIndex> {
113 self.meta
114 }
115
116 /// Get the action input associated with the action for this binding
117 pub fn action_input(&self) -> Option<SharedString> {
118 self.action_input.clone()
119 }
120}
121
122impl std::fmt::Debug for KeyBinding {
123 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124 f.debug_struct("KeyBinding")
125 .field("keystrokes", &self.keystrokes)
126 .field("context_predicate", &self.context_predicate)
127 .field("action", &self.action.name())
128 .finish()
129 }
130}
131
132/// A unique identifier for retrieval of metadata associated with a key binding.
133/// Intended to be used as an index or key into a user-defined store of metadata
134/// associated with the binding, such as the source of the binding.
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
136pub struct KeyBindingMetaIndex(pub u32);