Repository navigation
Expand file tree
/
Copy pathapp_settings.rs
More file actions
4387 lines (4053 loc) · 158 KB
/
Copy pathapp_settings.rs
File metadata and controls
4387 lines (4053 loc) · 158 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::fs;
use std::path::PathBuf;
#[cfg(test)]
use std::sync::atomic::AtomicU64;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, Ordering};
use std::sync::{OnceLock, RwLock};
use color_eyre::eyre::{Result, eyre};
#[cfg(target_os = "macos")]
use objc2::MainThreadMarker;
#[cfg(target_os = "macos")]
use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy};
use serde::{Deserialize, Serialize};
use crate::transcription_models::{TranscriptionModelId, TranscriptionSelection};
static RECORDING_DUCK_VOLUME: AtomicU32 = AtomicU32::new(0.2_f32.to_bits());
static RECORDING_AUDIO_BEHAVIOR: AtomicU8 = AtomicU8::new(0);
static DOUBLE_TAP_LOCK: AtomicBool = AtomicBool::new(true);
static DOUBLE_TAP_ONLY: AtomicBool = AtomicBool::new(false);
static SHORTCUT_TOGGLE: AtomicBool = AtomicBool::new(false);
static MEETINGS_ENABLED: AtomicBool = AtomicBool::new(false);
static PAUSE_BROWSER_MEDIA: AtomicBool = AtomicBool::new(false);
static HEX_MICROPHONE_ENABLED: AtomicBool = AtomicBool::new(false);
static MEETING_NOTES_ENABLED: AtomicBool = AtomicBool::new(true);
static MEETING_NOTES_OPENCODE: AtomicBool = AtomicBool::new(false);
static MEETING_INDICATOR_ENABLED: AtomicBool = AtomicBool::new(true);
static MEETING_INDICATOR_CORNER: AtomicU8 = AtomicU8::new(0);
static MEETING_RETENTION: AtomicU8 = AtomicU8::new(MeetingRetention::Forever as u8);
static MEETING_OUTPUT_FOLDER: OnceLock<RwLock<Option<PathBuf>>> = OnceLock::new();
static MEETING_PROVIDERS: OnceLock<RwLock<Vec<MeetingProviderChoice>>> = OnceLock::new();
static CALENDAR_SETTINGS: OnceLock<RwLock<CalendarSettings>> = OnceLock::new();
static MICROPHONE_POLICY: AtomicU8 = AtomicU8::new(0);
static CUSTOM_TRANSFORMATIONS_ENABLED: AtomicBool = AtomicBool::new(false);
static INDICATOR_POSITION: AtomicU8 = AtomicU8::new(0);
static HOTKEYS: OnceLock<RwLock<RuntimeHotkeys>> = OnceLock::new();
#[cfg(target_os = "macos")]
static PASTE_KEY_CODE: OnceLock<u16> = OnceLock::new();
static HOTKEY_CAPTURE_ACTIVE: AtomicBool = AtomicBool::new(false);
/// Distinct names for the tests' settings folders.
#[cfg(test)]
static SETTINGS_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
static TRANSCRIPTION_SELECTION: OnceLock<RwLock<RuntimeTranscriptionSelection>> = OnceLock::new();
static MICROPHONE_SELECTION: OnceLock<RwLock<RuntimeMicrophoneSelection>> = OnceLock::new();
#[cfg(hex_capture)]
static CAPTURE_SETTINGS: OnceLock<RwLock<CaptureSettings>> = OnceLock::new();
#[cfg(hex_capture)]
static SCRAWL_APP_RUNNING: AtomicBool = AtomicBool::new(false);
#[cfg(hex_capture)]
static CAPTURE_ON: AtomicBool = AtomicBool::new(false);
/// [`CaptureSettings::capsule_flow`] for the capsule, without a lock.
#[cfg(hex_capture)]
static CAPSULE_FLOW: AtomicU8 = AtomicU8::new(0);
#[derive(Default)]
struct RuntimeTranscriptionSelection {
revision: u64,
selection: TranscriptionSelection,
}
#[derive(Default)]
struct RuntimeMicrophoneSelection {
revision: u64,
device: Option<String>,
}
pub const SHIFT_KEY_MASK: u64 = 1 << 17;
pub const CONTROL_KEY_MASK: u64 = 1 << 18;
pub const OPTION_KEY_MASK: u64 = 1 << 19;
pub const COMMAND_KEY_MASK: u64 = 1 << 20;
pub const FUNCTION_KEY_MASK: u64 = 1 << 23;
pub const HOTKEY_MODIFIERS_MASK: u64 =
SHIFT_KEY_MASK | CONTROL_KEY_MASK | OPTION_KEY_MASK | COMMAND_KEY_MASK | FUNCTION_KEY_MASK;
pub const LEFT_CONTROL_MASK: u64 = 0x0000_0001;
pub const LEFT_SHIFT_MASK: u64 = 0x0000_0002;
pub const RIGHT_SHIFT_MASK: u64 = 0x0000_0004;
pub const LEFT_COMMAND_MASK: u64 = 0x0000_0008;
pub const RIGHT_COMMAND_MASK: u64 = 0x0000_0010;
pub const LEFT_OPTION_MASK: u64 = 0x0000_0020;
pub const RIGHT_OPTION_MASK: u64 = 0x0000_0040;
pub const RIGHT_CONTROL_MASK: u64 = 0x0000_2000;
/// Which of a modifier's keys a shortcut holds. `Either` is one key on
/// either side (or both, as before chords); `Both` is the left and the
/// right key together, such as both Options.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ModifierSide {
Left,
Right,
#[default]
Either,
Both,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct HotkeyModifiers {
#[serde(deserialize_with = "deserialize_modifier_side")]
pub control: Option<ModifierSide>,
#[serde(deserialize_with = "deserialize_modifier_side")]
pub option: Option<ModifierSide>,
#[serde(deserialize_with = "deserialize_modifier_side")]
pub shift: Option<ModifierSide>,
#[serde(deserialize_with = "deserialize_modifier_side")]
pub command: Option<ModifierSide>,
pub function: bool,
}
fn deserialize_modifier_side<'de, D>(
deserializer: D,
) -> std::result::Result<Option<ModifierSide>, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
let value = Option::<serde_json::Value>::deserialize(deserializer)?;
match value {
None | Some(serde_json::Value::Bool(false)) => Ok(None),
Some(serde_json::Value::Bool(true)) => Ok(Some(ModifierSide::Either)),
Some(serde_json::Value::String(value)) => {
serde_json::from_value(serde_json::Value::String(value))
.map(Some)
.map_err(D::Error::custom)
}
Some(_) => Err(D::Error::custom(
"modifier side must be left, right, either, or null",
)),
}
}
impl HotkeyModifiers {
pub const fn option() -> Self {
Self {
option: Some(ModifierSide::Either),
control: None,
shift: None,
command: None,
function: false,
}
}
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub const fn control() -> Self {
Self {
control: Some(ModifierSide::Either),
option: None,
shift: None,
command: None,
function: false,
}
}
#[cfg_attr(target_os = "macos", allow(dead_code))]
pub const fn control_option() -> Self {
Self {
control: Some(ModifierSide::Either),
option: Some(ModifierSide::Either),
shift: None,
command: None,
function: false,
}
}
pub const fn option_command() -> Self {
Self {
option: Some(ModifierSide::Either),
command: Some(ModifierSide::Either),
control: None,
shift: None,
function: false,
}
}
pub const fn is_empty(self) -> bool {
self.control.is_none()
&& self.option.is_none()
&& self.shift.is_none()
&& self.command.is_none()
&& !self.function
}
/// How many keys the modifiers hold: both sides of one count as two.
pub const fn count(self) -> u8 {
side_count(self.control)
+ side_count(self.option)
+ side_count(self.shift)
+ side_count(self.command)
+ self.function as u8
}
/// The sides a recorder keeps from the modifiers held at a modifier-only
/// chord's peak: a lone modifier keeps its side (the side picker can
/// widen it), both sides of one stay both (both Options), and every
/// other side becomes either, so ⌥⌘ works from either side.
pub fn recorded_sides(self) -> Self {
if self.count() == 1 {
return self;
}
let keep_both = |side: Option<ModifierSide>| match side {
Some(ModifierSide::Both) => Some(ModifierSide::Both),
side => either_side(side),
};
Self {
control: keep_both(self.control),
option: keep_both(self.option),
shift: keep_both(self.shift),
command: keep_both(self.command),
function: self.function,
}
}
pub const fn without_side_constraints(self) -> Self {
Self {
control: either_side(self.control),
option: either_side(self.option),
shift: either_side(self.shift),
command: either_side(self.command),
function: self.function,
}
}
/// Every key `required` names is among these held ones; others may be
/// held too.
fn contains(self, required: Self) -> bool {
side_covers(self.control, required.control)
&& side_covers(self.option, required.option)
&& side_covers(self.shift, required.shift)
&& side_covers(self.command, required.command)
&& (!required.function || self.function)
}
/// Exactly the keys `required` names are held: no other modifier, and
/// no other side of one it names.
fn holds_exactly(self, required: Self) -> bool {
side_exact(self.control, required.control)
&& side_exact(self.option, required.option)
&& side_exact(self.shift, required.shift)
&& side_exact(self.command, required.command)
&& self.function == required.function
}
/// One keycap per modifier key, so both Options show as two.
fn sided(self) -> impl Iterator<Item = (Modifier, ModifierSide)> {
let function = self.function.then_some(ModifierSide::Either);
[
(Modifier::Function, function),
(Modifier::Control, self.control),
(Modifier::Option, self.option),
(Modifier::Shift, self.shift),
(Modifier::Command, self.command),
]
.into_iter()
.flat_map(|(modifier, side)| {
let sides: &[ModifierSide] = match side {
None => &[],
Some(ModifierSide::Both) => &[ModifierSide::Left, ModifierSide::Right],
Some(ModifierSide::Left) => &[ModifierSide::Left],
Some(ModifierSide::Right) => &[ModifierSide::Right],
Some(ModifierSide::Either) => &[ModifierSide::Either],
};
sides.iter().map(move |side| (modifier, *side))
})
}
#[cfg(target_os = "macos")]
fn keycaps(self) -> impl Iterator<Item = &'static str> {
self.sided()
.map(|(modifier, side)| side_keycap(side, modifier.keycap()))
}
/// Each modifier key's keycap and the side it must be pressed on.
/// Linux binds no side, so its keycaps never name one.
fn sided_keycaps(self) -> impl Iterator<Item = (&'static str, ModifierSide)> {
self.sided().map(|(modifier, side)| {
let side = if cfg!(target_os = "linux") {
ModifierSide::Either
} else {
side
};
(modifier.keycap(), side)
})
}
#[cfg(not(target_os = "macos"))]
fn keycaps(self) -> impl Iterator<Item = &'static str> {
self.sided_keycaps().map(|(label, _)| label)
}
}
/// One modifier, as a chord names it.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Modifier {
Function,
Control,
Option,
Shift,
Command,
}
impl Modifier {
/// The Mac's symbols; Windows names Command the Windows key and Option
/// Alt, and Linux names them Super and Alt.
pub const fn keycap(self) -> &'static str {
match self {
Self::Function => "fn",
#[cfg(target_os = "macos")]
Self::Control => "⌃",
#[cfg(target_os = "macos")]
Self::Option => "⌥",
#[cfg(target_os = "macos")]
Self::Shift => "⇧",
#[cfg(target_os = "macos")]
Self::Command => "⌘",
#[cfg(not(target_os = "macos"))]
Self::Control => "Ctrl",
#[cfg(not(target_os = "macos"))]
Self::Option => "Alt",
#[cfg(not(target_os = "macos"))]
Self::Shift => "Shift",
#[cfg(target_os = "windows")]
Self::Command => "Win",
#[cfg(target_os = "linux")]
Self::Command => "Super",
}
}
}
const fn side_count(side: Option<ModifierSide>) -> u8 {
match side {
None => 0,
Some(ModifierSide::Both) => 2,
Some(_) => 1,
}
}
const fn either_side(side: Option<ModifierSide>) -> Option<ModifierSide> {
match side {
Some(_) => Some(ModifierSide::Either),
None => None,
}
}
/// `held` is what the keyboard reports for one modifier: a side, `Both`,
/// or `Either` for input that names no side. `Either` asks for any key of
/// it, held alone or with its twin.
fn side_covers(held: Option<ModifierSide>, required: Option<ModifierSide>) -> bool {
match (held, required) {
(_, None) => true,
(None, Some(_)) => false,
(Some(_), Some(ModifierSide::Either)) => true,
(Some(ModifierSide::Both), Some(ModifierSide::Left | ModifierSide::Right)) => true,
(Some(held), Some(required)) => held == required,
}
}
fn side_exact(held: Option<ModifierSide>, required: Option<ModifierSide>) -> bool {
match (held, required) {
(None, None) => true,
(Some(_), Some(ModifierSide::Either)) => true,
(Some(held), Some(required)) => held == required,
_ => false,
}
}
#[cfg(target_os = "macos")]
fn side_keycap(side: ModifierSide, symbol: &'static str) -> &'static str {
match (side, symbol) {
(ModifierSide::Left, "⌃") => "L⌃",
(ModifierSide::Right, "⌃") => "R⌃",
(ModifierSide::Left, "⌥") => "L⌥",
(ModifierSide::Right, "⌥") => "R⌥",
(ModifierSide::Left, "⇧") => "L⇧",
(ModifierSide::Right, "⇧") => "R⇧",
(ModifierSide::Left, "⌘") => "L⌘",
(ModifierSide::Right, "⌘") => "R⌘",
_ => symbol,
}
}
/// A shortcut's non-modifier key. macOS identifies it by `code`, the virtual
/// key code resolved through the active keyboard layout. Windows and Linux
/// identify it by `label`, the key's name ("Space", "V", "F12", "PageUp"),
/// which their input layers translate to virtual keys, X11 keysyms, or the
/// shortcuts portal's key names; `code` is zero there. A settings file never moves between OSes.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct HotkeyKey {
pub code: u16,
pub label: String,
}
/// Reserved input codes for the 32 mouse buttons CoreGraphics can report.
const MOUSE_INPUT_CODES: std::ops::Range<u16> = 0x8000..0x8020;
impl HotkeyKey {
/// macOS mouse buttons occupy a separate input-code range, beyond every
/// native keyboard code used by macOS. A shared trigger code lets keyboard
/// and mouse bindings use the same hold, toggle, conflict and persistence
/// rules. UI labels are one-based (Mouse 1 = left, Mouse 2 = right, Mouse 3 = middle).
pub fn mouse(button: u16) -> Option<Self> {
Self::mouse_code(button).map(|code| Self {
code,
label: format!("Mouse {}", button + 1),
})
}
/// Allocation-free encoding for the event tap.
pub fn mouse_code(button: u16) -> Option<u16> {
(button < 32).then(|| MOUSE_INPUT_CODES.start + button)
}
#[cfg(target_os = "macos")]
pub fn mouse_button(code: u16) -> Option<u16> {
code.checked_sub(MOUSE_INPUT_CODES.start)
.filter(|button| *button < 32)
}
pub fn is_mouse(&self) -> bool {
MOUSE_INPUT_CODES.contains(&self.code)
}
/// A key identified by name on Windows and Linux.
#[cfg_attr(target_os = "macos", allow(dead_code))]
pub fn named(name: &str) -> Self {
if let Some(button) = Self::mouse_number(name) {
return Self::mouse(button - 1).expect("validated mouse number");
}
Self {
code: 0,
label: key_label(name),
}
}
/// The lowercase key name Windows and Linux input layers resolve.
#[cfg_attr(target_os = "macos", allow(dead_code))]
pub fn name(&self) -> String {
if self.is_mouse() {
return format!("mouse{}", self.code - MOUSE_INPUT_CODES.start + 1);
}
self.label.to_ascii_lowercase()
}
/// One-based logical button number shared by every platform.
#[cfg_attr(target_os = "macos", allow(dead_code))]
pub fn mouse_number(name: &str) -> Option<u16> {
name.to_ascii_lowercase()
.strip_prefix("mouse")?
.trim()
.parse::<u16>()
.ok()
.filter(|number| (1..=32).contains(number))
}
fn same_key(&self, other: &Self) -> bool {
if cfg!(target_os = "macos") {
self.code == other.code
} else {
self.label.eq_ignore_ascii_case(&other.label)
}
}
}
/// The keycap label for a key name: one character in uppercase, otherwise
/// the name with a leading capital ("space" -> "Space", "f12" -> "F12").
#[cfg_attr(target_os = "macos", allow(dead_code))]
fn key_label(name: &str) -> String {
let name = name.trim();
let mut characters = name.chars();
match characters.next() {
Some(first) if name.chars().count() == 1 => first.to_uppercase().collect(),
Some(first) => first.to_uppercase().chain(characters).collect(),
None => String::new(),
}
}
/// A shortcut as a chord: the set of keys held together, any order and
/// nothing else. Modifiers name their side (or either), and at most one
/// other key or mouse button joins them. Settings store it as `keys`
/// ([`ChordKey`]); files from before chords stored `modifiers` and `key`,
/// which load as the same chord and are written back as `keys` once.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HotkeyBinding {
pub modifiers: HotkeyModifiers,
pub key: Option<HotkeyKey>,
}
/// One key of a stored chord: a modifier with its side, or a key.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum ChordKey {
Modifier {
modifier: ChordModifier,
#[serde(default, skip_serializing_if = "Option::is_none")]
side: Option<ChordSide>,
},
Key(HotkeyKey),
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ChordModifier {
Fn,
Control,
Option,
Shift,
Command,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ChordSide {
Left,
Right,
Any,
}
#[derive(Deserialize, Serialize)]
struct StoredChord {
keys: Vec<ChordKey>,
}
/// The shape settings stored before chords.
#[derive(Deserialize)]
struct LegacyBinding {
#[serde(default = "legacy_default_modifiers")]
modifiers: HotkeyModifiers,
#[serde(default = "legacy_default_key")]
key: Option<HotkeyKey>,
}
fn legacy_default_modifiers() -> HotkeyModifiers {
HotkeyBinding::default().modifiers
}
fn legacy_default_key() -> Option<HotkeyKey> {
HotkeyBinding::default().key
}
impl HotkeyBinding {
/// The chord's keys in a fixed order: fn, Control, Option, Shift,
/// Command (left before right), then the key.
pub fn chord_keys(&self) -> Vec<ChordKey> {
let mut keys = Vec::new();
if self.modifiers.function {
keys.push(ChordKey::Modifier {
modifier: ChordModifier::Fn,
side: None,
});
}
for (modifier, side) in [
(ChordModifier::Control, self.modifiers.control),
(ChordModifier::Option, self.modifiers.option),
(ChordModifier::Shift, self.modifiers.shift),
(ChordModifier::Command, self.modifiers.command),
] {
let sides: &[ChordSide] = match side {
None => &[],
Some(ModifierSide::Left) => &[ChordSide::Left],
Some(ModifierSide::Right) => &[ChordSide::Right],
Some(ModifierSide::Either) => &[ChordSide::Any],
Some(ModifierSide::Both) => &[ChordSide::Left, ChordSide::Right],
};
keys.extend(sides.iter().map(|side| ChordKey::Modifier {
modifier,
side: Some(*side),
}));
}
keys.extend(self.key.clone().map(ChordKey::Key));
keys
}
/// The chord of `keys`, which may come in any order. Both sides of a
/// modifier are `Both`; a key twice, a side beside "any", or a second
/// key besides modifiers is refused.
pub fn from_chord_keys(keys: impl IntoIterator<Item = ChordKey>) -> Result<Self, String> {
let mut binding = Self {
modifiers: HotkeyModifiers::default(),
key: None,
};
for key in keys {
match key {
ChordKey::Key(key) => {
if binding.key.is_some() {
return Err("a shortcut holds at most one key besides modifiers".into());
}
binding.key = Some(key);
}
ChordKey::Modifier {
modifier: ChordModifier::Fn,
side,
} => {
if binding.modifiers.function {
return Err("fn appears twice".into());
}
if side.is_some_and(|side| side != ChordSide::Any) {
return Err("fn has no side".into());
}
binding.modifiers.function = true;
}
ChordKey::Modifier { modifier, side } => {
let slot = match modifier {
ChordModifier::Control => &mut binding.modifiers.control,
ChordModifier::Option => &mut binding.modifiers.option,
ChordModifier::Shift => &mut binding.modifiers.shift,
ChordModifier::Command => &mut binding.modifiers.command,
ChordModifier::Fn => unreachable!("fn is matched above"),
};
let side = match side.unwrap_or(ChordSide::Any) {
ChordSide::Left => ModifierSide::Left,
ChordSide::Right => ModifierSide::Right,
ChordSide::Any => ModifierSide::Either,
};
*slot = Some(match (*slot, side) {
(None, side) => side,
(Some(ModifierSide::Left), ModifierSide::Right)
| (Some(ModifierSide::Right), ModifierSide::Left) => ModifierSide::Both,
_ => return Err(format!("{modifier:?} appears twice").to_lowercase()),
});
}
}
}
Ok(binding)
}
}
impl Serialize for HotkeyBinding {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
StoredChord {
keys: self.chord_keys(),
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for HotkeyBinding {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
use serde::de::Error;
let value = serde_json::Value::deserialize(deserializer)?;
if value.get("keys").is_some() {
let chord: StoredChord = serde_json::from_value(value).map_err(D::Error::custom)?;
return Self::from_chord_keys(chord.keys).map_err(D::Error::custom);
}
let legacy: LegacyBinding = serde_json::from_value(value).map_err(D::Error::custom)?;
Ok(Self {
modifiers: legacy.modifiers,
key: legacy.key,
})
}
}
impl Default for HotkeyBinding {
/// Option on macOS, Ctrl+Space on Windows, Alt+Space on Linux.
fn default() -> Self {
#[cfg(target_os = "macos")]
let binding = Self {
modifiers: HotkeyModifiers::option(),
key: None,
};
#[cfg(target_os = "windows")]
let binding = Self::chord(HotkeyModifiers::control(), "space");
#[cfg(target_os = "linux")]
let binding = Self::chord(HotkeyModifiers::option(), "space");
binding
}
}
impl HotkeyBinding {
/// Modifiers plus a key identified by name (Windows and Linux).
#[cfg_attr(target_os = "macos", allow(dead_code))]
fn chord(modifiers: HotkeyModifiers, key: &str) -> Self {
Self {
modifiers,
key: Some(HotkeyKey::named(key)),
}
}
/// Option-Shift-V on macOS; Ctrl+Alt+V elsewhere.
pub fn paste_last_default() -> Self {
#[cfg(target_os = "macos")]
let binding = Self {
modifiers: HotkeyModifiers {
option: Some(ModifierSide::Either),
shift: Some(ModifierSide::Either),
..Default::default()
},
key: Some(HotkeyKey {
code: paste_key_code(),
label: "V".into(),
}),
};
#[cfg(not(target_os = "macos"))]
let binding = Self::chord(HotkeyModifiers::control_option(), "v");
binding
}
/// Option-Shift-S, Scrawl's capture shortcut; F9 on Linux. Annotate's
/// one key is held to draw while the other hand moves the mouse, so on
/// Linux it's a single key one hand holds easily: F9 is free in Hex's
/// defaults (Alt+Space, Ctrl+Alt+V) and in the common desktops', where
/// F10 opens GTK's menu bar, F11 is full screen and F12 is often a
/// dropdown terminal.
#[cfg(hex_capture)]
pub fn capture_default() -> Self {
#[cfg(target_os = "macos")]
let binding = Self {
modifiers: HotkeyModifiers {
option: Some(ModifierSide::Either),
shift: Some(ModifierSide::Either),
..Default::default()
},
key: Some(HotkeyKey {
code: layout_key_code('s').unwrap_or(1),
label: "S".into(),
}),
};
#[cfg(not(target_os = "macos"))]
let binding = Self::chord(HotkeyModifiers::default(), "f9");
binding
}
pub fn paste_meeting_default() -> Self {
Self {
modifiers: HotkeyModifiers {
option: Some(ModifierSide::Either),
control: Some(ModifierSide::Either),
..Default::default()
},
key: Some(HotkeyKey {
code: paste_key_code(),
label: "V".into(),
}),
}
}
}
/// Scrawl's record shortcut from its app's `{key_code, carbon_modifiers,
/// label}` file; a shortcut without a modifier is not Scrawl's.
#[cfg(hex_capture)]
fn scrawl_shortcut(bytes: &[u8]) -> Option<HotkeyBinding> {
#[derive(Deserialize)]
struct Shortcut {
key_code: u16,
carbon_modifiers: u32,
label: String,
}
const COMMAND: u32 = 1 << 8;
const SHIFT: u32 = 1 << 9;
const OPTION: u32 = 1 << 11;
const CONTROL: u32 = 1 << 12;
let shortcut: Shortcut = serde_json::from_slice(bytes).ok()?;
let held = |mask: u32| (shortcut.carbon_modifiers & mask != 0).then_some(ModifierSide::Either);
let modifiers = HotkeyModifiers {
control: held(CONTROL),
option: held(OPTION),
shift: held(SHIFT),
command: held(COMMAND),
function: false,
};
let label: String = shortcut
.label
.chars()
.filter(|c| !matches!(c, '⌃' | '⌥' | '⇧' | '⌘'))
.collect();
(!modifiers.is_empty() && !label.is_empty()).then_some(HotkeyBinding {
modifiers,
key: Some(HotkeyKey {
code: shortcut.key_code,
label,
}),
})
}
#[cfg(target_os = "macos")]
fn paste_key_code() -> u16 {
*PASTE_KEY_CODE.get_or_init(|| layout_key_code('v').unwrap_or(9))
}
/// The active layout's key for `character`. GUI startup snapshots the layout
/// on the main thread; unit tests run on worker threads, where reaching TIS is
/// unsupported, so they resolve against the ANSI layout instead.
#[cfg(target_os = "macos")]
fn layout_key_code(character: char) -> Option<u16> {
if cfg!(test) {
return match character {
'e' => Some(14),
's' => Some(1),
'v' => Some(9),
_ => None,
};
}
crate::keyboard::key_code_for(character).ok()
}
#[cfg(not(target_os = "macos"))]
fn paste_key_code() -> u16 {
0
}
impl HotkeyBinding {
pub fn keycaps(&self) -> Vec<String> {
self.modifiers
.keycaps()
.map(str::to_string)
.chain(self.key.iter().map(|key| key.label.clone()))
.collect()
}
/// Each keycap with the side it must be pressed on: `Either` for the
/// key, and for every modifier but on macOS.
pub fn sided_keycaps(&self) -> Vec<(String, ModifierSide)> {
self.modifiers
.sided_keycaps()
.map(|(label, side)| (label.to_string(), side))
.chain(
self.key
.iter()
.map(|key| (key.label.clone(), ModifierSide::Either)),
)
.collect()
}
/// A left click (Mouse 1) with no modifier. Matching it would swallow
/// every click, Settings' own included, so no shortcut may be one.
pub fn is_bare_primary_click(&self) -> bool {
self.modifiers.is_empty()
&& self.key.as_ref().is_some_and(|key| {
key.code == MOUSE_INPUT_CODES.start
|| HotkeyKey::mouse_number(&key.label) == Some(1)
})
}
pub fn runtime(&self) -> RuntimeHotkey {
RuntimeHotkey {
modifiers: self.modifiers,
key_code: self.key.as_ref().map(|key| key.code),
}
}
pub fn overlaps(&self, other: &Self) -> bool {
let same_key = match (&self.key, &other.key) {
(Some(left), Some(right)) => left.same_key(right),
(None, None) => true,
_ => false,
};
same_key && modifiers_overlap(self.modifiers, other.modifiers)
}
/// The side of a chord that is one modifier key, such as Right Option;
/// none for every other chord, whose keys name their own sides.
pub fn standalone_side(&self) -> Option<ModifierSide> {
if self.key.is_some() || self.modifiers.function || self.modifiers.count() != 1 {
return None;
}
[
self.modifiers.control,
self.modifiers.option,
self.modifiers.shift,
self.modifiers.command,
]
.into_iter()
.flatten()
.next()
}
/// Moves a one-modifier chord to `side`; other chords are unchanged.
pub fn set_standalone_side(&mut self, side: ModifierSide) {
if self.standalone_side().is_none() || side == ModifierSide::Both {
return;
}
for current in [
&mut self.modifiers.control,
&mut self.modifiers.option,
&mut self.modifiers.shift,
&mut self.modifiers.command,
] {
if current.is_some() {
*current = Some(side);
}
}
}
}
fn modifiers_overlap(left: HotkeyModifiers, right: HotkeyModifiers) -> bool {
modifier_overlap(left.control, right.control)
&& modifier_overlap(left.option, right.option)
&& modifier_overlap(left.shift, right.shift)
&& modifier_overlap(left.command, right.command)
&& left.function == right.function
}
/// Whether one press could match both: `Either` takes any side, `Both`
/// only both.
fn modifier_overlap(left: Option<ModifierSide>, right: Option<ModifierSide>) -> bool {
match (left, right) {
(None, None) => true,
(Some(ModifierSide::Either), Some(_)) | (Some(_), Some(ModifierSide::Either)) => true,
(Some(left), Some(right)) => left == right,
_ => false,
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct RuntimeHotkey {
pub modifiers: HotkeyModifiers,
pub key_code: Option<u16>,
}
impl RuntimeHotkey {
pub fn is_empty(self) -> bool {
self.modifiers.is_empty() && self.key_code.is_none()
}
/// Exactly the binding's modifier keys are down: a sided binding wants
/// its side alone, and both sides of a modifier only for `Both`.
pub fn exact_modifiers(self, flags: u64) -> bool {
let flags = self.without_implied_function(flags);
modifiers_from_flags(flags).holds_exactly(self.modifiers)
}
/// macOS marks every press of a function, arrow, or navigation key with
/// SecondaryFn whether or not Fn is held, and the recorder leaves it out
/// of such a binding. Only for a binding on one of those keys that does
/// not ask for Fn is the flag ignored; Fn is never stripped otherwise.
fn without_implied_function(self, flags: u64) -> u64 {
if cfg!(target_os = "macos")
&& !self.modifiers.function
&& self.key_code.is_some_and(key_reports_function_flag)
{
flags & !FUNCTION_KEY_MASK
} else {
flags
}
}
/// Every modifier key of the binding is down, whatever else is.
pub fn required_modifiers_down(self, flags: u64) -> bool {
modifiers_from_flags(flags).contains(self.modifiers)
}
/// The device flags of each modifier the binding holds on both sides,
/// whose two keys must go down together (`suppression`).
pub fn both_sides_masks(self) -> impl Iterator<Item = (u64, u64)> {
[
(
self.modifiers.control,
LEFT_CONTROL_MASK,
RIGHT_CONTROL_MASK,
),
(self.modifiers.option, LEFT_OPTION_MASK, RIGHT_OPTION_MASK),
(self.modifiers.shift, LEFT_SHIFT_MASK, RIGHT_SHIFT_MASK),
(
self.modifiers.command,
LEFT_COMMAND_MASK,
RIGHT_COMMAND_MASK,
),
]
.into_iter()
.filter(|(side, ..)| *side == Some(ModifierSide::Both))
.map(|(_, left, right)| (left, right))
}
pub fn matches_key_press(self, code: u16, flags: u64) -> bool {
self.key_code == Some(code) && self.exact_modifiers(flags)
}
}
/// macOS virtual key codes whose events always carry SecondaryFn: F1–F20,
/// the arrows, Home, End, Page Up, Page Down, Forward Delete, and Help.
fn key_reports_function_flag(code: u16) -> bool {
const CODES: [u16; 30] = [
122, 120, 99, 118, 96, 97, 98, 100, 101, 109, 103, 111, 105, 107, 113, 106, 64, 79, 80, 90,
123, 124, 125, 126, 115, 119, 116, 121, 117, 114,
];
CODES.contains(&code)
}
pub fn modifiers_from_flags(flags: u64) -> HotkeyModifiers {
HotkeyModifiers {
control: side_from_flags(
flags,
CONTROL_KEY_MASK,
LEFT_CONTROL_MASK,
RIGHT_CONTROL_MASK,
),
option: side_from_flags(flags, OPTION_KEY_MASK, LEFT_OPTION_MASK, RIGHT_OPTION_MASK),
shift: side_from_flags(flags, SHIFT_KEY_MASK, LEFT_SHIFT_MASK, RIGHT_SHIFT_MASK),
command: side_from_flags(
flags,
COMMAND_KEY_MASK,
LEFT_COMMAND_MASK,
RIGHT_COMMAND_MASK,
),
function: flags & FUNCTION_KEY_MASK != 0,
}
}