Repository navigation
Expand file tree
/
Copy pathsettings.rs
More file actions
1474 lines (1421 loc) · 50.7 KB
/
Copy pathsettings.rs
File metadata and controls
1474 lines (1421 loc) · 50.7 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
//! The `hex settings` registry: one key per persisted setting, named by its
//! dotted path in `settings.json`, with the same rules and side effects the
//! window applies when you change it there.
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::ControlError;
use crate::app_settings::{
AppSettings, CALENDAR_LEAD_MINUTES, HotkeyBinding, HotkeyKey, HotkeyModifiers, HotkeySlot,
ModifierSide,
};
/// One setting as `hex settings get` reports it.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct SettingValue {
pub key: String,
pub value: Value,
/// bool, number, integer, text, choice, shortcut, path, or json.
pub kind: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub choices: Vec<String>,
pub writable: bool,
pub about: String,
/// False where this OS's Hex lacks what the setting needs ([`needs`]):
/// it is kept, but does nothing here and `set` refuses it.
#[serde(default = "available")]
pub available: bool,
}
fn available() -> bool {
true
}
#[derive(Clone, Copy, Debug)]
enum Kind {
Bool,
Number {
min: f64,
max: f64,
},
#[cfg_attr(not(hex_capture), allow(dead_code))]
Integer {
min: u64,
max: u64,
},
Choice(&'static [&'static str]),
Text,
Shortcut(HotkeySlot),
Path,
Json,
}
impl Kind {
fn name(self) -> &'static str {
match self {
Self::Bool => "bool",
Self::Number { .. } => "number",
Self::Integer { .. } => "integer",
Self::Choice(_) => "choice",
Self::Text => "text",
Self::Shortcut(_) => "shortcut",
Self::Path => "path",
Self::Json => "json",
}
}
}
struct Key {
key: &'static str,
kind: Kind,
/// `none` clears it.
optional: bool,
/// Why it can't be set here, if it can't.
read_only: Option<&'static str>,
about: &'static str,
}
const fn key(key: &'static str, kind: Kind, about: &'static str) -> Key {
Key {
key,
kind,
optional: false,
read_only: None,
about,
}
}
const fn optional(key: &'static str, kind: Kind, about: &'static str) -> Key {
Key {
key,
kind,
optional: true,
read_only: None,
about,
}
}
const fn read_only(key: &'static str, kind: Kind, about: &'static str, why: &'static str) -> Key {
Key {
key,
kind,
optional: false,
read_only: Some(why),
about,
}
}
const UNIT: Kind = Kind::Number { min: 0.0, max: 1.0 };
const MODEL_CHANGE: &str = "change the transcription model with `hex model use`";
/// Choice keys whose values are numbers in settings.json.
const NUMERIC_CHOICES: [&str; 2] = ["meetings.calendar.lead_minutes", "labs.unload_idle_minutes"];
const KEYS: &[Key] = &[
key(
"keyboard_model_switching.enabled",
Kind::Bool,
"Labs: switch the model when the keyboard input source changes (macOS, Windows, X11)",
),
key(
"keyboard_model_switching.mappings",
Kind::Json,
"Input-source IDs mapped to a model and language; absent sources don't switch (macOS, Windows, X11)",
),
key(
"release_microphone_while_idle",
Kind::Bool,
"Release the microphone between dictations",
),
key(
"sound_effects",
Kind::Bool,
"Play recording, cancellation, and error tones",
),
key(
"sound_effect_volume",
UNIT,
"Tone volume from 0 to 1; 0 turns tones off",
),
key(
"sound_theme",
Kind::Choice(&[
"signature",
"classic",
"click",
"soft",
"wood",
"analog",
"thock",
]),
"Which sounds play; classic, Hex's original tones, is the default",
),
optional(
"microphone",
Kind::Text,
"Microphone by name; system-default (or none) follows the system's default input",
),
key(
"avoid_bluetooth_microphone",
Kind::Bool,
"System default records from the built-in or another wired microphone, not a Bluetooth headset's",
),
key(
"recording_audio_behavior",
Kind::Choice(&["mute", "pause_media", "do_nothing", "duck"]),
"What other audio does while you dictate",
),
key(
"recording_duck_volume",
UNIT,
"Fraction of original output volume while lowering audio, from 0 to 1",
),
key(
"pause_browser_media",
Kind::Bool,
"Labs: also pause a playing browser tab while dictating (macOS, with Pause media)",
),
key(
"double_tap_lock",
Kind::Bool,
"Double-tap the dictation shortcut to keep recording hands-free",
),
key(
"double_tap_only",
Kind::Bool,
"Only a double tap starts dictation (needs double_tap_lock and a key chord)",
),
key(
"shortcut_mode",
Kind::Choice(&["hold", "toggle"]),
"Hold the shortcut while speaking, or press once to start and again to finish",
),
key(
"dictation_hotkey",
Kind::Shortcut(HotkeySlot::Dictation),
"The dictation shortcut",
),
optional(
"paste_last_hotkey",
Kind::Shortcut(HotkeySlot::PasteLast),
"The paste-last-dictation shortcut; none turns it off",
),
optional(
"raw_dictation_hotkey",
Kind::Shortcut(HotkeySlot::RawDictation),
"Dictate without processing: dictates and pastes the words as heard, skipping \
the Output steps; none (the default) turns it off",
),
optional(
"second_dictation_hotkey",
Kind::Shortcut(HotkeySlot::SecondDictation),
"Labs: another shortcut that dictates like dictation_hotkey, such as a key on an \
external keyboard (macOS, with labs.second_dictation_shortcut); none (the default) \
turns it off",
),
key(
"show_dock_icon",
Kind::Bool,
"Keep Hex in the Dock when Settings is closed (macOS)",
),
read_only(
"transcription.model",
Kind::Text,
"The dictation model",
MODEL_CHANGE,
),
read_only(
"transcription.language",
Kind::Text,
"The dictation language",
MODEL_CHANGE,
),
key(
"transcription.recognition_hints",
Kind::Text,
"Names and terms the model should expect (models that support hints)",
),
read_only(
"transcription_recents",
Kind::Json,
"Recently used models, each with its language and hints",
"Hex records these as you switch models",
),
key(
"vocabulary_boost",
Kind::Choice(&["off", "light", "normal", "strong"]),
"How readily transcription swaps heard words for a vocabulary term",
),
key(
"dictation_processing.default_mode",
Kind::Json,
"The Global mode: replacements, transformations, and rewriting",
),
key(
"dictation_processing.modes",
Kind::Json,
"Modes for specific apps and websites, as a JSON array",
),
key(
"history_retention",
Kind::Choice(&["off", "day", "week", "month", "forever"]),
"How long dictation history is kept",
),
key(
"labs.live_text",
Kind::Bool,
"Labs: provisional words beside the HUD while dictating",
),
key(
"labs.live_chapters",
Kind::Bool,
"Labs: chapter meeting transcripts while recording",
),
key(
"labs.playground",
Kind::Bool,
"Labs: the scene and story browser in the window",
),
key(
"labs.vocabulary_biasing",
Kind::Bool,
"Labs: bias Parakeet transcription toward the vocabulary",
),
key(
"labs.mouse_shortcuts",
Kind::Bool,
"Labs: record mouse buttons as shortcuts (macOS)",
),
key(
"labs.unload_idle",
Kind::Bool,
"Labs: unload the speech model when idle, freeing its memory",
),
key(
"labs.unload_idle_minutes",
Kind::Choice(&["5", "15", "30", "60"]),
"Minutes unused before Labs › Unload model when idle unloads the model",
),
key(
"labs.restore_shortcut_default",
Kind::Bool,
"Labs: offer Restore default beside the Paste last dictation shortcut",
),
key(
"labs.keep_on_clipboard",
Kind::Bool,
"Labs: leave the dictation on the clipboard after pasting instead of restoring what was there (macOS)",
),
key(
"labs.copy_only",
Kind::Bool,
"Labs: put the dictation on the clipboard instead of pasting it (macOS)",
),
key(
"labs.spoken_formatting",
Kind::Bool,
"Labs: turn spoken \"new line\", \"new paragraph\", and \"open/close quote\" into line breaks and quotation marks",
),
key(
"labs.filler_words",
Kind::Bool,
"Labs: remove filler words such as um and uh from dictations, without an AI model",
),
key(
"labs.subtitle_export",
Kind::Bool,
"Labs: export meeting transcripts as SRT or VTT subtitles with hex meetings show --srt|--vtt",
),
key(
"labs.second_dictation_shortcut",
Kind::Bool,
"Labs: second_dictation_hotkey dictates like the dictation shortcut (macOS)",
),
key(
"meetings.enabled",
Kind::Bool,
"Labs: Meetings (beta), call detection, recording, and transcripts",
),
optional(
"meetings.output_folder",
Kind::Path,
"Folder for meeting Markdown; none uses ~/Documents/Hex Meetings",
),
key(
"meetings.summarize_with_apple_intelligence",
Kind::Bool,
"Title and summarize meetings with Apple Intelligence",
),
key(
"meetings.summarize_with_opencode",
Kind::Bool,
"Title and summarize meetings with the OpenCode model (sends the transcript to it)",
),
key(
"meetings.show_recording_indicator",
Kind::Bool,
"Show the floating recording indicator during meetings",
),
key(
"meetings.recording_indicator_corner",
Kind::Choice(&["top_right", "top_left", "bottom_right", "bottom_left"]),
"Screen corner of the meeting recording indicator",
),
key(
"meetings.retention",
Kind::Choice(&["day", "week", "month", "forever"]),
"How long finished meetings are kept before they move to the Trash",
),
key(
"meetings.providers",
Kind::Json,
"Per-app call choices, as a JSON array of {key, label, policy: ask|always_record|never_offer}",
),
read_only(
"meetings.calendar.connected",
Kind::Bool,
"A calendar is connected for meeting reminders",
"connect a calendar from Settings › Meetings, which asks macOS for access",
),
key(
"meetings.calendar.excluded_calendars",
Kind::Json,
"Calendars left out of reminders, as a JSON array of EventKit identifiers",
),
key(
"meetings.calendar.remind",
Kind::Bool,
"Remind before calendar meetings",
),
key(
"meetings.calendar.lead_minutes",
Kind::Choice(&["0", "1", "2", "5"]),
"Minutes before a meeting its reminder shows",
),
key(
"experimental.hex_microphone",
Kind::Bool,
"Labs: the Voice Filter and its Hex Microphone virtual input",
),
key(
"experimental.hex_microphone_mode",
Kind::Choice(&[
"normal",
"muffled",
"quiet",
"muted",
"chipmunk",
"robot",
"walkie",
"underwater",
"far",
]),
"What Hex Microphone does to your voice while you dictate",
),
key(
"experimental.hex_microphone_comfort_noise",
Kind::Bool,
"Hex Microphone fills silence with soft noise",
),
key(
"experimental.hex_microphone_strength",
UNIT,
"How strongly Hex Microphone applies its filter, from 0 to 1",
),
key(
"enable_on_launch",
Kind::Bool,
"Start listening when Hex opens (Windows and Linux)",
),
key(
"paste_with_shift",
Kind::Bool,
"Paste with Ctrl-Shift-V for terminals (Linux and Windows)",
),
key(
"share_dictation_shortcut",
Kind::Bool,
"Labs: let other apps see the dictation shortcut too (Windows)",
),
optional(
"ui_language",
Kind::Choice(&["en", "pl", "zh", "ja", "de", "es", "uk"]),
"Interface language; none follows the system",
),
key(
"indicator_position",
Kind::Choice(&["top", "bottom", "hidden"]),
"Where the dictation HUD appears",
),
optional(
"updates.channel",
Kind::Choice(&["stable", "dev"]),
"Update channel; none follows the build (dev builds use dev, others stable)",
),
];
/// Captures exist only in builds with the `capture` build option.
#[cfg(hex_capture)]
const CAPTURE_KEYS: &[Key] = &[
key(
"capture.enabled",
Kind::Bool,
"Annotate: record the screen while you draw and talk (on by default)",
),
key(
"capture.hotkey",
Kind::Shortcut(HotkeySlot::Capture),
"The Annotate shortcut: press to start recording and again to finish",
),
key(
"capture.transcriber",
Kind::Choice(&["parakeet", "apple"]),
"What transcribes a capture's narration: Hex's loaded model or Apple's",
),
optional(
"capture.folder",
Kind::Path,
"Folder for new captures; none uses Scrawl's captures folder",
),
optional(
"capture.media_days",
RETENTION_DAYS,
"Days a capture keeps its video and audio; none keeps them",
),
optional(
"capture.bundle_days",
RETENTION_DAYS,
"Days a capture is kept; none keeps it",
),
key(
"capture.capsule_flow",
Kind::Choice(&["list", "toast", "menu_bar", "cursor", "notch"]),
"How the capture capsule offers where to send a capture (prototypes): a list, a \
one-line toast, the menu bar, a card at the pointer, or a notch",
),
key(
"capture.routing",
Kind::Json,
"Where captures go among OpenCode sessions: Scrawl's router settings (autoSend, sites, apps, smartRouting, …) as a JSON object",
),
key(
"capture.show_overlays_in_recordings",
Kind::Bool,
"Let screen recordings, captures included, show Hex's capsules, ink, and HUD (for demos)",
),
];
#[cfg(hex_capture)]
const RETENTION_DAYS: Kind = Kind::Integer { min: 1, max: 3650 };
#[cfg(not(hex_capture))]
const CAPTURE_KEYS: &[Key] = &[];
/// Settings that act only where Hex has a capability (by its
/// `rune_ui::capabilities` name), the same one that shows their row in the
/// window. The first matching prefix decides.
const NEEDS: &[(&str, &str)] = &[
("meetings.calendar.", "calendar"),
("meetings.", "meetings"),
("labs.live_chapters", "meetings"),
("labs.subtitle_export", "meetings"),
("experimental.hex_microphone", "fun"),
("show_dock_icon", "dock_icon"),
("keyboard_model_switching.", "keyboard_model_switching"),
("enable_on_launch", "listener_control"),
("share_dictation_shortcut", "share_shortcut"),
];
/// The capability `key` needs, if any.
fn needs(key: &str) -> Option<&'static str> {
NEEDS
.iter()
.find(|(prefix, _)| key == *prefix || key.starts_with(prefix))
.map(|(_, capability)| *capability)
}
/// Why `hex settings set` refuses `name` on this OS, if it does.
pub fn unavailable(name: &str) -> Option<ControlError> {
let capability = needs(name).filter(|capability| !crate::rune_ui::capability(capability))?;
Some(ControlError::new(
"unsupported",
format!(
"`{name}` does nothing on this OS: it needs {capability}, which Hex has only elsewhere"
),
))
}
/// Every key, in registry order.
fn keys() -> impl Iterator<Item = &'static Key> {
KEYS.iter().chain(CAPTURE_KEYS)
}
/// Settings `hex settings` never shows: Hex's own bookkeeping.
#[cfg(test)]
const INTERNAL: &[&str] = &["migrations", "mouse_shortcut_notice"];
/// Settings another `hex` command edits instead (`hex vocabulary`).
#[cfg(test)]
const OWN_COMMAND: &[&str] = &["vocabulary"];
/// What the OS knows about shortcuts: how a key name resolves on the
/// active layout, and the rules recording one in Settings applies.
pub struct ShortcutRules {
pub key_named: fn(&str) -> Result<HotkeyKey, String>,
pub rule: fn(HotkeySlot, &HotkeyBinding) -> Result<(), String>,
}
/// Something the host does beyond saving `settings.json`.
#[derive(Clone, Debug, PartialEq)]
pub enum Effect {
HistoryRetention(crate::history::HistoryRetention),
DockIcon,
/// Check the newly chosen channel now rather than within the hour.
CheckForUpdates,
}
/// A validated change, ready to save.
#[derive(Debug)]
pub struct Change {
pub settings: AppSettings,
pub effects: Vec<Effect>,
pub message: String,
}
impl Change {
pub fn changed(&self, before: &AppSettings) -> bool {
self.settings != *before
}
}
/// Every setting, in registry order.
pub fn list(settings: &AppSettings) -> Vec<SettingValue> {
let json = serde_json::to_value(settings).unwrap_or(Value::Null);
keys().map(|key| value_of(key, &json)).collect()
}
/// One setting, or every setting under a prefix such as `meetings`.
pub fn get(settings: &AppSettings, name: &str) -> Result<Vec<SettingValue>, ControlError> {
let json = serde_json::to_value(settings).unwrap_or(Value::Null);
let prefix = format!("{name}.");
let found: Vec<_> = keys()
.filter(|key| key.key == name || key.key.starts_with(&prefix))
.map(|key| value_of(key, &json))
.collect();
if found.is_empty() {
return Err(unknown(name));
}
Ok(found)
}
fn unknown(name: &str) -> ControlError {
let near = keys()
.map(|key| key.key)
.find(|key| {
key.ends_with(name)
|| name.ends_with(key)
|| key.replace('_', "") == name.replace(['_', '-'], "")
})
.map(|key| format!(" Did you mean `{key}`?"))
.unwrap_or_default();
ControlError::new(
"unknown-setting",
format!("unknown setting `{name}`.{near} Run `hex settings list` for every key."),
)
}
fn value_of(key: &Key, json: &Value) -> SettingValue {
let raw = json
.pointer(&pointer(key.key))
.cloned()
.unwrap_or(Value::Null);
let value = match key.kind {
Kind::Shortcut(_) => match serde_json::from_value::<Option<HotkeyBinding>>(raw) {
Ok(Some(binding)) => Value::String(format_hotkey(&binding)),
_ => Value::Null,
},
Kind::Choice(_) if NUMERIC_CHOICES.contains(&key.key) => Value::String(raw.to_string()),
_ => raw,
};
SettingValue {
key: key.key.into(),
value,
kind: key.kind.name().into(),
choices: match key.kind {
Kind::Choice(choices) => choices.iter().map(|&choice| choice.into()).collect(),
_ => Vec::new(),
},
writable: key.read_only.is_none(),
about: key.about.into(),
available: needs(key.key).is_none_or(crate::rune_ui::capability),
}
}
fn pointer(key: &str) -> String {
format!("/{}", key.replace('.', "/"))
}
/// Validates `raw` for `name` against `settings` and returns the settings
/// to save, applying the rules the window applies for the same change.
pub fn apply(
settings: &AppSettings,
name: &str,
raw: &str,
shortcuts: &ShortcutRules,
) -> Result<Change, ControlError> {
let key = keys()
.find(|key| key.key == name)
.ok_or_else(|| unknown(name))?;
if let Some(why) = key.read_only {
return Err(ControlError::new(
"read-only",
format!("`{name}` can't be set here: {why}"),
));
}
let value = parse(key, raw, shortcuts)?;
let mut json = serde_json::to_value(settings)
.map_err(|error| ControlError::new("internal", error.to_string()))?;
let slot = json
.pointer_mut(&pointer(key.key))
.ok_or_else(|| ControlError::new("internal", format!("`{name}` is missing")))?;
*slot = value;
let mut candidate: AppSettings =
serde_json::from_value(json).map_err(|error| invalid(name, &format!("{error}")))?;
let mut effects = Vec::new();
let message = format!("Set {name}");
match key.key {
"sound_effect_volume" => {
let volume = candidate.sound_effect_volume;
candidate.sound_effects = volume > 0.0;
if volume <= 0.0 {
candidate.sound_effect_volume = settings.sound_effect_volume;
}
}
"double_tap_lock" if !candidate.double_tap_lock => candidate.double_tap_only = false,
"double_tap_only" if candidate.double_tap_only => {
if !candidate.double_tap_lock || candidate.dictation_hotkey.key.is_none() {
return Err(invalid(
name,
"a double-tap-only start needs double_tap_lock on and a dictation shortcut \
with a key, such as option+space",
));
}
}
"dictation_hotkey"
| "paste_last_hotkey"
| "raw_dictation_hotkey"
| "second_dictation_hotkey"
| "capture.hotkey" => {
let Kind::Shortcut(slot) = key.kind else {
unreachable!("shortcut keys have the shortcut kind");
};
let binding = match slot {
HotkeySlot::Dictation => Some(&candidate.dictation_hotkey),
HotkeySlot::PasteLast => candidate.paste_last_hotkey.as_ref(),
HotkeySlot::RawDictation => candidate.raw_dictation_hotkey.as_ref(),
HotkeySlot::SecondDictation => candidate.second_dictation_hotkey.as_ref(),
#[cfg(hex_capture)]
HotkeySlot::Capture => Some(&candidate.capture.hotkey),
};
if let Some(binding) = binding {
if cfg!(target_os = "macos")
&& !candidate.labs.mouse_shortcuts
&& binding.key.as_ref().is_some_and(HotkeyKey::is_mouse)
{
return Err(invalid(
name,
"mouse buttons need Labs › Mouse shortcuts: hex labs on mouse-shortcuts",
));
}
(shortcuts.rule)(slot, binding).map_err(|why| invalid(name, &why))?;
if settings.hotkey_in_use(slot, binding) {
return Err(ControlError::new(
"shortcut-in-use",
format!(
"{} is already in use by another Hex shortcut",
format_hotkey(binding)
),
));
}
}
if candidate.dictation_hotkey.key.is_none() {
candidate.double_tap_only = false;
}
}
"keyboard_model_switching.mappings" => {
for choice in candidate.keyboard_model_switching.mappings.values() {
choice
.validate()
.map_err(|error| invalid(name, &error.to_string()))?;
}
}
"transcription.recognition_hints" => {
let model = crate::transcription_models::definition(candidate.transcription.model);
if !model.supports_recognition_hints {
return Err(invalid(
name,
&format!("{} doesn't take recognition hints", model.name),
));
}
}
"dictation_processing.default_mode" => {
candidate.dictation_processing.default_mode.name = "Global".into();
}
"dictation_processing.modes" => {
let mut names = std::collections::HashSet::new();
for mode in &candidate.dictation_processing.modes {
let mode_name = mode.name.trim();
if mode_name.is_empty() || !names.insert(mode_name.to_lowercase()) {
return Err(invalid(name, "every mode needs a unique, non-empty name"));
}
}
}
#[cfg(hex_capture)]
"capture.enabled"
if candidate.capture.enabled
&& candidate.hotkey_in_use(HotkeySlot::Capture, &candidate.capture.hotkey) =>
{
return Err(ControlError::new(
"shortcut-in-use",
"The capture shortcut is already in use; set capture.hotkey to another \
shortcut first",
));
}
"history_retention" => effects.push(Effect::HistoryRetention(candidate.history_retention)),
"show_dock_icon" => effects.push(Effect::DockIcon),
"updates.channel" => effects.push(Effect::CheckForUpdates),
_ => {}
}
Ok(Change {
settings: candidate,
effects,
message,
})
}
/// Validates every `key: value` in `values` against `settings` and returns
/// the settings to save, all or none (`hex settings apply`, the Home Manager
/// module). Values are JSON: booleans, numbers, `null` for `none`, objects
/// and arrays for json settings, text for the rest. `transcription.model`
/// and `transcription.language` select a model, as `hex model use` would,
/// without needing it installed. Keys that depend on each other (a
/// double-tap-only start and its shortcut) apply in any order.
pub fn apply_all(
settings: &AppSettings,
values: &serde_json::Map<String, Value>,
shortcuts: &ShortcutRules,
) -> Result<Change, ControlError> {
let mut candidate = settings.clone();
let model = values.get("transcription.model");
let language = values.get("transcription.language");
if model.is_some() || language.is_some() {
let text = |name: &str, value: Option<&Value>| match value {
None => Ok(None),
Some(Value::String(text)) => Ok(Some(text.clone())),
Some(_) => Err(invalid(name, "expected text")),
};
let model = text("transcription.model", model)?
.unwrap_or_else(|| candidate.transcription.model.as_str().to_owned());
let language = text("transcription.language", language)?;
candidate.transcription = super::model_selection(&candidate, &model, language.as_deref())?;
}
let mut pending = Vec::new();
for (name, value) in values {
if matches!(
name.as_str(),
"transcription.model" | "transcription.language"
) {
continue;
}
if let Some(error) = unavailable(name) {
return Err(error);
}
let key = keys()
.find(|key| key.key == name)
.ok_or_else(|| unknown(name))?;
let raw = match (key.kind, value) {
(Kind::Json, value) => value.to_string(),
(_, Value::String(text)) => text.clone(),
(_, Value::Null) => "none".into(),
(_, value) => value.to_string(),
};
pending.push((name.as_str(), raw));
}
let mut effects = Vec::new();
while !pending.is_empty() {
let tried = pending.len();
let mut failed = Vec::new();
let mut first_error = None;
for (name, raw) in pending.drain(..) {
match apply(&candidate, name, &raw, shortcuts) {
Ok(change) => {
candidate = change.settings;
effects.extend(change.effects);
}
Err(error) => {
first_error.get_or_insert(error);
failed.push((name, raw));
}
}
}
if let Some(error) = first_error
&& failed.len() == tried
{
return Err(error);
}
pending = failed;
}
Ok(Change {
settings: candidate,
effects,
message: format!("Applied {} settings", values.len()),
})
}
fn invalid(name: &str, why: &str) -> ControlError {
ControlError::new(
"invalid-value",
format!("invalid value for `{name}`: {why}"),
)
}
fn parse(key: &Key, raw: &str, shortcuts: &ShortcutRules) -> Result<Value, ControlError> {
let name = key.key;
let trimmed = raw.trim();
if key.optional && matches!(trimmed.to_ascii_lowercase().as_str(), "none" | "null" | "") {
return Ok(Value::Null);
}
if name == "microphone" && trimmed.eq_ignore_ascii_case("system-default") {
return Ok(Value::Null);
}
match key.kind {
Kind::Bool => match trimmed.to_ascii_lowercase().as_str() {
"on" | "true" | "yes" | "1" => Ok(Value::Bool(true)),
"off" | "false" | "no" | "0" => Ok(Value::Bool(false)),
_ => Err(invalid(name, "expected on or off")),
},
Kind::Number { min, max } => trimmed
.parse::<f64>()
.ok()
.filter(|value| value.is_finite() && (min..=max).contains(value))
.and_then(serde_json::Number::from_f64)
.map(Value::Number)
.ok_or_else(|| invalid(name, &format!("expected a number from {min} to {max}"))),
Kind::Integer { min, max } => trimmed
.parse::<u64>()
.ok()
.filter(|value| (min..=max).contains(value))
.map(Value::from)
.ok_or_else(|| {
invalid(
name,
&format!("expected a whole number from {min} to {max}"),
)
}),
Kind::Choice(choices) => {
let normalized = trimmed.to_ascii_lowercase().replace('-', "_");
let choice = choices
.iter()
.find(|choice| **choice == normalized)
.ok_or_else(|| invalid(name, &format!("expected one of {}", choices.join(", "))))?;
Ok(if name == "meetings.calendar.lead_minutes" {
let minutes: u8 = choice.parse().expect("lead choices are numbers");
debug_assert!(CALENDAR_LEAD_MINUTES.contains(&minutes));
Value::from(minutes)
} else if name == "labs.unload_idle_minutes" {
let minutes: u32 = choice.parse().expect("idle choices are numbers");
debug_assert!(crate::app_settings::UNLOAD_IDLE_MINUTES.contains(&minutes));
Value::from(minutes)
} else {
Value::String((*choice).into())
})
}
Kind::Text => Ok(Value::String(raw.into())),
Kind::Path => {
let path = match trimmed.strip_prefix("~/") {
Some(rest) => dirs::home_dir()
.ok_or_else(|| invalid(name, "no home folder to expand ~ in"))?
.join(rest),
None => std::path::PathBuf::from(trimmed),
};
if !path.is_absolute() {
return Err(invalid(name, "expected an absolute path"));
}
Ok(Value::String(path.to_string_lossy().into_owned()))
}
Kind::Json => serde_json::from_str(raw).map_err(|error| invalid(name, &error.to_string())),
Kind::Shortcut(_) => {
let binding =
parse_hotkey(trimmed, shortcuts.key_named).map_err(|why| invalid(name, &why))?;
serde_json::to_value(binding)
.map_err(|error| ControlError::new("internal", error.to_string()))
}
}
}
/// Reads a shortcut such as `option`, `right-command`, `fn`, `f5`,
/// `left-option+right-option` (both Options), or `control+option+space`:
/// modifiers, then at most one key.
pub fn parse_hotkey(
text: &str,
key_named: fn(&str) -> Result<HotkeyKey, String>,
) -> Result<HotkeyBinding, String> {
let mut modifiers = HotkeyModifiers::default();
let mut key = None;
let mut sided = false;
let parts: Vec<&str> = text.split('+').map(str::trim).collect();
if parts.iter().any(|part| part.is_empty()) {
return Err("expected modifiers and a key joined by +, such as option+space".into());
}
for part in parts {
let lower = part.to_ascii_lowercase();
let (side, name) = if let Some(rest) =
lower.strip_prefix("left-").or(lower.strip_prefix("left"))
{
(Some(ModifierSide::Left), rest.to_string())
} else if let Some(rest) = lower.strip_prefix("right-").or(lower.strip_prefix("right")) {
(Some(ModifierSide::Right), rest.to_string())
} else {
(None, lower.clone())
};
let slot = match name.as_str() {
"control" | "ctrl" => Some(&mut modifiers.control),
"option" | "opt" | "alt" => Some(&mut modifiers.option),
"shift" => Some(&mut modifiers.shift),
"command" | "cmd" | "super" | "win" | "meta" => Some(&mut modifiers.command),
_ => None,
};
match slot {
Some(slot) => {
sided |= side.is_some();
*slot = Some(match (*slot, side) {
(None, side) => side.unwrap_or(ModifierSide::Either),
(Some(ModifierSide::Left), Some(ModifierSide::Right))
| (Some(ModifierSide::Right), Some(ModifierSide::Left)) => ModifierSide::Both,
_ => return Err(format!("{part} appears twice")),
});
}
None if side.is_none() && matches!(name.as_str(), "fn" | "function" | "globe") => {
if modifiers.function {
return Err(format!("{part} appears twice"));
}