Repository navigation
Expand file tree
/
Copy pathonboarding.rs
More file actions
1842 lines (1691 loc) · 62.6 KB
/
Copy pathonboarding.rs
File metadata and controls
1842 lines (1691 loc) · 62.6 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
//! First-run setup state. macOS gates dictation on its privacy permissions.
//! Windows has one switch that matters, "Let desktop apps access your
//! microphone", which the tour shows only while it is off. Linux has no such
//! grants, so only the transcription model step applies.
use std::fs::{self, OpenOptions};
#[cfg(unix)]
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
use std::path::Path;
#[cfg(target_os = "macos")]
use std::process::Command;
#[cfg(target_os = "macos")]
use block2::RcBlock;
#[cfg(target_os = "macos")]
use objc2::msg_send;
#[cfg(target_os = "macos")]
use objc2::runtime::{AnyClass, Bool};
#[cfg(target_os = "macos")]
use objc2_foundation::NSString;
use crate::transcription_models::TranscriptionSelection;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PermissionState {
Ready,
NeedsRequest,
NeedsSettings,
/// Switched on in System Settings, but macOS applies it to Hex only
/// after Hex restarts.
NeedsRestart,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PermissionKind {
Microphone,
Accessibility,
/// System Audio Recording, asked only when Meetings is on.
SystemAudio,
/// Screen Recording, asked only from the Scrawl pane or at a first
/// capture, never in the tour.
ScreenRecording,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PermissionAction {
/// macOS shows its own prompt the first time.
RequestMicrophone,
/// Everything else is turned on in System Settings, with the guide.
ShowGuide(PermissionKind),
/// Granted, waiting for Hex to restart.
Restart,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PermissionWarning {
pub kind: PermissionKind,
pub action: PermissionAction,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SetupStatus {
pub microphone: PermissionState,
pub accessibility: PermissionState,
pub transcription_model: bool,
}
impl SetupStatus {
pub fn ready(self) -> bool {
self.microphone == PermissionState::Ready
&& self.accessibility == PermissionState::Ready
&& self.transcription_model
}
}
pub fn permission_warnings(status: SetupStatus) -> Vec<PermissionWarning> {
let mut warnings = Vec::with_capacity(2);
match status.microphone {
PermissionState::Ready => {}
PermissionState::NeedsRequest => warnings.push(PermissionWarning {
kind: PermissionKind::Microphone,
action: PermissionAction::RequestMicrophone,
}),
PermissionState::NeedsSettings => warnings.push(PermissionWarning {
kind: PermissionKind::Microphone,
action: PermissionAction::ShowGuide(PermissionKind::Microphone),
}),
PermissionState::NeedsRestart => warnings.push(PermissionWarning {
kind: PermissionKind::Microphone,
action: PermissionAction::Restart,
}),
}
match status.accessibility {
PermissionState::Ready => {}
PermissionState::NeedsRestart => warnings.push(PermissionWarning {
kind: PermissionKind::Accessibility,
action: PermissionAction::Restart,
}),
_ => warnings.push(PermissionWarning {
kind: PermissionKind::Accessibility,
action: PermissionAction::ShowGuide(PermissionKind::Accessibility),
}),
}
warnings
}
/// The first-run tour, in order. `Setup` holds every permission on one
/// screen; `TryIt` is a practice dictation into a field in the window. The
/// speech model downloads in the background from the moment the tour opens.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Step {
Welcome,
Setup,
TryIt,
Done,
}
impl Step {
const TOUR: [Self; 4] = [Self::Welcome, Self::Setup, Self::TryIt, Self::Done];
fn position(self) -> usize {
Self::TOUR
.iter()
.position(|step| *step == self)
.unwrap_or(0)
}
}
/// One row of the setup screen.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SetupItem {
Microphone,
Accessibility,
Model,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ItemStatus {
Ready,
/// Not asked yet.
Todo,
/// Asked; macOS's prompt or System Settings is up. The button reopens it.
Waiting,
/// Refused once: only System Settings can turn it on.
Denied,
/// Switched on; macOS applies it once Hex restarts.
Restart,
/// Downloading, with progress from zero through one.
Downloading(f32),
Failed,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ModelProgress {
pub installed: bool,
pub downloading: Option<f32>,
pub failed: bool,
}
/// What a practice dictation looks like from the event log.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Observation {
Started,
Transcribing,
Discarded,
Cancelled,
Pasted,
Failed,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Practice {
#[default]
Waiting,
Listening,
Transcribing,
/// Released before Hex kept any audio, or the clip was silent.
TooShort,
/// Transcribed, but no words came back.
NothingHeard,
Landed,
Failed,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Input {
Continue,
Back,
/// "Skip" on the practice step.
Skip,
Grant(SetupItem),
Status(SetupStatus, ModelProgress),
Dictation(Observation),
/// The shortcut listener could not start after setup became ready.
ListenerFailed {
relaunch_allowed: bool,
},
Reopen,
/// "Restart Hex" once every permission is on and one waits for it.
Restart,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Effect {
None,
RequestMicrophone,
/// Open the Privacy pane with the guide beside it: drag Hex into the
/// list, or (for a refused microphone) switch it on.
ShowGuide(PermissionKind),
DownloadModel,
/// Every permission just turned on: move to the next step after a beat,
/// so the last check is seen.
AdvanceSoon,
/// Quit and reopen Hex, resuming the tour: at the practice step, or
/// at setup while setup is unfinished.
Relaunch,
/// Close the tour.
Finish,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Row {
pub item: SetupItem,
pub status: ItemStatus,
/// The first row still to do; its button carries the screen's accent.
pub next: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub struct View {
pub step: Step,
/// Position among the dotted steps (every step but `Done`).
pub index: usize,
pub count: usize,
pub rows: Vec<Row>,
/// Every setup row is ready.
pub ready: bool,
/// Dictation can run: permissions and the model are ready.
pub dictation_ready: bool,
pub model: ItemStatus,
/// The tour downloaded the model, so its progress is worth showing
/// outside the setup rows.
pub show_download: bool,
pub practice: Practice,
pub can_go_back: bool,
/// The listener needs a restart Hex will not do by itself again.
pub reopen: bool,
/// Every permission is on, and at least one applies only after Hex
/// restarts: setup's primary action restarts Hex.
pub restart: bool,
}
#[derive(Clone, Debug)]
pub struct Flow {
step: Step,
status: SetupStatus,
model: ModelProgress,
permissions: bool,
/// Windows: the microphone switch was seen off, so its row shows.
microphone_row: bool,
practice_step: bool,
/// Microphone, then Accessibility.
asked: [bool; 2],
/// A refused microphone's System Settings guide is up.
microphone_guide: bool,
practice: Practice,
/// The setup screen keeps its page dot once it has been needed.
setup_needed: bool,
download_requested: bool,
advance_due: bool,
reopen: bool,
relaunching: bool,
}
impl Flow {
/// `permissions` is false where the OS has no privacy grants; `practice`
/// is false where this window cannot observe dictation.
pub fn new(start: Step, status: SetupStatus, permissions: bool, practice: bool) -> Self {
let mut flow = Self {
step: Step::Welcome,
status,
model: ModelProgress {
installed: status.transcription_model,
..ModelProgress::default()
},
permissions,
microphone_row: status.microphone != PermissionState::Ready,
practice_step: practice,
asked: [false; 2],
microphone_guide: false,
practice: Practice::Waiting,
setup_needed: false,
download_requested: false,
advance_due: false,
reopen: false,
relaunching: false,
};
// A tour resumed at setup keeps its page dot: the person was there.
flow.setup_needed = !flow.setup_ready() || start == Step::Setup;
// `status` is read fresh at launch, so a tour resumed after macOS's
// Quit & Reopen passes a setup whose grants are now real, and one
// resumed past setup waits there until they are.
flow.step = if start.position() > Step::Setup.position() && !flow.setup_ready() {
Step::Setup
} else {
flow.forward_from(start)
};
flow
}
pub fn step(&self) -> Step {
self.step
}
pub fn on(&mut self, input: Input) -> Effect {
match input {
Input::Continue => self.primary(),
Input::Back => {
self.step = self.back_from(self.step);
Effect::None
}
Input::Skip if self.step == Step::TryIt => self.advance(),
Input::Skip => Effect::None,
Input::Grant(item) => self.grant(item),
Input::Status(status, model) => self.update(status, model),
Input::Dictation(observation) => {
if self.step == Step::TryIt {
self.practice = next_practice(self.practice, observation);
}
Effect::None
}
Input::ListenerFailed { relaunch_allowed } => {
if relaunch_allowed {
self.relaunch()
} else {
self.reopen = true;
Effect::None
}
}
Input::Reopen if self.reopen => self.relaunch(),
Input::Reopen => Effect::None,
Input::Restart if self.step == Step::Setup && self.restart_needed() => {
self.relaunching = true;
Effect::Relaunch
}
Input::Restart => Effect::None,
}
}
pub fn view(&self) -> View {
let dotted: Vec<Step> = Step::TOUR
.into_iter()
.filter(|step| *step != Step::Done && self.shows(*step))
.collect();
let rows = self.rows();
View {
step: self.step,
index: dotted
.iter()
.position(|step| *step == self.step)
.unwrap_or(dotted.len()),
count: dotted.len(),
rows,
ready: self.setup_ready(),
dictation_ready: self.status.ready(),
model: self.model_status(),
show_download: self.download_requested && !self.model_in_setup(),
practice: self.practice,
can_go_back: self.step != Step::Welcome
&& self.step != Step::Done
&& self.back_from(self.step) != self.step,
reopen: self.reopen,
restart: self.restart_needed(),
}
}
fn restart_needed(&self) -> bool {
let states = [self.status.microphone, self.status.accessibility];
!self.relaunching
&& states.contains(&PermissionState::NeedsRestart)
&& states.iter().all(|state| {
matches!(
state,
PermissionState::Ready | PermissionState::NeedsRestart
)
})
}
/// Where the practice step can wait for the model, the model is not a
/// setup row: it downloads behind the permissions.
fn model_in_setup(&self) -> bool {
!self.permissions || !self.practice_step
}
fn permissions_ready(&self) -> bool {
self.status.microphone == PermissionState::Ready
&& self.status.accessibility == PermissionState::Ready
}
fn setup_ready(&self) -> bool {
self.permissions_ready() && (!self.model_in_setup() || self.status.transcription_model)
}
fn model_status(&self) -> ItemStatus {
if self.status.transcription_model {
ItemStatus::Ready
} else if let Some(progress) = self.model.downloading {
ItemStatus::Downloading(progress)
} else if self.model.failed {
ItemStatus::Failed
} else if self.download_requested {
ItemStatus::Downloading(0.0)
} else {
ItemStatus::Todo
}
}
fn update(&mut self, status: SetupStatus, model: ModelProgress) -> Effect {
let was_ready = self.setup_ready();
self.microphone_row |= status.microphone != PermissionState::Ready;
self.status = status;
self.model = model;
if self.step == Step::Setup && !was_ready && self.setup_ready() {
self.advance_due = true;
}
// The download starts the first time the tour sees no model, before
// any permission is asked, so it runs while the person reads.
if !status.transcription_model
&& model.downloading.is_none()
&& !model.failed
&& !self.download_requested
{
self.download_requested = true;
return Effect::DownloadModel;
}
if std::mem::take(&mut self.advance_due) && self.step == Step::Setup {
return Effect::AdvanceSoon;
}
Effect::None
}
fn rows(&self) -> Vec<Row> {
let mut rows = Vec::with_capacity(4);
if self.permissions || self.microphone_row {
rows.push(Row {
item: SetupItem::Microphone,
status: match self.status.microphone {
PermissionState::Ready => ItemStatus::Ready,
PermissionState::NeedsSettings if self.microphone_guide => ItemStatus::Waiting,
PermissionState::NeedsSettings => ItemStatus::Denied,
PermissionState::NeedsRequest if self.asked[0] => ItemStatus::Waiting,
PermissionState::NeedsRequest => ItemStatus::Todo,
PermissionState::NeedsRestart => ItemStatus::Restart,
},
next: false,
});
}
if self.permissions {
rows.push(Row {
item: SetupItem::Accessibility,
status: match self.status.accessibility {
PermissionState::Ready => ItemStatus::Ready,
PermissionState::NeedsRestart => ItemStatus::Restart,
_ if self.asked[1] => ItemStatus::Waiting,
_ => ItemStatus::Todo,
},
next: false,
});
}
if self.model_in_setup() {
rows.push(Row {
item: SetupItem::Model,
status: self.model_status(),
next: false,
});
}
if let Some(row) = rows.iter_mut().find(|row| {
!matches!(
row.status,
ItemStatus::Ready
| ItemStatus::Downloading(_)
| ItemStatus::Waiting
| ItemStatus::Restart
)
}) {
row.next = true;
}
rows
}
fn shows(&self, step: Step) -> bool {
match step {
Step::TryIt => self.practice_step,
Step::Setup => self.setup_needed || self.step == Step::Setup,
_ => true,
}
}
fn passes(&self, step: Step) -> bool {
match step {
Step::Setup => self.setup_ready(),
Step::TryIt => !self.practice_step,
_ => false,
}
}
fn forward_from(&self, mut step: Step) -> Step {
while self.passes(step) && step != Step::Done {
step = Step::TOUR[step.position() + 1];
}
step
}
fn back_from(&self, step: Step) -> Step {
let mut index = step.position();
while index > 0 {
index -= 1;
if !self.passes(Step::TOUR[index]) {
return Step::TOUR[index];
}
}
step
}
fn advance(&mut self) -> Effect {
if self.step == Step::Done {
return Effect::Finish;
}
self.step = self.forward_from(Step::TOUR[self.step.position() + 1]);
Effect::None
}
fn primary(&mut self) -> Effect {
match self.step {
Step::Setup if !self.setup_ready() => Effect::None,
Step::TryIt if self.practice != Practice::Landed => Effect::None,
_ => self.advance(),
}
}
fn grant(&mut self, item: SetupItem) -> Effect {
match item {
// The model can be retried from any step: its progress follows
// the whole tour.
SetupItem::Model
if !self.status.transcription_model && self.model.downloading.is_none() =>
{
self.model.failed = false;
self.download_requested = true;
Effect::DownloadModel
}
_ if self.step != Step::Setup => Effect::None,
SetupItem::Microphone => {
self.asked[0] = true;
match self.status.microphone {
PermissionState::Ready | PermissionState::NeedsRestart => Effect::None,
PermissionState::NeedsRequest => Effect::RequestMicrophone,
PermissionState::NeedsSettings => {
self.microphone_guide = true;
Effect::ShowGuide(PermissionKind::Microphone)
}
}
}
SetupItem::Accessibility if grantable(self.status.accessibility) => {
self.asked[1] = true;
Effect::ShowGuide(PermissionKind::Accessibility)
}
_ => Effect::None,
}
}
/// Once per tour, and only after dictation is ready: before that, the
/// listener has not been asked to start.
fn relaunch(&mut self) -> Effect {
if self.relaunching || !self.status.ready() {
return Effect::None;
}
self.relaunching = true;
self.reopen = false;
Effect::Relaunch
}
}
/// Not on yet, so System Settings still has something to switch on.
fn grantable(state: PermissionState) -> bool {
!matches!(
state,
PermissionState::Ready | PermissionState::NeedsRestart
)
}
fn next_practice(current: Practice, observation: Observation) -> Practice {
match observation {
Observation::Started => Practice::Listening,
Observation::Transcribing => Practice::Transcribing,
Observation::Discarded if current == Practice::Transcribing => Practice::NothingHeard,
Observation::Discarded => Practice::TooShort,
Observation::Cancelled if current == Practice::Landed => Practice::Landed,
Observation::Cancelled => Practice::Waiting,
Observation::Pasted => Practice::Landed,
Observation::Failed => Practice::Failed,
}
}
/// A relaunch the tour started at most this long ago keeps it from
/// relaunching again, so a grant that never reaches Hex cannot loop.
pub const RELAUNCH_GUARD_MS: u64 = 120_000;
static LISTENER_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Called by the recognition worker when the shortcut listener cannot start.
pub fn note_listener_failure() {
LISTENER_FAILED.store(true, std::sync::atomic::Ordering::Relaxed);
}
pub fn take_listener_failure() -> bool {
LISTENER_FAILED.swap(false, std::sync::atomic::Ordering::Relaxed)
}
pub fn unix_ms() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_millis() as u64)
}
/// Records a relaunch and where the tour resumes after it.
pub fn record_relaunch(now_ms: u64) -> color_eyre::Result<()> {
record_relaunch_at(&crate::app_paths::support_dir()?, now_ms)
}
pub fn relaunch_allowed(now_ms: u64) -> bool {
crate::app_paths::support_dir()
.map(|directory| relaunch_allowed_at(&directory, now_ms))
.unwrap_or(false)
}
/// The step a relaunched Hex resumes at, consumed once.
pub fn take_resume() -> Option<Step> {
let directory = crate::app_paths::support_dir().ok()?;
take_resume_at(&directory, unix_ms())
}
pub(crate) fn record_relaunch_at(directory: &Path, now_ms: u64) -> color_eyre::Result<()> {
fs::create_dir_all(directory)?;
fs::write(directory.join("onboarding-relaunch"), now_ms.to_string())?;
Ok(())
}
fn relaunched_at(directory: &Path) -> Option<u64> {
fs::read_to_string(directory.join("onboarding-relaunch"))
.ok()?
.trim()
.parse()
.ok()
}
pub(crate) fn relaunch_allowed_at(directory: &Path, now_ms: u64) -> bool {
relaunched_at(directory).is_none_or(|at| now_ms.saturating_sub(at) >= RELAUNCH_GUARD_MS)
}
/// A relaunch older than the guard is stale (Hex was quit and reopened
/// later), so the tour does not resume from it.
pub(crate) fn take_resume_at(directory: &Path, now_ms: u64) -> Option<Step> {
let at = relaunched_at(directory)?;
let marker = directory.join("onboarding-resume-consumed");
if marker.is_file() && relaunched_at_consumed(&marker) == Some(at) {
return None;
}
let _ = fs::write(&marker, at.to_string());
(now_ms.saturating_sub(at) < RELAUNCH_GUARD_MS).then_some(Step::TryIt)
}
fn relaunched_at_consumed(marker: &Path) -> Option<u64> {
fs::read_to_string(marker).ok()?.trim().parse().ok()
}
/// Remembers the tour's step, so a tour quit part-way (macOS's own "Quit &
/// Reopen" after a grant, or ⌘Q) resumes there.
pub fn record_step(step: Step) {
let result =
crate::app_paths::support_dir().and_then(|directory| record_step_at(&directory, step));
if let Err(error) = result {
tracing::warn!(%error, "could not record the onboarding step");
}
}
pub fn saved_step() -> Option<Step> {
saved_step_at(&crate::app_paths::support_dir().ok()?)
}
pub(crate) fn record_step_at(directory: &Path, step: Step) -> color_eyre::Result<()> {
let name = match step {
Step::Welcome => "welcome",
Step::Setup => "setup",
Step::TryIt => "try-it",
Step::Done => "done",
};
fs::create_dir_all(directory)?;
fs::write(directory.join("onboarding-step"), name)?;
Ok(())
}
pub(crate) fn saved_step_at(directory: &Path) -> Option<Step> {
match fs::read_to_string(directory.join("onboarding-step"))
.ok()?
.trim()
{
"setup" => Some(Step::Setup),
"try-it" => Some(Step::TryIt),
"done" => Some(Step::Done),
_ => None,
}
}
pub fn completion_recorded() -> bool {
let Ok(directory) = crate::app_paths::support_dir() else {
return false;
};
completion_recorded_at(&directory)
}
pub fn record_completion() -> color_eyre::Result<()> {
let directory = crate::app_paths::support_dir()?;
record_completion_at(&directory)
}
pub(crate) fn completion_recorded_at(directory: &Path) -> bool {
if directory.join("onboarding-complete").is_file() {
return true;
}
if directory.join("onboarding-pending").is_file() || !directory.join("settings.json").is_file()
{
return false;
}
if let Err(error) = record_completion_at(directory) {
tracing::warn!(%error, "could not migrate onboarding completion");
}
true
}
/// Once per settings file from before `anomaly.hex` (2.3.1 shared the `hex`
/// folder): macOS gave the new identity none of the old grants, so setup
/// that is not ready at launch reopens the tour instead of counting the old
/// completion. Setup that is ready changes nothing.
#[cfg(target_os = "macos")]
pub fn recheck_after_identity_change(
settings: &mut crate::app_settings::AppSettings,
setup_ready: bool,
) {
let result = crate::app_paths::support_dir()
.and_then(|directory| recheck_after_identity_change_at(&directory, settings, setup_ready));
match result {
Ok(true) => {
tracing::info!("setup is not ready under the new identity; reopening onboarding")
}
Ok(false) => {}
Err(error) => tracing::warn!(%error, "could not recheck onboarding for the new identity"),
}
}
/// True when it reopened the tour.
#[cfg(target_os = "macos")]
pub(crate) fn recheck_after_identity_change_at(
directory: &Path,
settings: &mut crate::app_settings::AppSettings,
setup_ready: bool,
) -> color_eyre::Result<bool> {
if !settings.predates_anomaly_identity() {
return Ok(false);
}
let reopen = !setup_ready;
if reopen {
record_pending_at(directory)?;
for marker in ["onboarding-complete", "onboarding-step"] {
match fs::remove_file(directory.join(marker)) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
return Err(error.into());
}
_ => {}
}
}
crate::durable::sync_directory(directory)?;
}
settings.record_anomaly_identity(&directory.join("settings.json"))?;
Ok(reopen)
}
/// Forgets that onboarding finished, so the window shows it again. Only the
/// onboarding markers change: settings, history, models, and permissions stay.
pub fn reset() -> color_eyre::Result<()> {
reset_at(&crate::app_paths::support_dir()?)
}
pub(crate) fn reset_at(directory: &Path) -> color_eyre::Result<()> {
record_pending_at(directory)?;
for marker in [
"onboarding-complete",
"onboarding-step",
"onboarding-relaunch",
] {
match fs::remove_file(directory.join(marker)) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
return Err(error.into());
}
_ => {}
}
}
crate::durable::sync_directory(directory)?;
Ok(())
}
pub(crate) fn record_pending_at(directory: &Path) -> color_eyre::Result<()> {
fs::create_dir_all(directory)?;
write_owner_only_marker(&directory.join("onboarding-pending"), false)?;
crate::durable::sync_directory(directory)?;
Ok(())
}
pub(crate) fn record_completion_at(directory: &Path) -> color_eyre::Result<()> {
fs::create_dir_all(directory)?;
let destination = directory.join("onboarding-complete");
let temporary = directory.join(".onboarding-complete.tmp");
write_owner_only_marker(&temporary, true)?;
fs::rename(temporary, destination)?;
crate::durable::sync_directory(directory)?;
Ok(())
}
fn write_owner_only_marker(path: &Path, truncate: bool) -> color_eyre::Result<()> {
let mut options = OpenOptions::new();
options.create(true).truncate(truncate).write(true);
#[cfg(unix)]
options.mode(0o600);
let file = options.open(path)?;
#[cfg(unix)]
file.set_permissions(fs::Permissions::from_mode(0o600))?;
file.sync_all()?;
Ok(())
}
pub fn status(selection: &TranscriptionSelection) -> SetupStatus {
let transcription_model = crate::transcription_models::validate(selection)
.is_ok_and(|model| crate::transcription_models::is_installed(model, &selection.language));
status_with_transcription_model(transcription_model)
}
#[cfg(target_os = "macos")]
pub fn status_with_transcription_model(transcription_model: bool) -> SetupStatus {
SetupStatus {
microphone: microphone_state(),
// Accessibility also grants the listen-event access Hex's shortcut
// taps need, so Input Monitoring is never asked for.
accessibility: accessibility_state(CGPreflightPostEventAccess(), AXIsProcessTrusted()),
transcription_model,
}
}
#[cfg(not(target_os = "macos"))]
pub fn status_with_transcription_model(transcription_model: bool) -> SetupStatus {
SetupStatus {
#[cfg(target_os = "windows")]
microphone: windows_microphone_state(),
#[cfg(not(target_os = "windows"))]
microphone: PermissionState::Ready,
accessibility: PermissionState::Ready,
transcription_model,
}
}
/// Windows Settings' "Where Hex turns the microphone on".
#[cfg(target_os = "windows")]
pub const WINDOWS_MICROPHONE_SETTINGS: &str = "ms-settings:privacy-microphone";
/// Off when the device-wide, per-user, or desktop-apps microphone switch in
/// Settings › Privacy & security › Microphone says `Deny`. Windows never
/// prompts desktop apps, so only Settings turns it back on.
#[cfg(target_os = "windows")]
fn windows_microphone_state() -> PermissionState {
use winreg::RegKey;
use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ};
const CONSENT: &str = r"Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\microphone";
let denied = |root, path: &str| {
RegKey::predef(root)
.open_subkey_with_flags(path, KEY_READ)
.and_then(|key| key.get_value::<String, _>("Value"))
.is_ok_and(|value| value.eq_ignore_ascii_case("Deny"))
};
if denied(HKEY_LOCAL_MACHINE, CONSENT)
|| denied(HKEY_CURRENT_USER, CONSENT)
|| denied(HKEY_CURRENT_USER, &format!(r"{CONSENT}\NonPackaged"))
{
PermissionState::NeedsSettings
} else {
PermissionState::Ready
}
}
#[cfg(target_os = "macos")]
pub fn request_microphone() {
let Some(class) = AnyClass::get(c"AVCaptureDevice") else {
tracing::error!("AVCaptureDevice is unavailable");
return;
};
let handler = RcBlock::new(|granted: Bool| {
tracing::info!(
granted = granted.as_bool(),
"microphone permission request finished"
);
});
unsafe {
let _: () = msg_send![
class,
requestAccessForMediaType: &*AVMediaTypeAudio,
completionHandler: &*handler
];
}
}
/// Reopens the installed app once this process exits. Returns false outside
/// an app bundle (a development binary), where the person reopens Hex.
/// The relaunch keeps this process's `HEX_*` environment.
#[cfg(target_os = "macos")]
pub fn spawn_relaunch() -> bool {
let Ok(executable) = std::env::current_exe() else {
return false;
};
let Some(bundle) = executable
.ancestors()
.nth(3)
.filter(|path| path.extension().is_some_and(|extension| extension == "app"))
else {
return false;
};
Command::new("/bin/sh")
.args(relaunch_arguments(
std::process::id(),
bundle,
std::env::vars_os(),
))
.spawn()
.inspect_err(|error| tracing::error!(%error, "could not schedule relaunch"))
.is_ok()
}
/// `/bin/sh` arguments that wait for `pid` to exit, then open `bundle` with
/// the forwarded environment. Waiting keeps the relaunched copy from racing
/// the instance lock; `open` without -n leaves a single copy.
#[cfg(target_os = "macos")]
fn relaunch_arguments(
pid: u32,
bundle: &Path,
vars: impl IntoIterator<Item = (std::ffi::OsString, std::ffi::OsString)>,
) -> Vec<std::ffi::OsString> {
let mut arguments: Vec<std::ffi::OsString> = vec![
"-c".into(),
"pid=$1; shift; while kill -0 \"$pid\" 2>/dev/null; do sleep 0.1; done; \
exec /usr/bin/open \"$@\""
.into(),
"hex-relaunch".into(),
pid.to_string().into(),
];
arguments.extend(open_env_arguments(vars));
arguments.push(bundle.into());
arguments
}
/// `open --env` arguments for every `HEX_*` variable in `vars`
/// (HEX_RETAIN_DICTATION_AUDIO, HEX_ENABLE_LLM, HEX_EXPERIMENTAL_MIC, …), sorted.
/// LaunchServices starts apps without the caller's environment, so a
/// relaunch or `hex start` passes these explicitly. Values go only to
/// `open`'s arguments; never log them.
#[cfg(target_os = "macos")]
pub fn open_env_arguments(
vars: impl IntoIterator<Item = (std::ffi::OsString, std::ffi::OsString)>,
) -> Vec<std::ffi::OsString> {
let mut forwarded = vars
.into_iter()
.filter(|(key, _)| key.to_str().is_some_and(|key| key.starts_with("HEX_")))
.collect::<Vec<_>>();
forwarded.sort();
forwarded
.into_iter()
.flat_map(|(key, value)| {
let mut pair = key;
pair.push("=");
pair.push(value);
[std::ffi::OsString::from("--env"), pair]
})
.collect()
}
#[cfg(target_os = "macos")]
fn microphone_state() -> PermissionState {
let Some(class) = AnyClass::get(c"AVCaptureDevice") else {
return PermissionState::NeedsRequest;
};
let status: isize =
unsafe { msg_send![class, authorizationStatusForMediaType: &*AVMediaTypeAudio] };
microphone_authorization_state(status)