Repository navigation
Expand file tree
/
Copy pathapp_settings.rs
More file actions
3611 lines (3376 loc) · 141 KB
/
Copy pathapp_settings.rs
File metadata and controls
3611 lines (3376 loc) · 141 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::{Arc, 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::dictation::vocabulary::{VocabularyEntry, serialize_saved};
use crate::transcription::models::{TranscriptionModelId, TranscriptionSelection};
#[cfg(hex_capture)]
mod capture;
mod dictation_processing;
mod extra_shortcuts;
mod hotkeys;
mod labs;
mod meeting_folder;
mod meetings;
mod microphone_key;
mod persistence;
mod screenshots;
#[cfg(target_os = "linux")]
pub(crate) use persistence::LaunchLoad;
pub(crate) use persistence::LaunchNote;
mod shortcut_repair;
mod typing_speed;
#[cfg(hex_capture)]
pub use capture::*;
pub use dictation_processing::{
DictationMode, DictationPostProcessing, DictationProcessingSettings,
};
pub use extra_shortcuts::*;
pub use hotkeys::*;
pub use labs::*;
pub use meeting_folder::default_meeting_output_folder;
pub use meetings::*;
#[cfg_attr(not(target_os = "macos"), allow(unused_imports))]
pub(crate) use microphone_key::{MicrophoneKey, MicrophoneKeyTap};
#[cfg_attr(not(target_os = "macos"), allow(unused_imports))]
pub use screenshots::{
ScreenshotSettings, screenshot_hotkey, screenshot_record_hotkey, screenshot_settings,
};
pub use typing_speed::{
DEFAULT_TYPING_WPM, MAX_TYPING_WPM, MIN_TYPING_WPM, clamp as clamp_typing_wpm,
};
const DEFAULT_RECORDING_DUCK_VOLUME: f32 = 0.2;
const DEFAULT_DOUBLE_TAP_LOCK: bool = true;
static RECORDING_DUCK_VOLUME: AtomicU32 = AtomicU32::new(DEFAULT_RECORDING_DUCK_VOLUME.to_bits());
// Until settings load, "While dictating" is its default, not Mute: the
// hotkey pre-roll depends on it.
static RECORDING_AUDIO_BEHAVIOR: AtomicU8 =
AtomicU8::new(RecordingAudioBehavior::DoNothing.encoded());
static DOUBLE_TAP_LOCK: AtomicBool = AtomicBool::new(DEFAULT_DOUBLE_TAP_LOCK);
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_SUMMARIES: AtomicU8 = AtomicU8::new(MeetingSummaries::platform_default() as u8);
static MEETING_INDICATOR_ENABLED: AtomicBool =
AtomicBool::new(meetings::DEFAULT_SHOW_RECORDING_INDICATOR);
static MEETING_INDICATOR_CORNER: AtomicU8 = AtomicU8::new(MeetingIndicatorCorner::TopRight as u8);
/// [`MeetingRetention::encode`]d; [`RETENTION_UNSET`] until settings apply.
static MEETING_RETENTION: AtomicU8 = AtomicU8::new(RETENTION_UNSET);
/// [`MeetingRetention::encode`]d; [`RETENTION_UNSET`] until settings apply.
static MEETING_AUDIO_RETENTION: AtomicU8 = AtomicU8::new(RETENTION_UNSET);
static MEETING_STOP_WHEN_CALL_ENDS: AtomicBool = AtomicBool::new(false);
static MEETING_DESCRIPTIVE_FILENAMES: AtomicBool = AtomicBool::new(false);
static MEETING_NOTES_FILE: AtomicBool = AtomicBool::new(false);
const RETENTION_UNSET: u8 = u8::MAX;
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_SELECTED: AtomicBool = AtomicBool::new(false);
static INDICATOR_POSITION: AtomicU8 = AtomicU8::new(0);
static HOTKEYS: OnceLock<RwLock<AppliedHotkeys>> = OnceLock::new();
static HOTKEY_CAPTURE_ACTIVE: AtomicBool = AtomicBool::new(false);
#[cfg(test)]
/// Distinct names for the tests' settings folders.
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>,
}
/// Experimental opt-in features hidden by default.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(default)]
pub struct ExperimentalSettings {
pub hex_microphone: bool,
pub hex_microphone_mode: crate::audio::voice_filter::VoiceFilterMode,
pub hex_microphone_comfort_noise: bool,
pub hex_microphone_strength: f32,
}
impl Default for ExperimentalSettings {
fn default() -> Self {
Self {
hex_microphone: false,
hex_microphone_mode: crate::audio::voice_filter::VoiceFilterMode::Muffled,
hex_microphone_comfort_noise: true,
hex_microphone_strength: 1.0,
}
}
}
/// Whether the Voice Filter runs: the listener streams the Hex Microphone
/// and Hex watches its driver. Its Labs toggle (`experimental.hex_microphone`,
/// or `HEX_EXPERIMENTAL_MIC`) or an installed driver turns it on, so a driver
/// apps already use keeps receiving audio.
pub fn voice_filter_enabled(setting: bool, driver_installed: bool) -> bool {
setting || env_hex_experimental_mic() || driver_installed
}
pub fn env_hex_experimental_mic() -> bool {
std::env::var("HEX_EXPERIMENTAL_MIC")
.ok()
.is_some_and(|v| matches!(v.trim(), "1" | "true" | "TRUE" | "yes"))
}
/// Where Linux and Windows run the speech model (#856): Auto picks a GPU
/// unless it failed before under its current driver, then the CPU.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TranscriptionDevice {
#[default]
Auto,
Gpu,
Cpu,
}
/// Where the recording HUD appears while dictating.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[repr(u8)]
pub enum IndicatorPosition {
#[default]
Top = 0,
Bottom = 1,
Hidden = 2,
}
/// Which release-service channel a direct install updates from
/// (`crate::updater`).
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UpdateChannel {
Stable,
Dev,
}
impl UpdateChannel {
pub const ALL: [Self; 2] = [Self::Stable, Self::Dev];
pub const fn name(self) -> &'static str {
match self {
Self::Stable => "stable",
Self::Dev => "dev",
}
}
pub const fn label(self) -> &'static str {
match self {
Self::Stable => "Stable",
Self::Dev => "Dev",
}
}
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct UpdateSettings {
/// `None` follows the build: the channel it was published on (stamped at
/// build time), else `dev` for a dev version, else its install's channel.
/// Another channel than the build's is a switch the user confirms.
pub channel: Option<UpdateChannel>,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RecordingAudioBehavior {
Mute,
Duck,
PauseMedia,
#[default]
DoNothing,
}
pub use crate::dictation::text_replacements::TextReplacement;
impl RecordingAudioBehavior {
pub const ALL: [Self; 4] = [Self::Mute, Self::PauseMedia, Self::Duck, Self::DoNothing];
pub const fn label(self) -> &'static str {
match self {
Self::Mute => "Mute",
Self::Duck => "Lower audio",
Self::PauseMedia => "Pause media",
Self::DoNothing => "Do nothing",
}
}
const fn encoded(self) -> u8 {
match self {
Self::Mute => 0,
Self::Duck => 3,
Self::PauseMedia => 1,
Self::DoNothing => 2,
}
}
fn decode(value: u8) -> Self {
match value {
3 => Self::Duck,
1 => Self::PauseMedia,
2 => Self::DoNothing,
_ => Self::Mute,
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(default)]
pub struct AppSettings {
#[serde(skip)]
pub(crate) source: persistence::Source,
/// Retired spoken-commands opt-in, kept untouched in `settings.json`.
#[serde(
default,
rename = "commands_enabled",
deserialize_with = "deserialize_retired_value",
skip_serializing_if = "Option::is_none"
)]
pub retired_commands_enabled: Option<serde_json::Value>,
pub release_microphone_while_idle: bool,
pub sound_effects: bool,
pub sound_effect_volume: f32,
/// Which feedback sounds play (`crate::feedback`).
pub sound_theme: crate::feedback::SoundSet,
pub microphone: Option<String>,
/// System default records from the built-in microphone, else another
/// real input, rather than a Bluetooth default.
pub avoid_bluetooth_microphone: bool,
pub recording_audio_behavior: RecordingAudioBehavior,
/// Fraction of the original output volume while ducking.
pub recording_duck_volume: f32,
/// With Pause media on macOS, also pause a browser that is audibly playing.
pub pause_browser_media: bool,
pub double_tap_lock: bool,
pub double_tap_only: bool,
pub shortcut_mode: crate::dictation::ShortcutMode,
pub dictation_hotkey: HotkeyBinding,
/// Retired Voice Action shortcut, kept untouched in `settings.json`.
#[serde(
default,
rename = "edit_hotkey",
deserialize_with = "deserialize_retired_value",
skip_serializing_if = "Option::is_none"
)]
pub retired_edit_hotkey: Option<serde_json::Value>,
pub paste_last_hotkey: Option<HotkeyBinding>,
/// Toggle mode's cancel shortcut: discards the recording. Hex takes it
/// only while a toggled recording runs; Hold mode has no cancel.
pub cancel_hotkey: HotkeyBinding,
/// Dictate without processing: records like the dictation shortcut and
/// pastes the transcript as heard. Unbound by default.
pub raw_dictation_hotkey: Option<HotkeyBinding>,
/// Labs › Transform typed text (Linux): runs the focused app's Output
/// steps on the text already typed in the focused field and replaces it.
/// Unbound by default and ignored while its Labs toggle is off.
pub typed_text_hotkey: Option<HotkeyBinding>,
/// Labs › Second dictation shortcut: another shortcut that dictates
/// exactly as `dictation_hotkey` does. Unbound by default and ignored
/// while its Labs toggle is off.
pub second_dictation_hotkey: Option<HotkeyBinding>,
/// Labs › More dictation shortcuts (macOS): up to
/// [`MAX_EXTRA_DICTATION_SHORTCUTS`] more, each with its own binding and
/// activation mode. Saved rows stay while the Lab is off but never
/// register or match.
#[serde(default)]
pub extra_dictation_hotkeys: Vec<ExtraDictationHotkey>,
/// Labs › Terminal paste shortcut: another shortcut that dictates like
/// `dictation_hotkey` and always pastes with Ctrl+Shift+V (Windows,
/// Linux). Unbound by default and ignored while its Labs toggle is off.
pub terminal_paste_hotkey: Option<HotkeyBinding>,
pub show_dock_icon: bool,
pub transcription: TranscriptionSelection,
/// Where the speech model runs (Linux and Windows).
pub transcription_device: TranscriptionDevice,
pub transcription_recents: Vec<TranscriptionSelection>,
pub keyboard_model_switching: KeyboardModelSwitching,
pub dictation_processing: DictationProcessingSettings,
/// Retired Voice Action settings, kept untouched in `settings.json`.
#[serde(
default,
rename = "voice_action",
deserialize_with = "deserialize_retired_value",
skip_serializing_if = "Option::is_none"
)]
pub retired_voice_action: Option<serde_json::Value>,
pub history_retention: crate::history::HistoryRetention,
/// Words a minute the person types, which Dictation stats' time saved
/// compares against what they dictated; clamped to 10–200.
#[serde(
default = "typing_speed::default_wpm",
deserialize_with = "typing_speed::deserialize"
)]
pub typing_wpm: u32,
pub meetings: MeetingSettings,
#[cfg(hex_capture)]
pub capture: CaptureSettings,
/// Capture settings from a build with captures, kept as they were.
#[cfg(not(hex_capture))]
#[serde(rename = "capture", skip_serializing_if = "Option::is_none")]
pub capture_from_other_build: Option<serde_json::Value>,
#[serde(default)]
pub experimental: ExperimentalSettings,
/// The Labs features' own switches (`crate::labs`).
pub labs: LabsSettings,
/// Labs › Screenshots' shortcut and folder (macOS).
pub screenshots: ScreenshotSettings,
/// Start listening when Hex opens (Windows and Linux, where the
/// listener can be off).
pub enable_on_launch: bool,
/// Paste with Ctrl-Shift-V for terminals (Linux and Windows).
pub paste_with_shift: bool,
/// Hex keeps its own GNOME custom keyboard shortcuts, on GNOME without a
/// shortcuts portal (Linux, #781).
pub gnome_keyboard_shortcuts: bool,
/// Let other apps see the dictation shortcut's key presses too
/// (Windows), so a push-to-talk key can drive both.
pub share_dictation_shortcut: bool,
/// A mouse-button shortcut went back to its default because Labs ›
/// Mouse shortcuts is off; the window says so once, then clears it.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub mouse_shortcut_notice: bool,
/// The interface language code; `None` follows the system language.
pub ui_language: Option<String>,
pub indicator_position: IndicatorPosition,
pub updates: UpdateSettings,
/// The shared vocabulary (`crate::dictation::vocabulary`). Left out of the file
/// while empty, so settings without one stay as they were.
#[serde(
skip_serializing_if = "Vec::is_empty",
serialize_with = "serialize_saved"
)]
pub vocabulary: Vec<VocabularyEntry>,
/// How readily transcription swaps heard words for a vocabulary term.
pub vocabulary_boost: crate::dictation::vocabulary::VocabularyBoost,
/// One-time settings changes already applied. A file that predates a
/// change lacks its ID, so the change runs once on the next load; new
/// settings start with every ID because they need none.
#[serde(default)]
pub migrations: Vec<String>,
#[serde(skip_serializing)]
pub text_replacements: Vec<TextReplacement>,
}
/// Moves English dictation to the streaming English model once.
const STREAMING_ENGLISH_MIGRATION: &str = "streaming-english-model";
/// Annotate became a default feature: on for everyone once.
#[cfg(hex_capture)]
const ANNOTATE_DEFAULT_MIGRATION: &str = "annotate-on-by-default";
/// Settings saved by an `anomaly.hex` build. Up to 2.3.1 Hex was
/// `com.kitlangton.hex2` and used the same folder, so a file without this
/// ID may carry onboarding finished under grants macOS no longer gives the
/// new identity; the macOS launch checks setup once
/// (`onboarding::recheck_after_identity_change`).
const ANOMALY_IDENTITY_MIGRATION: &str = "anomaly-hex-identity";
#[cfg(hex_capture)]
const MIGRATIONS: &[&str] = &[
STREAMING_ENGLISH_MIGRATION,
ANNOTATE_DEFAULT_MIGRATION,
ANOMALY_IDENTITY_MIGRATION,
MEETING_RETENTION_DEFAULT_MIGRATION,
MEETING_SUMMARIES_MIGRATION,
MEETING_LABS_SETTINGS_MIGRATION,
labs::YEARLY_STATS_MERGE_MIGRATION,
];
#[cfg(not(hex_capture))]
const MIGRATIONS: &[&str] = &[
STREAMING_ENGLISH_MIGRATION,
ANOMALY_IDENTITY_MIGRATION,
MEETING_RETENTION_DEFAULT_MIGRATION,
MEETING_SUMMARIES_MIGRATION,
MEETING_LABS_SETTINGS_MIGRATION,
labs::YEARLY_STATS_MERGE_MIGRATION,
];
/// Scrawl's settings were read into `capture` once. Left out of
/// `MIGRATIONS` so new settings import them too.
#[cfg(hex_capture)]
const SCRAWL_IMPORT_MIGRATION: &str = "scrawl-capture-settings";
/// Scrawl's router settings were read into `capture.routing` once: its own
/// migration, as it came after the first import.
#[cfg(hex_capture)]
const SCRAWL_ROUTING_IMPORT_MIGRATION: &str = "scrawl-routing-settings";
/// Meeting retention first saved `forever` as its default; that default is
/// now unchosen (24 hours for new meetings, older ones kept).
const MEETING_RETENTION_DEFAULT_MIGRATION: &str = "meeting-retention-default";
/// Summarize with Apple Intelligence and Summarize with OpenCode became one
/// choice, `meetings.summaries`.
const MEETING_SUMMARIES_MIGRATION: &str = "meeting-summaries-choice";
/// Stop when the call ends, Descriptive meeting file names, Separate
/// notes file, and Expire meeting audio separately became Meetings ›
/// Settings rows: their switches were read into `meetings.*` once.
const MEETING_LABS_SETTINGS_MIGRATION: &str = "meeting-labs-settings";
fn deserialize_retired_value<'de, D>(
deserializer: D,
) -> std::result::Result<Option<serde_json::Value>, D::Error>
where
D: serde::Deserializer<'de>,
{
serde_json::Value::deserialize(deserializer).map(Some)
}
impl Default for AppSettings {
fn default() -> Self {
Self {
source: Default::default(),
retired_commands_enabled: None,
release_microphone_while_idle: false,
sound_effects: true,
sound_effect_volume: crate::feedback::DEFAULT_VOLUME,
sound_theme: crate::feedback::SoundSet::default(),
microphone: None,
avoid_bluetooth_microphone: true,
recording_audio_behavior: RecordingAudioBehavior::DoNothing,
recording_duck_volume: DEFAULT_RECORDING_DUCK_VOLUME,
pause_browser_media: false,
double_tap_lock: DEFAULT_DOUBLE_TAP_LOCK,
double_tap_only: false,
shortcut_mode: crate::dictation::ShortcutMode::Hold,
dictation_hotkey: HotkeyBinding::default(),
retired_edit_hotkey: None,
paste_last_hotkey: Some(HotkeyBinding::paste_last_default()),
cancel_hotkey: HotkeyBinding::cancel_default(),
raw_dictation_hotkey: None,
typed_text_hotkey: None,
second_dictation_hotkey: None,
extra_dictation_hotkeys: Vec::new(),
terminal_paste_hotkey: None,
show_dock_icon: true,
transcription: default_transcription(),
transcription_device: TranscriptionDevice::Auto,
transcription_recents: Vec::new(),
keyboard_model_switching: KeyboardModelSwitching::default(),
dictation_processing: DictationProcessingSettings::default(),
retired_voice_action: None,
history_retention: crate::history::HistoryRetention::default(),
typing_wpm: DEFAULT_TYPING_WPM,
meetings: MeetingSettings::default(),
#[cfg(hex_capture)]
capture: CaptureSettings::default(),
#[cfg(not(hex_capture))]
capture_from_other_build: None,
experimental: ExperimentalSettings::default(),
labs: LabsSettings::default(),
screenshots: ScreenshotSettings::default(),
enable_on_launch: true,
paste_with_shift: false,
gnome_keyboard_shortcuts: false,
share_dictation_shortcut: false,
mouse_shortcut_notice: false,
ui_language: None,
indicator_position: IndicatorPosition::default(),
updates: UpdateSettings::default(),
vocabulary: Vec::new(),
vocabulary_boost: crate::dictation::vocabulary::VocabularyBoost::default(),
migrations: MIGRATIONS.iter().map(|id| id.to_string()).collect(),
text_replacements: Vec::new(),
}
}
}
/// macOS input-source IDs mapped to the model and language they select. An
/// absent entry means "Don't switch"; this never changes the model merely
/// because dictation starts.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct KeyboardModelSwitching {
pub enabled: bool,
pub mappings: std::collections::BTreeMap<String, KeyboardModelChoice>,
}
/// What one input source selects: a model and a language it supports.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct KeyboardModelChoice {
pub model: TranscriptionModelId,
pub language: String,
}
impl KeyboardModelChoice {
/// The picker's downloadable models only; Apple Speech is never mapped.
pub fn validate(&self) -> Result<()> {
let selection = TranscriptionSelection {
model: self.model,
language: self.language.clone(),
};
// An import stays mapped while it is missing or off, like the
// saved selection; switching to it then runs the default model.
if self.model.is_labs_gated() {
return crate::transcription::models::validate_saved(&selection);
}
let model = crate::transcription::models::validate(&selection)?;
match model.runtime {
crate::transcription::models::ModelRuntime::Gguf(_) => Ok(()),
crate::transcription::models::ModelRuntime::AppleSpeech => {
Err(eyre!("{} can't be switched to by input source", model.name))
}
}
}
}
/// A new install starts with the model recommended for the person's
/// language, so first-run setup can download it without asking.
fn default_transcription() -> TranscriptionSelection {
crate::transcription::models::recommended_selection(&crate::desktop::i18n::preferred_language())
}
impl AppSettings {
pub fn transcription_for_model(&self, id: TranscriptionModelId) -> TranscriptionSelection {
if self.transcription.model == id {
return self.transcription.clone();
}
if let Some(selection) = self.transcription_recents.iter().rev().find(|selection| {
selection.model == id && crate::transcription::models::validate_saved(selection).is_ok()
}) {
return selection.clone();
}
let model = crate::transcription::models::definition(id);
TranscriptionSelection {
model: id,
language: model.language_for(&self.transcription.language).into(),
}
}
pub fn remember_transcription(&mut self, selection: TranscriptionSelection) {
self.transcription_recents.push(self.transcription.clone());
self.transcription_recents.push(selection.clone());
self.normalize_transcription_recents();
self.transcription = selection;
}
fn normalize_transcription_recents(&mut self) {
let mut seen = std::collections::HashSet::new();
self.transcription_recents.reverse();
self.transcription_recents.retain(|selection| {
crate::transcription::models::validate_saved(selection).is_ok()
&& seen.insert(selection.model)
});
self.transcription_recents.reverse();
}
pub fn save_transcription(&mut self, selection: TranscriptionSelection) -> Result<()> {
crate::transcription::models::validate(&selection)?;
let mut candidate = self.clone();
candidate.remember_transcription(selection);
*self = self.update(&candidate)?;
Ok(())
}
#[cfg(test)]
fn save_transcription_with(
&mut self,
selection: TranscriptionSelection,
save: impl FnOnce(&Self) -> Result<()>,
) -> Result<()> {
crate::transcription::models::validate(&selection)?;
let mut candidate = self.clone();
candidate.remember_transcription(selection);
self.commit_with(candidate, save)
}
/// Persist the entire candidate before replacing the current editor value.
/// The candidate may include unrelated debounced edits, which must survive
/// both failed immediate changes and successful commits.
#[cfg(test)]
pub(crate) fn commit_with(
&mut self,
candidate: Self,
save: impl FnOnce(&Self) -> Result<()>,
) -> Result<()> {
save(&candidate)?;
*self = candidate;
Ok(())
}
pub fn load() -> Result<Self> {
let path = path()?;
#[cfg_attr(not(hex_capture), allow(unused_mut))]
let mut settings = Self::load_from(&path)?;
#[cfg(hex_capture)]
{
let base = settings.clone();
let read = |path: PathBuf| fs::read(path).ok();
let engine = read(scrawl_capture::handoff::default_config_path());
let mut imported = false;
if !settings.has_migration(SCRAWL_IMPORT_MIGRATION) {
settings.import_scrawl_settings(
engine.as_deref(),
crate::app_paths::data_dir()
.and_then(|data| read(data.join("scrawl/config.json")))
.as_deref(),
);
settings.migrations.push(SCRAWL_IMPORT_MIGRATION.into());
imported = true;
}
if !settings.has_migration(SCRAWL_ROUTING_IMPORT_MIGRATION) {
settings.import_scrawl_routing(engine.as_deref());
settings
.migrations
.push(SCRAWL_ROUTING_IMPORT_MIGRATION.into());
imported = true;
}
if imported
&& path.exists()
&& persistence::healthy_file(&path)
&& let Err(error) = base.update(&settings).map(|saved| settings = saved)
{
tracing::warn!(%error, "could not record the Scrawl settings import");
}
}
settings.apply_runtime();
Ok(settings)
}
/// Reads Scrawl's settings into `capture`, never writing Scrawl's
/// files: `engine` is `~/.config/scrawl/config.json` (transcriber,
/// captures folder, retention) and `app` is the app's shortcut file.
/// Missing or unreadable values keep Hex's defaults.
#[cfg(hex_capture)]
fn import_scrawl_settings(&mut self, engine: Option<&[u8]>, app: Option<&[u8]>) {
if let Some(config) = engine.and_then(|bytes| {
serde_json::from_slice::<serde_json::Value>(bytes)
.ok()
.filter(serde_json::Value::is_object)
}) {
if config
.get("transcriber")
.and_then(serde_json::Value::as_str)
== Some("apple")
{
self.capture.transcriber = CaptureTranscriber::Apple;
}
let home = crate::app_paths::home_dir();
if let Some(folder) = config
.get("capturesDir")
.or_else(|| config.get("captures_dir"))
.and_then(serde_json::Value::as_str)
.map(|dir| match (dir.strip_prefix("~/"), &home) {
(Some(rest), Some(home)) => home.join(rest),
_ => PathBuf::from(dir),
})
.filter(|dir| dir.is_absolute())
{
self.capture.folder = Some(folder);
}
if let Some(policy) = config
.get("retention")
.and_then(|value| serde_json::from_value(value.clone()).ok())
{
self.capture.set_retention(policy);
}
}
if let Some(binding) = app.and_then(scrawl_shortcut)
&& !self.hotkey_in_use(HotkeySlot::Capture, &binding)
{
self.capture.hotkey = binding;
}
}
/// Reads the router's settings from Scrawl's `config.json` (`engine`):
/// its rules, `autoSend`, and the `smartRouting` and `jevRouting`
/// experiments, leniently as Scrawl reads them, leaving out the Jev key.
/// A missing or unreadable file keeps the defaults.
#[cfg(hex_capture)]
fn import_scrawl_routing(&mut self, engine: Option<&[u8]>) {
let Some(serde_json::Value::Object(root)) =
engine.and_then(|bytes| serde_json::from_slice(bytes).ok())
else {
return;
};
let mut warnings = Vec::new();
self.capture.routing =
scrawl_capture::router_config_from_scrawl(&root, &mut warnings).into();
// A warning quotes the value it dropped, which may be the Jev key.
if !warnings.is_empty() {
tracing::info!(
count = warnings.len(),
"Scrawl routing settings were left out"
);
}
}
/// The saved `labs` switches, read without loading, normalizing, or
/// writing anything else.
pub fn saved_labs() -> LabsSettings {
#[derive(Deserialize)]
struct File {
#[serde(default)]
labs: LabsSettings,
}
path()
.ok()
.and_then(|path| fs::read(path).ok())
.and_then(|data| serde_json::from_slice::<File>(&data).ok())
.map(|file| file.labs)
.unwrap_or_default()
}
/// The saved `updates.channel`, read without loading, normalizing, or
/// writing anything else, so the updater thread never races a save.
pub fn saved_update_channel() -> Option<UpdateChannel> {
#[derive(Deserialize)]
struct File {
#[serde(default)]
updates: UpdateSettings,
}
let data = fs::read(path().ok()?).ok()?;
serde_json::from_slice::<File>(&data).ok()?.updates.channel
}
/// The saved settings as `load` would see them, for a reader that must
/// never change the file: no migration is written back.
pub fn read() -> Result<Self> {
Ok(Self::read_from(&path()?)?.0)
}
fn validate_recording_duck_volume(&self) -> Result<()> {
if !self.recording_duck_volume.is_finite()
|| !(0.0..=1.0).contains(&self.recording_duck_volume)
{
return Err(eyre!("recording_duck_volume must be between 0 and 1"));
}
Ok(())
}
fn apply_runtime(&self) {
// A read may finish publishing after a newer transaction has saved.
// Keep all runtime projections in the same revision order as disk.
static APPLIED: std::sync::Mutex<u64> = std::sync::Mutex::new(0);
let mut applied = APPLIED.lock().unwrap_or_else(|error| error.into_inner());
if self.source.revision != 0 && self.source.revision < *applied {
return;
}
*applied = (*applied).max(self.source.revision);
self.apply_runtime_values();
}
fn apply_runtime_values(&self) {
// Whatever an editor holds, a managed lock keeps its switches off.
let policy = crate::policy::Policy::current();
if policy.any() {
let mut managed = self.clone();
policy.enforce(&mut managed);
if managed != *self {
return managed.apply_runtime_values();
}
}
MICROPHONE_POLICY.store(
u8::from(self.release_microphone_while_idle),
Ordering::Release,
);
crate::audio::set_avoid_bluetooth_microphone(self.avoid_bluetooth_microphone);
CUSTOM_TRANSFORMATIONS_SELECTED.store(
crate::personal_commands::custom_transformations_selected(&self.dictation_processing),
Ordering::Release,
);
crate::feedback::set_enabled(self.sound_effects);
crate::feedback::set_volume(self.sound_effect_volume.clamp(0.0, 1.0));
crate::feedback::set_sound_set(self.sound_theme);
crate::desktop::i18n::apply(self.ui_language.as_deref());
INDICATOR_POSITION.store(self.indicator_position as u8, Ordering::Relaxed);
#[cfg(not(target_os = "macos"))]
crate::transcription::local_transcriber::set_device(self.transcription_device);
RECORDING_DUCK_VOLUME.store(self.recording_duck_volume.to_bits(), Ordering::Relaxed);
RECORDING_AUDIO_BEHAVIOR.store(self.recording_audio_behavior.encoded(), Ordering::Relaxed);
PAUSE_BROWSER_MEDIA.store(self.pause_browser_media, Ordering::Relaxed);
DOUBLE_TAP_LOCK.store(self.double_tap_lock, Ordering::Relaxed);
DOUBLE_TAP_ONLY.store(
self.double_tap_lock
&& self.double_tap_only
&& (self.dictation_hotkey.key.is_some() || self.double_tap_modifiers_allowed()),
Ordering::Relaxed,
);
SHORTCUT_TOGGLE.store(
self.shortcut_mode == crate::dictation::ShortcutMode::Toggle,
Ordering::Relaxed,
);
MEETINGS_ENABLED.store(
self.meetings.available() && crate::labs::Feature::Meetings.shipped(),
Ordering::Release,
);
crate::labs::apply(&self.labs);
screenshots::apply_screenshots(self);
#[cfg(hex_capture)]
{
*CAPTURE_SETTINGS
.get_or_init(Default::default)
.write()
.unwrap_or_else(|error| error.into_inner()) = self.capture.clone();
CAPTURE_ON.store(self.capture_on(), Ordering::Release);
crate::capture_host::record_own_windows(self.capture.show_overlays_in_recordings);
let flow = CapsuleFlow::ALL
.iter()
.position(|flow| *flow == self.capture.capsule_flow)
.unwrap_or_default();
CAPSULE_FLOW.store(flow as u8, Ordering::Release);
}
HEX_MICROPHONE_ENABLED.store(self.experimental.hex_microphone, Ordering::Release);
crate::audio::hex_microphone::sync_from_settings(
self.experimental.hex_microphone_mode,
self.experimental.hex_microphone_comfort_noise,
self.experimental.hex_microphone_strength,
);
MEETING_SUMMARIES.store(self.meetings.summaries as u8, Ordering::Release);
crate::meeting::generator::set_summary_model(self.meetings.opencode_model.as_deref());
MEETING_INDICATOR_ENABLED.store(self.meetings.show_recording_indicator, Ordering::Release);
MEETING_INDICATOR_CORNER.store(
self.meetings.recording_indicator_corner as u8,
Ordering::Release,
);
MEETING_RETENTION.store(
MeetingRetention::encode(self.meetings.retention),
Ordering::Release,
);
MEETING_AUDIO_RETENTION.store(
MeetingRetention::encode(self.meetings.audio_retention),
Ordering::Release,
);
MEETING_STOP_WHEN_CALL_ENDS.store(self.meetings.stop_when_call_ends, Ordering::Release);
MEETING_DESCRIPTIVE_FILENAMES.store(
self.meetings.export.descriptive_filenames,
Ordering::Release,
);
MEETING_NOTES_FILE.store(self.meetings.export.notes_file, Ordering::Release);
*MEETING_OUTPUT_FOLDER
.get_or_init(Default::default)
.write()
.unwrap_or_else(|error| error.into_inner()) =
Some(self.meetings.resolved_output_folder());
*MEETING_PROVIDERS
.get_or_init(Default::default)
.write()
.unwrap_or_else(|error| error.into_inner()) = self.meetings.providers.clone();
*CALENDAR_SETTINGS
.get_or_init(Default::default)
.write()
.unwrap_or_else(|error| error.into_inner()) = self.meetings.calendar.clone();
*HOTKEYS
.get_or_init(Default::default)
.write()
.unwrap_or_else(|error| error.into_inner()) = AppliedHotkeys {
runtime: self.runtime_hotkeys(),
settings: Some(Arc::new(self.clone())),
};
// An import that can't run stays saved; the listener runs the
// default model until it is fixed.
set_transcription_selection(&crate::transcription::custom_models::runnable(
&self.transcription,
));
set_microphone_selection(self.microphone.as_deref());
#[cfg(target_os = "macos")]
crate::dictation::config::update_dictation_profiles(
&self.dictation_processing,
self.labs.voice_prompt,
);
crate::dictation::vocabulary::apply(&self.vocabulary, self.vocabulary_boost);
}
/// Mode activations saved while Finder showed filename extensions carry a
/// `.app` suffix that never matched the foreground application name.
#[cfg(not(target_os = "macos"))]
fn normalize_mode_application_names(&mut self) {}
#[cfg(target_os = "macos")]
fn normalize_mode_application_names(&mut self) {
let modes = std::iter::once(&mut self.dictation_processing.default_mode)
.chain(self.dictation_processing.modes.iter_mut());
for mode in modes {
let mut mode_migrated = false;
for application in &mut mode.applications {
let normalized =
crate::dictation::context::strip_bundle_extension(application).to_owned();
if normalized != *application {
*application = normalized;
mode_migrated = true;
}
}
if mode_migrated {
mode.applications.sort_by_key(|name| name.to_lowercase());
mode.applications.dedup();
}
}
}
fn migrate_legacy_replacements(&mut self) {
if self.text_replacements.is_empty() {
return;
}
if self
.dictation_processing
.default_mode
.replacements
.is_empty()
{
self.dictation_processing.default_mode.replacements = self.text_replacements.clone();
}
for mode in &mut self.dictation_processing.modes {
if mode.replacements.is_empty() {
mode.replacements = self.text_replacements.clone();
}
}
self.text_replacements.clear();
}
/// Applies each one-time change this file has not seen, then records it
/// so a later choice, such as switching back, sticks.
fn apply_one_time_migrations(&mut self) {
self.apply_one_time_migrations_with(|model| {
crate::transcription::models::is_installed(model, "en")
});
}
fn apply_one_time_migrations_with(
&mut self,
installed: impl Fn(&crate::transcription::models::ModelDefinition) -> bool,
) {
if !self.has_migration(STREAMING_ENGLISH_MIGRATION) {
self.switch_english_to_streaming_model(installed);
self.migrations.push(STREAMING_ENGLISH_MIGRATION.into());
}
if !self.has_migration(MEETING_RETENTION_DEFAULT_MIGRATION) {
if self.meetings.retention == Some(MeetingRetention::Forever) {
self.meetings.retention = None;
}
self.migrations
.push(MEETING_RETENTION_DEFAULT_MIGRATION.into());
}
self.migrate_meeting_summaries();
self.migrate_meeting_labs();
self.migrate_yearly_stats_lab();
#[cfg(hex_capture)]
if !self.has_migration(ANNOTATE_DEFAULT_MIGRATION) {
self.capture.enabled = true;
self.migrations.push(ANNOTATE_DEFAULT_MIGRATION.into());
}
}
/// The two retired summary switches become `meetings.summaries` once.
pub(super) fn migrate_meeting_summaries(&mut self) {
if !self.has_migration(MEETING_SUMMARIES_MIGRATION) {
self.meetings.summaries = MeetingSummaries::from_retired(
self.meetings
.summarize_with_apple_intelligence
.unwrap_or(true),
self.meetings.summarize_with_opencode.unwrap_or(false),
);
self.migrations.push(MEETING_SUMMARIES_MIGRATION.into());
}
self.meetings.summarize_with_apple_intelligence = None;
self.meetings.summarize_with_opencode = None;
}
/// The four meeting labs that became Meetings › Settings rows carry
/// their switches over once; a separate audio retention stays only if
/// its lab was on, since it applied only then.
pub(super) fn migrate_meeting_labs(&mut self) {
if !self.has_migration(MEETING_LABS_SETTINGS_MIGRATION) {