1use core::fmt;
7use core::str::FromStr;
8
9pub mod grammar;
10mod keys;
11
12pub use grammar::{ChordError, ChordErrorKind};
13#[cfg(feature = "iced")]
14pub use keys::UnsupportedKeyCode;
15pub use keys::{KeyCode, NamedKey};
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
19#[non_exhaustive]
20pub enum Modifier {
21 ControlOrMeta,
24 Control,
26 Alt,
28 Shift,
30 Meta,
32}
33
34impl Modifier {
35 pub const ALL: &'static [Modifier] = &[
37 Modifier::ControlOrMeta,
38 Modifier::Control,
39 Modifier::Alt,
40 Modifier::Shift,
41 Modifier::Meta,
42 ];
43
44 #[must_use]
46 pub const fn name(self) -> &'static str {
47 match self {
48 Modifier::ControlOrMeta => "ControlOrMeta",
49 Modifier::Control => "Control",
50 Modifier::Alt => "Alt",
51 Modifier::Shift => "Shift",
52 Modifier::Meta => "Meta",
53 }
54 }
55
56 #[must_use]
58 pub const fn key(self) -> Option<NamedKey> {
59 match self {
60 Modifier::ControlOrMeta => None,
61 Modifier::Control => Some(NamedKey::Control),
62 Modifier::Alt => Some(NamedKey::Alt),
63 Modifier::Shift => Some(NamedKey::Shift),
64 Modifier::Meta => Some(NamedKey::Meta),
65 }
66 }
67
68 const fn bit(self) -> u8 {
69 match self {
70 Modifier::ControlOrMeta => 1,
71 Modifier::Control => 1 << 1,
72 Modifier::Alt => 1 << 2,
73 Modifier::Shift => 1 << 3,
74 Modifier::Meta => 1 << 4,
75 }
76 }
77}
78
79impl fmt::Display for Modifier {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 f.write_str(self.name())
82 }
83}
84
85#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
87pub struct ModifierSet(u8);
88
89impl ModifierSet {
90 pub const NONE: Self = Self(0);
92 pub const CONTROL_OR_META: Self = Self(Modifier::ControlOrMeta.bit());
94 pub const CONTROL: Self = Self(Modifier::Control.bit());
96 pub const ALT: Self = Self(Modifier::Alt.bit());
98 pub const SHIFT: Self = Self(Modifier::Shift.bit());
100 pub const META: Self = Self(Modifier::Meta.bit());
102
103 #[must_use]
105 pub const fn only(modifier: Modifier) -> Self {
106 Self(modifier.bit())
107 }
108
109 #[must_use]
111 pub const fn union(self, other: Self) -> Self {
112 Self(self.0 | other.0)
113 }
114
115 #[must_use]
117 pub const fn with(self, modifier: Modifier) -> Self {
118 Self(self.0 | modifier.bit())
119 }
120
121 #[must_use]
123 pub const fn has(self, modifier: Modifier) -> bool {
124 self.0 & modifier.bit() != 0
125 }
126
127 #[must_use]
129 pub const fn contains(self, other: Self) -> bool {
130 self.0 & other.0 == other.0
131 }
132
133 #[must_use]
135 pub const fn is_empty(self) -> bool {
136 self.0 == 0
137 }
138
139 pub fn iter(self) -> impl Iterator<Item = Modifier> {
141 Modifier::ALL
142 .iter()
143 .copied()
144 .filter(move |modifier| self.has(*modifier))
145 }
146}
147
148impl From<Modifier> for ModifierSet {
149 fn from(modifier: Modifier) -> Self {
150 Self::only(modifier)
151 }
152}
153
154impl FromIterator<Modifier> for ModifierSet {
155 fn from_iter<I: IntoIterator<Item = Modifier>>(modifiers: I) -> Self {
156 modifiers.into_iter().fold(Self::NONE, Self::with)
157 }
158}
159
160impl core::ops::BitOr for ModifierSet {
161 type Output = Self;
162
163 fn bitor(self, other: Self) -> Self {
164 self.union(other)
165 }
166}
167
168impl core::ops::BitOr<Modifier> for ModifierSet {
169 type Output = Self;
170
171 fn bitor(self, modifier: Modifier) -> Self {
172 self.with(modifier)
173 }
174}
175
176impl fmt::Debug for ModifierSet {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 f.debug_set().entries(self.iter()).finish()
179 }
180}
181
182#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
184pub enum Keystroke {
185 Named(NamedKey),
187 Code(KeyCode),
189 Character(char),
192}
193
194impl From<NamedKey> for Keystroke {
195 fn from(key: NamedKey) -> Self {
196 Keystroke::Named(key)
197 }
198}
199
200impl From<KeyCode> for Keystroke {
201 fn from(code: KeyCode) -> Self {
202 Keystroke::Code(code)
203 }
204}
205
206impl From<char> for Keystroke {
207 fn from(character: char) -> Self {
208 Keystroke::Character(character)
209 }
210}
211
212impl fmt::Display for Keystroke {
213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214 grammar::write_keystroke(f, *self)
215 }
216}
217
218impl FromStr for Keystroke {
219 type Err = ChordError;
220
221 fn from_str(input: &str) -> Result<Self, ChordError> {
222 grammar::parse_keystroke(input)
223 }
224}
225
226#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
228pub struct Chord {
229 modifiers: ModifierSet,
230 key: Keystroke,
231}
232
233impl Chord {
234 #[must_use]
236 pub const fn new(modifiers: ModifierSet, key: Keystroke) -> Self {
237 Self { modifiers, key }
238 }
239
240 #[must_use]
242 pub const fn modifiers(self) -> ModifierSet {
243 self.modifiers
244 }
245
246 #[must_use]
248 pub const fn key(self) -> Keystroke {
249 self.key
250 }
251}
252
253impl From<Keystroke> for Chord {
254 fn from(key: Keystroke) -> Self {
255 Self::new(ModifierSet::NONE, key)
256 }
257}
258
259impl fmt::Display for Chord {
261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262 for modifier in self.modifiers.iter() {
263 write!(f, "{modifier}+")?;
264 }
265 grammar::write_keystroke(f, self.key)
266 }
267}
268
269impl FromStr for Chord {
270 type Err = ChordError;
271
272 fn from_str(input: &str) -> Result<Self, ChordError> {
273 grammar::parse_chord(input)
274 }
275}
276
277#[cfg(feature = "serde")]
278mod serde_impls {
279 use super::{Chord, Keystroke};
280 use serde::de::Error as _;
281
282 impl serde::Serialize for Chord {
283 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
284 serializer.collect_str(self)
285 }
286 }
287
288 impl<'de> serde::Deserialize<'de> for Chord {
289 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
290 String::deserialize(deserializer)?
291 .parse()
292 .map_err(D::Error::custom)
293 }
294 }
295
296 impl serde::Serialize for Keystroke {
297 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
298 serializer.collect_str(self)
299 }
300 }
301
302 impl<'de> serde::Deserialize<'de> for Keystroke {
303 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
304 String::deserialize(deserializer)?
305 .parse()
306 .map_err(D::Error::custom)
307 }
308 }
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314
315 #[test]
316 fn modifier_sets() {
317 let set = ModifierSet::CONTROL | ModifierSet::SHIFT;
318 assert!(set.has(Modifier::Control));
319 assert!(!set.has(Modifier::Alt));
320 assert!(set.contains(ModifierSet::SHIFT));
321 assert!(!set.contains(ModifierSet::SHIFT | ModifierSet::META));
322 assert!(ModifierSet::default().is_empty());
323 assert_eq!(
324 set.iter().collect::<Vec<_>>(),
325 [Modifier::Control, Modifier::Shift]
326 );
327 assert_eq!(format!("{set:?}"), "{Control, Shift}");
328 assert_eq!(
329 [Modifier::Shift, Modifier::Control]
330 .into_iter()
331 .collect::<ModifierSet>(),
332 set
333 );
334 assert_eq!(ModifierSet::NONE | Modifier::Alt, ModifierSet::ALT);
335 assert_eq!(ModifierSet::from(Modifier::Meta), ModifierSet::META);
336 assert_eq!(
337 ModifierSet::only(Modifier::ControlOrMeta),
338 ModifierSet::CONTROL_OR_META
339 );
340 }
341
342 #[test]
343 fn modifiers_print_in_canonical_order() {
344 let all: ModifierSet = Modifier::ALL.iter().copied().collect();
345 let chord = Chord::new(all, Keystroke::Character('k'));
346 assert_eq!(chord.to_string(), "ControlOrMeta+Control+Alt+Shift+Meta+K");
347 }
348
349 #[test]
350 fn modifier_keys() {
351 assert_eq!(Modifier::ControlOrMeta.key(), None);
352 assert_eq!(Modifier::Control.key(), Some(NamedKey::Control));
353 assert_eq!(Modifier::Meta.to_string(), "Meta");
354 }
355
356 #[test]
357 fn chord_parts_and_conversions() {
358 let chord = Chord::new(ModifierSet::SHIFT, NamedKey::Enter.into());
359 assert_eq!(chord.modifiers(), ModifierSet::SHIFT);
360 assert_eq!(chord.key(), Keystroke::Named(NamedKey::Enter));
361 assert_eq!(
362 Chord::from(Keystroke::from('a')).modifiers(),
363 ModifierSet::NONE
364 );
365 assert_eq!(
366 Keystroke::from(KeyCode::KeyK),
367 Keystroke::Code(KeyCode::KeyK)
368 );
369 }
370
371 #[cfg(feature = "serde")]
372 #[test]
373 fn chords_serialise_as_strings() -> Result<(), serde_json::Error> {
374 let chord: Chord = Chord::new(
375 ModifierSet::CONTROL | ModifierSet::SHIFT,
376 Keystroke::Character('k'),
377 );
378 assert_eq!(serde_json::to_string(&chord)?, "\"Control+Shift+K\"");
379 assert_eq!(
380 serde_json::from_str::<Chord>("\"Ctrl + Shift + K\"")?,
381 chord
382 );
383 assert!(serde_json::from_str::<Chord>("\"Ctrl+\"").is_err());
384 assert_eq!(
385 serde_json::to_string(&Keystroke::Code(KeyCode::KeyA))?,
386 "\"Code(KeyA)\""
387 );
388 assert_eq!(
389 serde_json::from_str::<Keystroke>("\"F5\"")?,
390 Keystroke::Named(NamedKey::F5)
391 );
392 Ok(())
393 }
394}