Repository navigation
Expand file tree
/
Copy pathapp_settings.rs
More file actions
3496 lines (3238 loc) · 129 KB
/
Copy pathapp_settings.rs
File metadata and controls
3496 lines (3238 loc) · 129 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::dictation::vocabulary::{VocabularyEntry, serialize_saved};
use crate::transcription::models::{TranscriptionModelId, TranscriptionSelection};
mod dictation_processing;
mod hotkeys;
mod persistence;
mod shortcut_repair;
pub use dictation_processing::{
DictationMode, DictationPostProcessing, DictationProcessingSettings,
};
pub use hotkeys::*;
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);
/// [`MeetingRetention::encode`]d; [`RETENTION_UNSET`] until settings apply.
static MEETING_RETENTION: AtomicU8 = AtomicU8::new(RETENTION_UNSET);
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_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);
#[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>,
}
/// Screen corner where the floating meeting recording indicator snaps.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[repr(u8)]
pub enum MeetingIndicatorCorner {
#[default]
TopRight = 0,
TopLeft = 1,
BottomRight = 2,
BottomLeft = 3,
}
impl MeetingIndicatorCorner {
pub const fn is_right(self) -> bool {
matches!(self, Self::TopRight | Self::BottomRight)
}
pub const fn is_top(self) -> bool {
matches!(self, Self::TopRight | Self::TopLeft)
}
const fn decode(value: u8) -> Self {
match value {
1 => Self::TopLeft,
2 => Self::BottomRight,
3 => Self::BottomLeft,
_ => Self::TopRight,
}
}
}
/// Opt-in meeting recording. Detection, the Meetings pane, and the meeting
/// paste shortcut stay off in release builds until `enabled` is set.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct MeetingSettings {
pub enabled: bool,
/// Folder for finished Markdown transcripts; `None` uses the default.
pub output_folder: Option<PathBuf>,
/// Title meetings and write a two-sentence summary with Apple
/// Intelligence when it is available.
pub summarize_with_apple_intelligence: bool,
/// Title meetings and write a two-sentence summary with the OpenCode
/// model, which sends the transcript to it. On a Mac, only when Apple
/// Intelligence is unavailable or off.
pub summarize_with_opencode: bool,
/// Show the floating recording indicator while a meeting is recording.
pub show_recording_indicator: bool,
/// Screen corner the floating recording indicator snaps to after dragging.
pub recording_indicator_corner: MeetingIndicatorCorner,
/// What to do when a call from each website or app is detected. Older
/// files only had a `never_offer` list, whose entries carry no `policy`
/// and so read as Never offer.
#[serde(alias = "never_offer")]
pub providers: Vec<MeetingProviderChoice>,
/// Reminders before calendar meetings (macOS). Off until the user
/// connects a calendar.
pub calendar: CalendarSettings,
/// How long finished meetings are kept before they move to the Trash.
/// `None` until the user chooses: meetings recorded since the default
/// began are kept 24 hours, and older ones stay. Left out of the file
/// while unchosen: a build from before it can't read `null` (#744).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub retention: Option<MeetingRetention>,
}
/// How long a finished meeting is kept, counted from when it ended.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MeetingRetention {
Day,
Week,
Month,
Forever,
}
impl MeetingRetention {
pub const ALL: [Self; 4] = [Self::Day, Self::Week, Self::Month, Self::Forever];
pub const fn label(self) -> &'static str {
match self {
Self::Day => "24 hours",
Self::Week => "7 days",
Self::Month => "30 days",
Self::Forever => "Forever",
}
}
pub const fn max_age_ms(self) -> Option<u64> {
const DAY_MS: u64 = 24 * 60 * 60 * 1_000;
match self {
Self::Day => Some(DAY_MS),
Self::Week => Some(7 * DAY_MS),
Self::Month => Some(30 * DAY_MS),
Self::Forever => None,
}
}
/// The default for meetings recorded since it began.
pub const DEFAULT: Self = Self::Day;
const fn encode(retention: Option<Self>) -> u8 {
match retention {
Some(Self::Day) => 0,
Some(Self::Week) => 1,
Some(Self::Month) => 2,
Some(Self::Forever) => 3,
None => 4,
}
}
const fn decode(value: u8) -> Option<Self> {
match value {
0 => Some(Self::Day),
1 => Some(Self::Week),
2 => Some(Self::Month),
3 => Some(Self::Forever),
_ => None,
}
}
}
/// The connected calendar and its meeting reminders.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct CalendarSettings {
/// Set once the user clicks Connect calendar and macOS grants access;
/// Hex never asks for calendar access before that.
pub connected: bool,
/// Calendars left out of reminders, by EventKit identifier. Every
/// calendar is included by default, so new ones are too.
pub excluded_calendars: Vec<String>,
/// Show a reminder capsule before each meeting.
pub remind: bool,
/// How many minutes before a meeting starts the reminder shows; zero
/// shows it at the start.
pub lead_minutes: u8,
}
/// The reminder lead times Settings offers, in minutes.
pub const CALENDAR_LEAD_MINUTES: [u8; 4] = [0, 1, 2, 5];
impl Default for CalendarSettings {
fn default() -> Self {
Self {
connected: false,
excluded_calendars: Vec::new(),
remind: true,
lead_minutes: 1,
}
}
}
impl CalendarSettings {
/// Whether reminders should run: connected, and wanted.
pub fn reminders_active(&self) -> bool {
self.connected && self.remind
}
/// The lead time, snapped to an offered choice.
pub fn lead(&self) -> std::time::Duration {
let minutes = if CALENDAR_LEAD_MINUTES.contains(&self.lead_minutes) {
self.lead_minutes
} else {
1
};
std::time::Duration::from_secs(u64::from(minutes) * 60)
}
pub fn includes(&self, calendar: &str) -> bool {
!self
.excluded_calendars
.iter()
.any(|excluded| excluded == calendar)
}
}
/// The call services Settings always lists, by provider key (the app's
/// canonical bundle ID, or the website host for browser services) and
/// English name.
pub const KNOWN_MEETING_PROVIDERS: [(&str, &str); 7] = [
("com.tinyspeck.slackmacgap", "Slack huddles"),
("us.zoom.xos", "Zoom"),
("meet.google.com", "Google Meet"),
("com.microsoft.teams2", "Microsoft Teams"),
("com.apple.FaceTime", "FaceTime"),
("net.whatsapp.WhatsApp", "WhatsApp"),
("com.gather.GatherV2", "Gather"),
];
/// What Hex does when it detects a call from a provider.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MeetingPolicy {
/// Offer to record.
#[default]
Ask,
/// Start recording without an offer.
AlwaysRecord,
/// Neither offer nor record.
NeverOffer,
}
/// A website host or an app's canonical bundle ID, the name shown in
/// Settings, and the user's choice for its calls. Unlisted providers Ask.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct MeetingProviderChoice {
pub key: String,
pub label: String,
/// Always written; missing only in a legacy `never_offer` entry.
#[serde(default = "legacy_never_offer")]
pub policy: MeetingPolicy,
}
fn legacy_never_offer() -> MeetingPolicy {
MeetingPolicy::NeverOffer
}
impl Default for MeetingSettings {
fn default() -> Self {
Self {
enabled: false,
output_folder: None,
summarize_with_apple_intelligence: true,
summarize_with_opencode: false,
show_recording_indicator: true,
recording_indicator_corner: MeetingIndicatorCorner::TopRight,
providers: Vec::new(),
calendar: CalendarSettings::default(),
retention: None,
}
}
}
impl MeetingSettings {
/// Whether meetings may record and process: always in developer builds,
/// otherwise once turned on, and never under a managed lock.
pub fn available(&self) -> bool {
crate::labs::Feature::Meetings.managed().is_none()
&& (crate::DEVELOPER_FEATURES_ENABLED || self.enabled)
}
pub fn resolved_output_folder(&self) -> PathBuf {
self.output_folder
.clone()
.filter(|folder| !folder.as_os_str().is_empty())
.unwrap_or_else(default_meeting_output_folder)
}
}
/// 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,
}
}
}
/// The `labs` switches (`crate::labs`), each off by default; older Labs features keep their own keys, and `labs.enabled` is ignored.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct LabsSettings {
/// Live text beside the HUD while dictating.
pub live_text: bool,
/// Live chapters while a meeting records.
pub live_chapters: bool,
/// The playground in the window.
pub playground: bool,
/// Parakeet transcription biased toward the vocabulary.
pub vocabulary_biasing: bool,
/// Mouse buttons may be recorded as shortcuts (macOS, issue 209).
pub mouse_shortcuts: bool,
/// The engine unloads the speech model after `unload_idle_minutes` (5, 15 default, 30, 60) unused (issue 442).
pub unload_idle: bool,
pub unload_idle_minutes: u32,
/// Paste last dictation's row offers its default shortcut back (issue 613).
pub restore_shortcut_default: bool,
/// A pasted dictation stays on the clipboard, not the previous one (macOS, issue 200).
pub keep_on_clipboard: bool,
/// A dictation is put on the clipboard and never pasted (macOS, issue 629).
pub copy_only: bool,
/// Spoken "new line", "new paragraph", and "open/close quote" become line breaks and quotes (issue 630).
pub spoken_formatting: bool,
/// Filler words such as "um" and "uh" are removed from dictations (issue 631).
pub filler_words: bool,
/// `hex meetings show --srt|--vtt` exports a transcript as timed subtitles (macOS, issue 633).
pub subtitle_export: bool,
/// `second_dictation_hotkey` dictates like the dictation shortcut (macOS, issue 627).
pub second_dictation_shortcut: bool,
/// A paste gets a leading space when the character before the cursor wants one (macOS, issue 632).
pub smart_spacing: bool,
/// Spoken symbol words ("comma", "hashtag", "underscore") become characters joined to their words (issue 678).
pub spoken_symbols: bool,
/// The Local transcription picker offers a sort and a "Supports the saved language" toggle (issue 645).
pub picker_sort_filter: bool,
/// The recorder keeps each modifier's side in a modifier-only chord, such as Right ⌘ + Right ⌥ (macOS, issue 710).
pub sided_modifier_chords: bool,
/// In Toggle mode, a press held past the hold threshold dictates until it lifts (macOS, issue 711).
pub tap_or_hold: bool,
/// The picker shows each model's raw error rate, benchmark, source, and conditions (issue 647).
pub benchmark_details: bool,
/// Parakeet Ultra joins the Local transcription picker (issue 648).
pub parakeet_ultra: bool,
/// Menu, Pause, and Scroll Lock may be shortcut keys (Linux, issue 767).
pub standalone_special_keys: bool,
pub history_stats: bool,
pub recent_dictations: bool,
pub skip_pauses: bool,
/// An automatic meeting recording stops after its call ends (macOS, issue 835).
pub stop_when_call_ends: bool,
/// Output's Try card offers Vocabulary and Fix this beside its result (issue 989).
pub output_fixes: bool,
/// The speech model picker lists the model in use first (issue 1019).
pub picker_active_first: bool,
/// The picker's "Use model file where it is…" adds a GGUF file without copying it (issue 941).
pub model_in_place: bool,
/// The picker's All speech models view offers "Only downloaded models" (issue 1018).
pub picker_downloaded: bool,
/// The ISO § key may be a shortcut on its own (Linux, issue 1050).
pub section_key_alone: bool,
/// Dictations saved to History keep their audio, for Transcribe again (issue 1032).
pub keep_recordings: bool,
pub hide_menu_bar_icon: bool,
}
/// The idle times Labs › Unload model when idle offers, in minutes.
pub const UNLOAD_IDLE_MINUTES: [u32; 4] = [5, 15, 30, 60];
impl Default for LabsSettings {
fn default() -> Self {
Self {
live_text: false,
live_chapters: false,
playground: false,
vocabulary_biasing: false,
mouse_shortcuts: false,
unload_idle: false,
unload_idle_minutes: 15,
restore_shortcut_default: false,
keep_on_clipboard: false,
copy_only: false,
spoken_formatting: false,
filler_words: false,
subtitle_export: false,
second_dictation_shortcut: false,
smart_spacing: false,
spoken_symbols: false,
picker_sort_filter: false,
sided_modifier_chords: false,
tap_or_hold: false,
benchmark_details: false,
parakeet_ultra: false,
standalone_special_keys: false,
history_stats: false,
recent_dictations: false,
skip_pauses: false,
stop_when_call_ends: false,
output_fixes: false,
picker_active_first: false,
model_in_place: false,
picker_downloaded: false,
section_key_alone: false,
keep_recordings: false,
hide_menu_bar_icon: false,
}
}
}
/// 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"))
}
pub fn default_meeting_output_folder() -> PathBuf {
dirs::document_dir()
.or_else(|| dirs::home_dir().map(|home| home.join("Documents")))
.unwrap_or_else(|| PathBuf::from("."))
.join(if crate::app_paths::is_macos_test_build() {
"Hex Test Meetings"
} else {
"Hex Meetings"
})
}
/// 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,
}
/// Annotate: Scrawl's captures inside Hex, on macOS, Linux, and Windows
/// (`capture_host`). On by default; off means no capture work at all.
#[cfg(hex_capture)]
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct CaptureSettings {
pub enabled: bool,
/// Annotate's one key: tap to start and stop, hold while recording to
/// draw.
pub hotkey: HotkeyBinding,
pub transcriber: CaptureTranscriber,
/// Where new captures go; `None` is Scrawl's own captures folder.
pub folder: Option<PathBuf>,
/// Days a capture keeps its video, audio, and full-size frames; `None`
/// keeps them.
pub media_days: Option<u32>,
/// Days a capture is kept at all; `None` keeps it.
pub bundle_days: Option<u32>,
/// Where a written capture is sent among OpenCode sessions: Scrawl's
/// router settings, imported once from Scrawl.
pub routing: CaptureRouting,
/// Lets screen recordings, Hex's own captures included, show Hex's
/// overlays: the capture capsule, picker, and ink, the dictation HUD,
/// and the meeting capsules. Off keeps them out (`capture_host`).
pub show_overlays_in_recordings: bool,
/// How the capsule offers where to send a finished capture, while Kit
/// compares the directions.
pub capsule_flow: CapsuleFlow,
}
/// The capsule's flow after a capture stops, one of five prototypes.
#[cfg(hex_capture)]
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CapsuleFlow {
/// (a) "Copied", and the suggestions in a list under the capsule.
#[default]
List,
/// (b) One quiet line, "Send to SEER ⏎"; ⇥ moves to the next guess.
Toast,
/// (c) A short hint of the guesses in the capsule, which then folds
/// into Hex's menu-bar item.
MenuBar,
/// (d) The guesses in a small card at the pointer.
Cursor,
/// (e) A pill hanging from the top edge that grows down into the
/// guesses.
Notch,
}
#[cfg(hex_capture)]
impl CapsuleFlow {
pub const ALL: [Self; 5] = [
Self::List,
Self::Toast,
Self::MenuBar,
Self::Cursor,
Self::Notch,
];
}
#[cfg(hex_capture)]
impl Default for CaptureSettings {
fn default() -> Self {
let week = scrawl_capture::retention::Preset::Week.policy();
Self {
enabled: true,
hotkey: HotkeyBinding::capture_default(),
transcriber: CaptureTranscriber::default(),
folder: None,
media_days: week.media_days,
bundle_days: week.bundle_days,
routing: CaptureRouting::default(),
show_overlays_in_recordings: false,
capsule_flow: CapsuleFlow::default(),
}
}
}
/// Scrawl's router settings (`scrawl_capture::RouterConfig`, its
/// camelCase JSON). Never holds a Jev key: Jev is called with
/// `$OPENCODE_API_KEY` or OpenCode's own credential, so `hex settings`
/// never shows one.
#[cfg(hex_capture)]
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(
from = "scrawl_capture::RouterConfig",
into = "scrawl_capture::RouterConfig"
)]
pub struct CaptureRouting(scrawl_capture::RouterConfig);
// The config's only non-`Eq` field is a JSON value, which compares totally.
#[cfg(hex_capture)]
impl Eq for CaptureRouting {}
#[cfg(hex_capture)]
impl From<scrawl_capture::RouterConfig> for CaptureRouting {
fn from(mut config: scrawl_capture::RouterConfig) -> Self {
config.jev_api_key = None;
Self(config)
}
}
#[cfg(hex_capture)]
impl From<CaptureRouting> for scrawl_capture::RouterConfig {
fn from(routing: CaptureRouting) -> Self {
routing.0
}
}
#[cfg(hex_capture)]
impl CaptureRouting {
pub fn config(&self) -> &scrawl_capture::RouterConfig {
&self.0
}
}
#[cfg(hex_capture)]
impl CaptureSettings {
/// The folder new captures go to.
pub fn captures_dir(&self) -> PathBuf {
self.folder
.clone()
.unwrap_or_else(scrawl_capture::handoff::builtin_captures_dir)
}
pub fn retention(&self) -> scrawl_capture::retention::Policy {
scrawl_capture::retention::Policy {
media_days: self.media_days,
bundle_days: self.bundle_days,
}
}
pub fn set_retention(&mut self, policy: scrawl_capture::retention::Policy) {
self.media_days = policy.media_days;
self.bundle_days = policy.bundle_days;
}
}
/// What turns a capture's narration into words.
#[cfg(hex_capture)]
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CaptureTranscriber {
/// The dictation model Hex already has loaded, with word times.
#[default]
Parakeet,
/// Apple's speech recognizer, as Scrawl uses by default.
Apple,
}
#[cfg(hex_capture)]
impl CaptureTranscriber {
pub const ALL: [Self; 2] = [Self::Parakeet, Self::Apple];
}
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 {
/// 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 › Second dictation shortcut: another shortcut that dictates
/// exactly as `dictation_hotkey` does (macOS). Unbound by default and
/// ignored while its Labs toggle is off.
pub second_dictation_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,
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,
/// 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,
];
#[cfg(not(hex_capture))]
const MIGRATIONS: &[&str] = &[
STREAMING_ENGLISH_MIGRATION,
ANOMALY_IDENTITY_MIGRATION,
MEETING_RETENTION_DEFAULT_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";
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 {
retired_commands_enabled: None,
release_microphone_while_idle: false,
sound_effects: true,
sound_effect_volume: 0.5,
sound_theme: crate::feedback::SoundSet::default(),
microphone: None,
avoid_bluetooth_microphone: true,
recording_audio_behavior: RecordingAudioBehavior::DoNothing,
recording_duck_volume: 0.2,
pause_browser_media: false,
double_tap_lock: true,
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,
second_dictation_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(),
meetings: MeetingSettings::default(),
#[cfg(hex_capture)]
capture: CaptureSettings::default(),
#[cfg(not(hex_capture))]
capture_from_other_build: None,
experimental: ExperimentalSettings::default(),
labs: LabsSettings::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 {