1#[cfg(feature = "schemars")]
2use schemars::JsonSchema;
3use serde::{Deserialize, Serialize};
4use std::{
5 error::Error,
6 fmt::{Display, Write},
7};
8
9use crate::{OperatingSystem, PlatformKeyboardMapper};
10
11pub trait AsKeystroke {
13 fn as_keystroke(&self) -> &Keystroke;
15}
16
17#[derive(Clone, Debug, Eq, PartialEq, Default, Deserialize, Hash)]
19pub struct Keystroke {
20 pub modifiers: Modifiers,
22
23 pub key: String,
29
30 pub key_char: Option<String>,
34}
35
36#[derive(Debug, Clone, Eq, PartialEq, Hash)]
38pub struct KeybindingKeystroke {
39 inner: Keystroke,
41 #[cfg(target_os = "windows")]
43 display_modifiers: Modifiers,
44 #[cfg(target_os = "windows")]
46 display_key: String,
47}
48
49#[derive(Debug)]
52pub struct InvalidKeystrokeError {
53 pub keystroke: String,
55}
56
57impl Error for InvalidKeystrokeError {}
58
59impl Display for InvalidKeystrokeError {
60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 write!(
62 f,
63 "Invalid keystroke \"{}\". {}",
64 self.keystroke, KEYSTROKE_PARSE_EXPECTED_MESSAGE
65 )
66 }
67}
68
69pub const KEYSTROKE_PARSE_EXPECTED_MESSAGE: &str = "Expected a sequence of modifiers \
71 (`ctrl`, `alt`, `shift`, `fn`, `cmd`, `super`, or `win`) \
72 followed by a key, separated by `-`.";
73
74impl Keystroke {
75 pub fn should_match(&self, target: &KeybindingKeystroke) -> bool {
84 #[cfg(not(target_os = "windows"))]
85 if let Some(key_char) = self
86 .key_char
87 .as_ref()
88 .filter(|key_char| key_char != &&self.key)
89 {
90 let ime_modifiers = Modifiers {
91 control: self.modifiers.control,
92 platform: self.modifiers.platform,
93 ..Default::default()
94 };
95
96 if &target.inner.key == key_char && target.inner.modifiers == ime_modifiers {
97 return true;
98 }
99 }
100
101 #[cfg(target_os = "windows")]
102 if let Some(key_char) = self
103 .key_char
104 .as_ref()
105 .filter(|key_char| key_char != &&self.key)
106 {
107 if &target.inner.key == key_char && target.inner.modifiers == Modifiers::none() {
109 return true;
110 }
111 }
112
113 target.inner.modifiers == self.modifiers && target.inner.key == self.key
114 }
115
116 pub fn parse(source: &'static str) -> std::result::Result<Self, InvalidKeystrokeError> {
122 Self::parse_internal(source, None)
123 }
124
125 pub fn parse_with_os(
127 source: &str,
128 os: OperatingSystem,
129 ) -> std::result::Result<Self, InvalidKeystrokeError> {
130 Self::parse_internal(source, Some(os))
131 }
132
133 fn parse_internal(
134 source: &str,
135 os: Option<OperatingSystem>,
136 ) -> std::result::Result<Self, InvalidKeystrokeError> {
137 let mut modifiers = Modifiers::none();
138 let mut key = None;
139 let mut key_char = None;
140
141 let mut components = source.split('-').peekable();
142 while let Some(component) = components.next() {
143 if component.eq_ignore_ascii_case("ctrl") {
144 modifiers.control = true;
145 continue;
146 }
147 if component.eq_ignore_ascii_case("alt") {
148 modifiers.alt = true;
149 continue;
150 }
151 if component.eq_ignore_ascii_case("shift") {
152 modifiers.shift = true;
153 continue;
154 }
155 if component.eq_ignore_ascii_case("fn") {
156 modifiers.function = true;
157 continue;
158 }
159 if component.eq_ignore_ascii_case("secondary") {
160 let os = os.ok_or_else(|| InvalidKeystrokeError {
161 keystroke: source.to_owned(),
162 })?;
163 if os == OperatingSystem::Mac {
164 modifiers.platform = true;
165 } else {
166 modifiers.control = true;
167 };
168 continue;
169 }
170
171 let is_platform = component.eq_ignore_ascii_case("cmd")
172 || component.eq_ignore_ascii_case("super")
173 || component.eq_ignore_ascii_case("win");
174
175 if is_platform {
176 modifiers.platform = true;
177 continue;
178 }
179
180 let mut key_str = component.to_string();
181
182 if let Some(next) = components.peek() {
183 if next.is_empty() && source.ends_with('-') {
184 key = Some(String::from("-"));
185 break;
186 } else if next.len() > 1 && next.starts_with('>') {
187 key = Some(key_str);
188 key_char = Some(String::from(&next[1..]));
189 components.next();
190 } else {
191 return Err(InvalidKeystrokeError {
192 keystroke: source.to_owned(),
193 });
194 }
195 continue;
196 }
197
198 if component.len() == 1 && component.as_bytes()[0].is_ascii_uppercase() {
199 modifiers.shift = true;
201 key_str.make_ascii_lowercase();
202 } else {
203 key_str.make_ascii_lowercase()
206 }
207 key = Some(key_str);
208 }
209
210 key = key.or_else(|| {
213 use std::mem;
214 if mem::take(&mut modifiers.shift) {
216 Some("shift".to_string())
217 } else if mem::take(&mut modifiers.control) {
218 Some("control".to_string())
219 } else if mem::take(&mut modifiers.alt) {
220 Some("alt".to_string())
221 } else if mem::take(&mut modifiers.platform) {
222 Some("platform".to_string())
223 } else if mem::take(&mut modifiers.function) {
224 Some("function".to_string())
225 } else {
226 None
227 }
228 });
229
230 let key = key.ok_or_else(|| InvalidKeystrokeError {
231 keystroke: source.to_owned(),
232 })?;
233
234 Ok(Keystroke {
235 modifiers,
236 key,
237 key_char,
238 })
239 }
240
241 pub fn unparse(&self, os: OperatingSystem) -> String {
243 unparse(&self.modifiers, &self.key, os)
244 }
245
246 pub fn display(&self, os: OperatingSystem) -> KeystrokeDisplay<'_> {
248 KeystrokeDisplay {
249 modifiers: &self.modifiers,
250 key: &self.key,
251 os,
252 }
253 }
254
255 pub fn is_ime_in_progress(&self) -> bool {
258 self.key_char.is_none()
259 && (is_printable_key(&self.key) || self.key.is_empty())
260 && !(self.modifiers.platform
261 || self.modifiers.control
262 || self.modifiers.function
263 || self.modifiers.alt)
264 }
265
266 pub fn with_simulated_ime(mut self) -> Self {
270 if self.key_char.is_none()
271 && !self.modifiers.platform
272 && !self.modifiers.control
273 && !self.modifiers.function
274 && !self.modifiers.alt
275 {
276 self.key_char = match self.key.as_str() {
277 "space" => Some(" ".into()),
278 "tab" => Some("\t".into()),
279 "enter" => Some("\n".into()),
280 key if !is_printable_key(key) || key.is_empty() => None,
281 key => {
282 if self.modifiers.shift {
283 Some(key.to_uppercase())
284 } else {
285 Some(key.into())
286 }
287 }
288 }
289 }
290 self
291 }
292
293 pub fn is_modifier_key(&self) -> bool {
295 matches!(
296 self.key.as_str(),
297 "shift" | "control" | "alt" | "platform" | "function"
298 )
299 }
300}
301
302impl KeybindingKeystroke {
303 pub fn display(&self, os: OperatingSystem) -> KeystrokeDisplay<'_> {
305 KeystrokeDisplay {
306 modifiers: self.modifiers(),
307 key: self.key(),
308 os,
309 }
310 }
311
312 #[cfg(target_os = "windows")]
313 #[expect(missing_docs)]
314 pub fn new(inner: Keystroke, display_modifiers: Modifiers, display_key: String) -> Self {
315 KeybindingKeystroke {
316 inner,
317 display_modifiers,
318 display_key,
319 }
320 }
321
322 pub fn new_with_mapper(
324 inner: Keystroke,
325 use_key_equivalents: bool,
326 keyboard_mapper: &dyn PlatformKeyboardMapper,
327 ) -> Self {
328 keyboard_mapper.map_key_equivalent(inner, use_key_equivalents)
329 }
330
331 pub fn from_keystroke(keystroke: Keystroke) -> Self {
333 #[cfg(target_os = "windows")]
334 {
335 let key = keystroke.key.clone();
336 let modifiers = keystroke.modifiers;
337 KeybindingKeystroke {
338 inner: keystroke,
339 display_modifiers: modifiers,
340 display_key: key,
341 }
342 }
343 #[cfg(not(target_os = "windows"))]
344 {
345 KeybindingKeystroke { inner: keystroke }
346 }
347 }
348
349 pub fn inner(&self) -> &Keystroke {
351 &self.inner
352 }
353
354 pub fn modifiers(&self) -> &Modifiers {
361 #[cfg(target_os = "windows")]
362 {
363 &self.display_modifiers
364 }
365 #[cfg(not(target_os = "windows"))]
366 {
367 &self.inner.modifiers
368 }
369 }
370
371 pub fn key(&self) -> &str {
377 #[cfg(target_os = "windows")]
378 {
379 &self.display_key
380 }
381 #[cfg(not(target_os = "windows"))]
382 {
383 &self.inner.key
384 }
385 }
386
387 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
389 self.inner.modifiers = modifiers;
390 #[cfg(target_os = "windows")]
391 {
392 self.display_modifiers = modifiers;
393 }
394 }
395
396 pub fn set_key(&mut self, key: String) {
398 #[cfg(target_os = "windows")]
399 {
400 self.display_key = key.clone();
401 }
402 self.inner.key = key;
403 }
404
405 pub fn unparse(&self, os: OperatingSystem) -> String {
407 #[cfg(target_os = "windows")]
408 {
409 unparse(&self.display_modifiers, &self.display_key, os)
410 }
411 #[cfg(not(target_os = "windows"))]
412 {
413 unparse(&self.inner.modifiers, &self.inner.key, os)
414 }
415 }
416
417 pub fn remove_key_char(&mut self) {
419 self.inner.key_char = None;
420 }
421}
422
423fn is_printable_key(key: &str) -> bool {
424 !matches!(
425 key,
426 "f1" | "f2"
427 | "f3"
428 | "f4"
429 | "f5"
430 | "f6"
431 | "f7"
432 | "f8"
433 | "f9"
434 | "f10"
435 | "f11"
436 | "f12"
437 | "f13"
438 | "f14"
439 | "f15"
440 | "f16"
441 | "f17"
442 | "f18"
443 | "f19"
444 | "f20"
445 | "f21"
446 | "f22"
447 | "f23"
448 | "f24"
449 | "f25"
450 | "f26"
451 | "f27"
452 | "f28"
453 | "f29"
454 | "f30"
455 | "f31"
456 | "f32"
457 | "f33"
458 | "f34"
459 | "f35"
460 | "backspace"
461 | "delete"
462 | "left"
463 | "right"
464 | "up"
465 | "down"
466 | "pageup"
467 | "pagedown"
468 | "insert"
469 | "home"
470 | "end"
471 | "back"
472 | "forward"
473 | "escape"
474 )
475}
476
477pub struct KeystrokeDisplay<'a> {
479 modifiers: &'a Modifiers,
480 key: &'a str,
481 os: OperatingSystem,
482}
483
484impl std::fmt::Display for KeystrokeDisplay<'_> {
485 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
486 display_modifiers(self.modifiers, self.os, f)?;
487 display_key(self.key, self.os, f)
488 }
489}
490
491#[derive(Copy, Clone, Debug, Eq, PartialEq, Default, Serialize, Deserialize, Hash)]
493#[cfg_attr(feature = "schemars", derive(JsonSchema))]
494pub struct Modifiers {
495 #[serde(default)]
497 pub control: bool,
498
499 #[serde(default)]
502 pub alt: bool,
503
504 #[serde(default)]
506 pub shift: bool,
507
508 #[serde(default)]
512 pub platform: bool,
513
514 #[serde(default)]
516 pub function: bool,
517}
518
519impl Modifiers {
520 pub fn modified(&self) -> bool {
522 self.control || self.alt || self.shift || self.platform || self.function
523 }
524
525 pub fn secondary(&self, cx: &crate::App) -> bool {
530 if cx.platform_info().is_mac() {
531 self.platform
532 } else {
533 self.control
534 }
535 }
536
537 pub fn number_of_modifiers(&self) -> u8 {
539 self.control as u8
540 + self.alt as u8
541 + self.shift as u8
542 + self.platform as u8
543 + self.function as u8
544 }
545
546 pub fn none() -> Modifiers {
548 Default::default()
549 }
550
551 pub fn command() -> Modifiers {
553 Modifiers {
554 platform: true,
555 ..Default::default()
556 }
557 }
558
559 pub fn secondary_key(cx: &crate::App) -> Modifiers {
561 if cx.platform_info().is_mac() {
562 Modifiers {
563 platform: true,
564 ..Default::default()
565 }
566 } else {
567 Modifiers {
568 control: true,
569 ..Default::default()
570 }
571 }
572 }
573
574 pub fn windows() -> Modifiers {
576 Modifiers {
577 platform: true,
578 ..Default::default()
579 }
580 }
581
582 pub fn super_key() -> Modifiers {
584 Modifiers {
585 platform: true,
586 ..Default::default()
587 }
588 }
589
590 pub fn control() -> Modifiers {
592 Modifiers {
593 control: true,
594 ..Default::default()
595 }
596 }
597
598 pub fn alt() -> Modifiers {
600 Modifiers {
601 alt: true,
602 ..Default::default()
603 }
604 }
605
606 pub fn shift() -> Modifiers {
608 Modifiers {
609 shift: true,
610 ..Default::default()
611 }
612 }
613
614 pub fn function() -> Modifiers {
616 Modifiers {
617 function: true,
618 ..Default::default()
619 }
620 }
621
622 pub fn command_shift() -> Modifiers {
624 Modifiers {
625 shift: true,
626 platform: true,
627 ..Default::default()
628 }
629 }
630
631 pub fn control_shift() -> Modifiers {
633 Modifiers {
634 shift: true,
635 control: true,
636 ..Default::default()
637 }
638 }
639
640 pub fn is_subset_of(&self, other: &Modifiers) -> bool {
642 (*other & *self) == *self
643 }
644}
645
646impl std::ops::BitOr for Modifiers {
647 type Output = Self;
648
649 fn bitor(mut self, other: Self) -> Self::Output {
650 self |= other;
651 self
652 }
653}
654
655impl std::ops::BitOrAssign for Modifiers {
656 fn bitor_assign(&mut self, other: Self) {
657 self.control |= other.control;
658 self.alt |= other.alt;
659 self.shift |= other.shift;
660 self.platform |= other.platform;
661 self.function |= other.function;
662 }
663}
664
665impl std::ops::BitXor for Modifiers {
666 type Output = Self;
667 fn bitxor(mut self, rhs: Self) -> Self::Output {
668 self ^= rhs;
669 self
670 }
671}
672
673impl std::ops::BitXorAssign for Modifiers {
674 fn bitxor_assign(&mut self, other: Self) {
675 self.control ^= other.control;
676 self.alt ^= other.alt;
677 self.shift ^= other.shift;
678 self.platform ^= other.platform;
679 self.function ^= other.function;
680 }
681}
682
683impl std::ops::BitAnd for Modifiers {
684 type Output = Self;
685 fn bitand(mut self, rhs: Self) -> Self::Output {
686 self &= rhs;
687 self
688 }
689}
690
691impl std::ops::BitAndAssign for Modifiers {
692 fn bitand_assign(&mut self, other: Self) {
693 self.control &= other.control;
694 self.alt &= other.alt;
695 self.shift &= other.shift;
696 self.platform &= other.platform;
697 self.function &= other.function;
698 }
699}
700
701#[derive(Copy, Clone, Debug, Eq, PartialEq, Default, Serialize, Deserialize, Hash)]
703#[cfg_attr(feature = "schemars", derive(JsonSchema))]
704pub struct Capslock {
705 #[serde(default)]
707 pub on: bool,
708}
709
710impl AsKeystroke for Keystroke {
711 fn as_keystroke(&self) -> &Keystroke {
712 self
713 }
714}
715
716impl AsKeystroke for KeybindingKeystroke {
717 fn as_keystroke(&self) -> &Keystroke {
718 &self.inner
719 }
720}
721
722impl<T: AsKeystroke + ?Sized> AsKeystroke for &T {
723 fn as_keystroke(&self) -> &Keystroke {
724 (**self).as_keystroke()
725 }
726}
727
728fn display_modifiers(
729 modifiers: &Modifiers,
730 os: OperatingSystem,
731 f: &mut std::fmt::Formatter<'_>,
732) -> std::fmt::Result {
733 if modifiers.control {
734 f.write_str(if os == OperatingSystem::Mac {
735 "^"
736 } else {
737 "ctrl-"
738 })?;
739 }
740 if modifiers.alt {
741 f.write_str(if os == OperatingSystem::Mac {
742 "⌥"
743 } else {
744 "alt-"
745 })?;
746 }
747 if modifiers.platform {
748 f.write_str(match os {
749 OperatingSystem::Mac => "⌘",
750 OperatingSystem::Windows => "⊞",
751 OperatingSystem::Linux | OperatingSystem::FreeBsd => "❖",
752 OperatingSystem::Ios | OperatingSystem::Android | OperatingSystem::Unknown => "cmd-",
753 })?;
754 }
755 if modifiers.shift {
756 f.write_str(if os == OperatingSystem::Mac {
757 "⇧"
758 } else {
759 "shift-"
760 })?;
761 }
762 Ok(())
763}
764
765fn display_key(
766 key: &str,
767 os: OperatingSystem,
768 f: &mut std::fmt::Formatter<'_>,
769) -> std::fmt::Result {
770 let key = match key {
771 "backspace" if os == OperatingSystem::Mac => '⌫',
772 "up" if os == OperatingSystem::Mac => '↑',
773 "down" if os == OperatingSystem::Mac => '↓',
774 "left" if os == OperatingSystem::Mac => '←',
775 "right" if os == OperatingSystem::Mac => '→',
776 "tab" if os == OperatingSystem::Mac => '⇥',
777 "escape" if os == OperatingSystem::Mac => '⎋',
778 "shift" if os == OperatingSystem::Mac => '⇧',
779 "control" if os == OperatingSystem::Mac => '⌃',
780 "alt" if os == OperatingSystem::Mac => '⌥',
781 "platform" if os == OperatingSystem::Mac => '⌘',
782
783 key if key.len() == 1 => key.chars().next().unwrap().to_ascii_uppercase(),
784 key => return f.write_str(key),
785 };
786 f.write_char(key)
787}
788
789#[inline]
790fn unparse(modifiers: &Modifiers, key: &str, os: OperatingSystem) -> String {
791 let mut result = String::new();
792 if modifiers.function {
793 result.push_str("fn-");
794 }
795 if modifiers.control {
796 result.push_str("ctrl-");
797 }
798 if modifiers.alt {
799 result.push_str("alt-");
800 }
801 if modifiers.platform {
802 result.push_str(match os {
803 OperatingSystem::Windows => "win-",
804 OperatingSystem::Linux
805 | OperatingSystem::FreeBsd
806 | OperatingSystem::Android
807 | OperatingSystem::Unknown => "super-",
808 OperatingSystem::Mac | OperatingSystem::Ios => "cmd-",
809 });
810 }
811 if modifiers.shift {
812 result.push_str("shift-");
813 }
814 result.push_str(&key);
815 result
816}