1use std::fmt;
4
5#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
7pub struct Modifiers {
8 pub shift: bool,
9 pub control: bool,
10 pub alt: bool,
11 pub platform: bool,
13}
14
15impl Modifiers {
16 pub const NONE: Modifiers = Modifiers {
17 shift: false,
18 control: false,
19 alt: false,
20 platform: false,
21 };
22
23 pub fn secondary(&self) -> bool {
25 if cfg!(target_os = "macos") {
26 self.platform
27 } else {
28 self.control
29 }
30 }
31
32 pub fn any(&self) -> bool {
33 self.shift || self.control || self.alt || self.platform
34 }
35
36 pub fn is_command_like(&self) -> bool {
38 self.control || self.alt || self.platform
39 }
40
41 pub fn types_text(&self) -> bool {
46 if self.platform {
47 false
48 } else if cfg!(target_os = "macos") {
49 !self.control
50 } else {
51 self.control == self.alt
52 }
53 }
54}
55
56#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
58pub enum NamedKey {
59 Enter,
60 Tab,
61 Space,
62 Backspace,
63 Delete,
64 Escape,
65 ArrowLeft,
66 ArrowRight,
67 ArrowUp,
68 ArrowDown,
69 Home,
70 End,
71 PageUp,
72 PageDown,
73 Insert,
74 F(u8),
75 Shift,
76 Control,
77 Alt,
78 Super,
79 CapsLock,
80 ContextMenu,
81}
82
83impl NamedKey {
84 fn name(&self) -> String {
85 match self {
86 NamedKey::Enter => "enter".into(),
87 NamedKey::Tab => "tab".into(),
88 NamedKey::Space => "space".into(),
89 NamedKey::Backspace => "backspace".into(),
90 NamedKey::Delete => "delete".into(),
91 NamedKey::Escape => "escape".into(),
92 NamedKey::ArrowLeft => "left".into(),
93 NamedKey::ArrowRight => "right".into(),
94 NamedKey::ArrowUp => "up".into(),
95 NamedKey::ArrowDown => "down".into(),
96 NamedKey::Home => "home".into(),
97 NamedKey::End => "end".into(),
98 NamedKey::PageUp => "pageup".into(),
99 NamedKey::PageDown => "pagedown".into(),
100 NamedKey::Insert => "insert".into(),
101 NamedKey::F(n) => format!("f{n}"),
102 NamedKey::Shift => "shift".into(),
103 NamedKey::Control => "control".into(),
104 NamedKey::Alt => "alt".into(),
105 NamedKey::Super => "super".into(),
106 NamedKey::CapsLock => "capslock".into(),
107 NamedKey::ContextMenu => "menu".into(),
108 }
109 }
110
111 fn parse(s: &str) -> Option<NamedKey> {
112 Some(match s {
113 "enter" | "return" => NamedKey::Enter,
114 "tab" => NamedKey::Tab,
115 "space" => NamedKey::Space,
116 "backspace" => NamedKey::Backspace,
117 "delete" | "del" => NamedKey::Delete,
118 "escape" | "esc" => NamedKey::Escape,
119 "left" => NamedKey::ArrowLeft,
120 "right" => NamedKey::ArrowRight,
121 "up" => NamedKey::ArrowUp,
122 "down" => NamedKey::ArrowDown,
123 "home" => NamedKey::Home,
124 "end" => NamedKey::End,
125 "pageup" => NamedKey::PageUp,
126 "pagedown" => NamedKey::PageDown,
127 "insert" => NamedKey::Insert,
128 "menu" => NamedKey::ContextMenu,
129 _ => {
130 let n = s.strip_prefix('f')?.parse::<u8>().ok()?;
131 if (1..=24).contains(&n) {
132 NamedKey::F(n)
133 } else {
134 return None;
135 }
136 }
137 })
138 }
139
140 pub fn is_modifier(&self) -> bool {
141 matches!(
142 self,
143 NamedKey::Shift
144 | NamedKey::Control
145 | NamedKey::Alt
146 | NamedKey::Super
147 | NamedKey::CapsLock
148 )
149 }
150}
151
152#[derive(Clone, Debug, PartialEq, Eq, Hash)]
154pub enum Key {
155 Character(String),
158 Named(NamedKey),
159 Unidentified,
160}
161
162impl Key {
163 pub fn character(s: &str) -> Key {
164 Key::Character(s.to_lowercase())
165 }
166}
167
168#[derive(Clone, Debug, PartialEq, Eq, Hash)]
170pub struct Keystroke {
171 pub modifiers: Modifiers,
172 pub key: Key,
173 pub key_char: Option<String>,
176}
177
178#[derive(Clone, Debug, PartialEq, Eq)]
180pub struct KeystrokeParseError(pub String);
181
182impl fmt::Display for KeystrokeParseError {
183 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184 write!(f, "invalid keystroke: {}", self.0)
185 }
186}
187
188impl std::error::Error for KeystrokeParseError {}
189
190impl Keystroke {
191 pub fn new(modifiers: Modifiers, key: Key) -> Self {
192 Keystroke {
193 modifiers,
194 key,
195 key_char: None,
196 }
197 }
198
199 pub fn parse(source: &str) -> Result<Keystroke, KeystrokeParseError> {
202 let mut modifiers = Modifiers::default();
203 let mut key = None;
204 let parts: Vec<&str> = split_keystroke(source);
205 let last = parts.len().saturating_sub(1);
206 for (i, part) in parts.iter().enumerate() {
207 let lower = part.to_lowercase();
208 if i < last {
209 match lower.as_str() {
210 "ctrl" | "control" => modifiers.control = true,
211 "shift" => modifiers.shift = true,
212 "alt" | "option" => modifiers.alt = true,
213 "cmd" | "super" | "win" | "meta" | "platform" => modifiers.platform = true,
214 "secondary" => {
215 if cfg!(target_os = "macos") {
216 modifiers.platform = true
217 } else {
218 modifiers.control = true
219 }
220 }
221 _ => return Err(KeystrokeParseError(source.to_string())),
222 }
223 } else if let Some(named) = NamedKey::parse(&lower) {
224 key = Some(Key::Named(named));
225 } else if part.chars().count() == 1 {
226 key = Some(Key::character(part));
227 } else {
228 return Err(KeystrokeParseError(source.to_string()));
229 }
230 }
231 let key = key.ok_or_else(|| KeystrokeParseError(source.to_string()))?;
232 Ok(Keystroke {
233 modifiers,
234 key,
235 key_char: None,
236 })
237 }
238
239 pub fn matches(&self, binding: &Keystroke) -> bool {
241 if self.key == binding.key && self.modifiers == binding.modifiers {
242 return true;
243 }
244 if !binding.modifiers.shift
246 && let (Key::Character(want), Some(produced)) = (&binding.key, &self.key_char)
247 {
248 let mut mods = self.modifiers;
249 mods.shift = false;
250 return produced == want && mods == binding.modifiers;
251 }
252 false
253 }
254}
255
256fn split_keystroke(s: &str) -> Vec<&str> {
258 let mut parts = Vec::new();
259 let mut start = 0;
260 let bytes = s.as_bytes();
261 let mut i = 0;
262 while i < bytes.len() {
263 if bytes[i] == b'-' && i > start {
264 parts.push(&s[start..i]);
265 start = i + 1;
266 }
267 i += 1;
268 }
269 if start < s.len() {
270 parts.push(&s[start..]);
271 }
272 parts
273}
274
275impl fmt::Display for Keystroke {
276 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277 if self.modifiers.control {
278 f.write_str("ctrl-")?;
279 }
280 if self.modifiers.alt {
281 f.write_str("alt-")?;
282 }
283 if self.modifiers.shift {
284 f.write_str("shift-")?;
285 }
286 if self.modifiers.platform {
287 f.write_str(if cfg!(target_os = "macos") {
288 "cmd-"
289 } else {
290 "win-"
291 })?;
292 }
293 match &self.key {
294 Key::Character(c) => f.write_str(c),
295 Key::Named(n) => f.write_str(&n.name()),
296 Key::Unidentified => f.write_str("?"),
297 }
298 }
299}
300
301#[cfg(test)]
302mod tests {
303 use super::*;
304
305 #[test]
306 fn parse_and_display() {
307 let k = Keystroke::parse("ctrl-shift-p").unwrap();
308 assert!(k.modifiers.control && k.modifiers.shift);
309 assert_eq!(k.key, Key::Character("p".into()));
310 assert_eq!(k.to_string(), "ctrl-shift-p");
311 assert_eq!(
312 Keystroke::parse("alt-f4").unwrap().key,
313 Key::Named(NamedKey::F(4))
314 );
315 assert_eq!(
316 Keystroke::parse("ctrl--").unwrap().key,
317 Key::Character("-".into())
318 );
319 assert!(Keystroke::parse("hyper-x").is_err());
320 assert!(Keystroke::parse("").is_err());
321 }
322
323 #[test]
324 fn altgr_types_text() {
325 let altgr = Modifiers {
326 control: true,
327 alt: true,
328 ..Default::default()
329 };
330 let ctrl = Modifiers {
331 control: true,
332 ..Default::default()
333 };
334 assert!(Modifiers::NONE.types_text());
335 assert!(!ctrl.types_text());
336 if !cfg!(target_os = "macos") {
337 assert!(altgr.types_text());
338 }
339 }
340
341 #[test]
342 fn shifted_character_matching() {
343 let binding = Keystroke::parse("?").unwrap();
344 let pressed = Keystroke {
345 modifiers: Modifiers {
346 shift: true,
347 ..Default::default()
348 },
349 key: Key::Character("/".into()),
350 key_char: Some("?".into()),
351 };
352 assert!(pressed.matches(&binding));
353 let ctrl_s = Keystroke::parse("ctrl-s").unwrap();
354 let pressed = Keystroke {
355 modifiers: Modifiers {
356 control: true,
357 ..Default::default()
358 },
359 key: Key::character("S"),
360 key_char: None,
361 };
362 assert!(pressed.matches(&ctrl_s));
363 }
364}