1#[must_use]
11pub fn key(name: &str) -> Option<String> {
12 if name == " " {
13 return Some("space".to_owned());
14 }
15 let name = name.trim();
16 if name.chars().count() == 1 {
17 return Some(name.to_lowercase());
18 }
19 let canonical = match name.to_ascii_lowercase().replace([' ', '_'], "").as_str() {
22 "return" | "enter" => "enter",
23 "esc" | "escape" => "escape",
24 "spacebar" | "space" => "space",
25 "tab" => "tab",
26 "backspace" | "back" => "backspace",
27 "del" | "delete" => "delete",
28 "ins" | "insert" => "insert",
29 "arrowup" | "up" => "up",
30 "arrowdown" | "down" => "down",
31 "arrowleft" | "left" => "left",
32 "arrowright" | "right" => "right",
33 "home" => "home",
34 "end" => "end",
35 "pgup" | "pageup" => "pageup",
36 "pgdn" | "pgdown" | "pagedown" => "pagedown",
37 "f1" => "f1",
38 "f2" => "f2",
39 "f3" => "f3",
40 "f4" => "f4",
41 "f5" => "f5",
42 "f6" => "f6",
43 "f7" => "f7",
44 "f8" => "f8",
45 "f9" => "f9",
46 "f10" => "f10",
47 "f11" => "f11",
48 "f12" => "f12",
49 _ => return None,
50 };
51 Some(canonical.to_owned())
52}
53
54pub const KEY_NAMES: &str = "`Enter`, `Esc`, `Space`, `Tab`, `Backspace`, `Delete`, `Home`, `End`, `PageUp`, `PageDown`, the arrows, `F1`–`F12`, or one character";
56
57fn modifier(name: &str) -> Option<Modifier> {
59 match name.trim().to_ascii_lowercase().as_str() {
60 "ctrl" | "control" | "cmd" | "command" | "⌘" | "⌃" => Some(Modifier::Command),
61 "shift" | "⇧" => Some(Modifier::Shift),
62 "alt" | "option" | "⌥" => Some(Modifier::Alt),
63 "super" | "meta" | "win" | "logo" => Some(Modifier::System),
64 _ => None,
65 }
66}
67
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
69enum Modifier {
70 Command,
72 Shift,
73 Alt,
74 System,
76}
77
78fn parts_of(text: &str) -> Vec<&str> {
80 let text = text.trim();
81 let (modifiers, own) = match text.strip_suffix(['=', '-']) {
85 Some(rest) if rest.contains('+') => (rest.trim_end_matches('+'), text.get(rest.len()..)),
88 _ => (text, None),
89 };
90 let mut parts: Vec<&str> = modifiers.split('+').map(str::trim).collect();
91 if let Some(own) = own {
92 parts.push(own);
93 }
94 parts
95}
96
97pub fn written(text: &str) -> Result<String, String> {
106 let _ = Chord::parse(text)?;
107 let parts = parts_of(text);
108 let last = parts.len().saturating_sub(1);
109 let shown: Vec<&str> = parts
110 .iter()
111 .enumerate()
112 .map(|(at, part)| match (at == last, modifier(part)) {
113 (true, _) | (false, None) => *part,
114 (false, Some(Modifier::Command)) => "Ctrl",
115 (false, Some(Modifier::System)) => "Super",
116 (false, Some(Modifier::Shift)) => "Shift",
117 (false, Some(Modifier::Alt)) => "Alt",
118 })
119 .collect();
120 Ok(shown.join("+"))
121}
122
123#[allow(
127 clippy::struct_excessive_bools,
128 reason = "a press reports the four modifiers as independent flags; a chord mirrors them"
129)]
130#[derive(Clone, Debug, PartialEq, Eq)]
131pub struct Chord {
132 pub command: bool,
134 pub system: bool,
136 pub shift: bool,
137 pub alt: bool,
138 pub key: String,
140}
141
142impl Chord {
143 pub fn parse(text: &str) -> Result<Self, String> {
150 let text = text.trim();
151 let mut parts = parts_of(text);
152 if text.is_empty() || parts.iter().any(|part| part.is_empty()) {
153 return Err(format!(
154 "`{text}` is no shortcut: it is modifiers and one key, such as `Ctrl+Enter`"
155 ));
156 }
157 let mut key_seen: Option<&str> = None;
158 for part in &parts {
159 match (modifier(part), key_seen) {
160 (None, None) => key_seen = Some(*part),
161 (None, Some(_)) => {
162 return Err(format!(
163 "`{text}` names more than one key: it is modifiers and one key, such as `Ctrl+Enter`"
164 ));
165 }
166 (Some(_), Some(key)) => {
167 return Err(format!(
168 "`{text}` holds one key: `{key}` comes before `{part}`, which is a modifier"
169 ));
170 }
171 (Some(_), None) => {}
172 }
173 }
174 let Some(part) = parts.pop() else {
175 return Err(format!("`{text}` names no key: {KEY_NAMES}"));
176 };
177 if modifier(part).is_some() {
178 return Err(format!(
179 "`{part}` is a modifier, not a key: `{part}+Enter` holds it with a key"
180 ));
181 }
182 let Some(key) = key(part) else {
183 return Err(format!("`{part}` is no key: {KEY_NAMES}"));
184 };
185 let mut chord = Self {
186 command: false,
187 system: false,
188 shift: false,
189 alt: false,
190 key,
191 };
192 for part in parts {
193 match modifier(part) {
194 Some(Modifier::Command) if !chord.command => chord.command = true,
195 Some(Modifier::System) if !chord.system => chord.system = true,
196 Some(Modifier::Shift) if !chord.shift => chord.shift = true,
197 Some(Modifier::Alt) if !chord.alt => chord.alt = true,
198 Some(_) => return Err(format!("`{part}` is given twice in `{text}`")),
199 None => {
200 return Err(format!(
201 "`{part}` is no modifier: `Ctrl`, `Shift`, `Alt` or `Super`"
202 ));
203 }
204 }
205 }
206 Ok(chord)
207 }
208
209 #[must_use]
212 pub fn text(&self) -> String {
213 let mut parts = Vec::with_capacity(5);
214 for (held, name) in [
215 (self.system, "Super"),
216 (self.command, "Ctrl"),
217 (self.alt, "Alt"),
218 (self.shift, "Shift"),
219 ] {
220 if held {
221 parts.push(name.to_owned());
222 }
223 }
224 parts.push(self.key.clone());
225 parts.join("+")
226 }
227}
228
229#[cfg(test)]
230mod tests {
231 use super::*;
232
233 #[test]
235 fn one_table_names_the_keys_a_shortcut_can_use() {
236 assert_eq!(key("Enter").as_deref(), Some("enter"));
237 assert_eq!(key("Return").as_deref(), Some("enter"));
238 assert_eq!(key("Esc").as_deref(), Some("escape"));
239 assert_eq!(key("PgDn").as_deref(), Some("pagedown"));
240 assert_eq!(key("F5").as_deref(), Some("f5"));
241 assert_eq!(key("E").as_deref(), Some("e"));
242 assert_eq!(key(" ").as_deref(), Some("space"));
243 assert_eq!(key("Page Up").as_deref(), Some("pageup"));
244 assert_eq!(key("Shift"), None);
245 assert_eq!(key("Entr"), None);
246 }
247
248 #[test]
250 fn a_chord_is_modifiers_and_one_key() {
251 let chord = Chord::parse("Shift+cTrL+Enter").expect("a chord");
252 assert!(chord.command && chord.shift && !chord.alt && !chord.system);
253 assert_eq!(chord.key, "enter");
254 assert_eq!(chord.text(), "Ctrl+Shift+enter");
255 assert_eq!(Chord::parse("e").expect("a key on its own").text(), "e");
256 assert_eq!(
257 Chord::parse("Super+Space").expect("a desktop chord").text(),
258 "Super+space"
259 );
260 assert_eq!(
261 Chord::parse("Ctrl+Enter").unwrap(),
262 Chord::parse("Control+Return").unwrap()
263 );
264 assert_eq!(
266 Chord::parse("Ctrl+=").expect("the equals key").text(),
267 "Ctrl+="
268 );
269 assert_eq!(
270 Chord::parse("Ctrl+-").expect("the minus key").text(),
271 "Ctrl+-"
272 );
273 for (wrong, said) in [
274 ("", "no shortcut"),
275 ("Ctrl", "is a modifier, not a key"),
276 ("Ctrl++Enter", "no shortcut"),
277 ("Ctrl+Entr", "is no key"),
278 ("Ctrl+Shift+Shift+K", "given twice"),
279 ("Ctrl+K+Shift", "comes before"),
280 ("Ctrl+K+Enter", "more than one key"),
281 ] {
282 let error = Chord::parse(wrong).expect_err(wrong);
283 assert!(error.contains(said), "`{wrong}`: {error}");
284 }
285 }
286
287 #[test]
290 fn a_chord_is_written_as_its_app_wrote_the_key() {
291 assert_eq!(written("Ctrl+S").expect("a chord"), "Ctrl+S");
292 assert_eq!(
293 written("control+shift+Down").expect("a chord"),
294 "Ctrl+Shift+Down"
295 );
296 assert_eq!(written("Super+/").expect("a chord"), "Super+/");
297 assert_eq!(written("Ctrl+=").expect("a chord"), "Ctrl+=");
298 for spelling in ["Ctrl+Enter", "control+Return", "shift+cTrL+ENTER"] {
299 assert_eq!(
300 Chord::parse(&written(spelling).expect("a chord")).expect("the written chord"),
301 Chord::parse(spelling).expect("the press"),
302 "{spelling} writes the press it names"
303 );
304 }
305 assert!(written("Ctrl+").is_err(), "what is no chord is not written");
306 }
307}