Repository navigation
Expand file tree
/
Copy pathmacos_rune.rs
More file actions
1439 lines (1358 loc) · 55.2 KB
/
Copy pathmacos_rune.rs
File metadata and controls
1439 lines (1358 loc) · 55.2 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
//! Hex on macOS (`hex app`): one menu-bar process.
//!
//! - The main thread runs Rune's event loop (`rune::App`, windowless and
//! kept running, as an accessory app) and, beside it on the same AppKit
//! run loop, the native status item, the updater, the main menu, the Dock
//! reopen handler, and the Metal dictation HUD. A 16 ms main-loop timer
//! ([`Pump`]) drives them, so they keep working with no window open.
//! - The runtime thread owns model preparation, starts the listener once
//! setup is ready, and publishes the listener, model, update, and settings
//! state the window shows ([`RuntimeHandle`]).
//! - The listener (`recognition::listen`), the meeting controller, and the
//! local API keep their own threads.
//!
//! Closing the window hides it; Quit (menu bar, ⌘Q, `hex quit`, `hex restart`
//! and the onboarding relaunch after scheduling the new copy, or Ctrl-C) ends
//! the loop, then stops and joins everything and ends the process with
//! `_exit` ([`crate::desktop::process_exit`]). AppKit's own terminate
//! (the quit Apple event, logout) does the same from its
//! will-terminate notification.
//!
//! The meeting capsules (offer, call ended, ready, recording) are Rune
//! overlays (`rune_ui::meeting_capsules`): non-activating panels fed from
//! the controller events here.
use std::cell::RefCell;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, SyncSender};
use std::sync::{Arc, Mutex, OnceLock};
use std::thread;
use std::time::{Duration, Instant};
use block2::RcBlock;
use color_eyre::Result;
use color_eyre::eyre::eyre;
use objc2::rc::Retained;
use objc2::runtime::{AnyObject, NSObjectProtocol, Sel};
use objc2::{MainThreadOnly, msg_send, sel};
use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSMenu, NSMenuItem};
use objc2_foundation::{MainThreadMarker, NSAppleEventManager, NSObject, NSString, NSTimer};
use crate::app_settings::AppSettings;
use crate::desktop::host::{
DesktopAction, DesktopListenerSnapshot, DesktopShortcut, DesktopShortcuts,
DesktopTranscriptionSnapshot, DesktopUpdateStatus,
};
use crate::dictation::indicator::DictationIndicatorEvent;
use crate::macos_rune::status_item::StatusItemAction;
use crate::meeting::MeetingRequest;
use crate::meeting::watcher::{ControllerEvent, ListenerConfig, MeetingMenuState};
use crate::recognition::RecognitionControl;
use crate::rune_hud::DictationIndicatorUi;
use crate::rune_ui::{Destination, Ui};
use crate::transcription::models::{
ModelPreparationStage, TranscriptionModelId, TranscriptionSelection,
};
use crate::transcription::preparation::TranscriptionPreparation;
mod control;
pub(crate) mod status_item;
#[cfg(test)]
mod tests;
/// How often the runtime refreshes while nothing is asked.
const RUNTIME_TICK: Duration = Duration::from_millis(250);
/// The main-loop timer: the HUD follows the pointer and channels drain.
const PUMP_INTERVAL: f64 = 0.016;
/// Seconds a window opened at launch has to draw its first frame before the
/// status item, HUD, and menu are set up anyway.
const LAUNCH_SETUP_DEADLINE: f64 = 1.0;
const MODEL_MENU_REFRESH: Duration = Duration::from_secs(1);
const MEETING_MENU_REFRESH: Duration = Duration::from_millis(500);
/// 'aevt' / 'rapp': the Apple event LaunchServices sends when the app is
/// opened again while it runs (Dock, Finder, `open`).
const CORE_EVENT_CLASS: u32 = u32::from_be_bytes(*b"aevt");
const REOPEN_APPLICATION: u32 = u32::from_be_bytes(*b"rapp");
/// What the window asks the runtime, in the Linux service's vocabulary so
/// the shared panes send the same requests on every platform.
#[derive(Clone, Debug)]
pub(crate) enum Request {
/// Update actions go to the updater from the window (`rune_ui::host`).
Desktop(#[allow(dead_code)] DesktopAction),
/// Handled in the window (`rune_ui::host`): an AppKit event monitor.
CaptureShortcutFor(#[allow(dead_code)] ShortcutTarget),
CancelShortcut,
/// Linux's service registers recorded shortcuts; on macOS the window
/// saves them and the listener follows `settings.json`.
#[allow(dead_code)]
SetShortcut {
target: ShortcutTarget,
shortcut: DesktopShortcut,
},
ChooseModel {
model: TranscriptionModelId,
language: String,
},
/// The menu bar's model list: only installed models, never a download.
SelectInstalledModel(TranscriptionModelId),
/// `hex model use`: this exact selection, installed only, never a download.
UseInstalledSelection(TranscriptionSelection),
/// Snapshot from the main-thread TIS observer, not a shortcut event.
InputSourceChanged(Option<String>),
CancelModel,
/// The window saved `settings.json`; adopt it.
ReloadSettings,
}
/// A shortcut the listener registers.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) enum ShortcutTarget {
#[default]
Dictation,
PasteLast,
#[cfg(hex_capture)]
Capture,
RawDictation,
/// Labs › Second dictation shortcut.
SecondDictation,
/// Toggle mode's cancel shortcut.
Cancel,
}
/// What the runtime last published for the window and the menu bar.
#[derive(Clone, PartialEq)]
pub(crate) struct Published {
pub(crate) listener: DesktopListenerSnapshot,
pub(crate) transcription: DesktopTranscriptionSnapshot,
pub(crate) update_status: DesktopUpdateStatus,
pub(crate) update_notes: Option<crate::desktop::host::UpdateNotes>,
pub(crate) settings: AppSettings,
preparation: crate::transcription::preparation::PreparationStatus,
}
type Wake = Arc<dyn Fn() + Send + Sync>;
#[derive(Default)]
struct Shared {
published: Mutex<Option<Arc<Published>>>,
wakers: Mutex<Vec<Wake>>,
}
/// The window's and the menu bar's connection to the runtime.
#[derive(Clone)]
pub(crate) struct RuntimeHandle {
requests: Sender<Request>,
shared: Arc<Shared>,
meeting_requests: SyncSender<MeetingRequest>,
recognition_controls: SyncSender<RecognitionControl>,
history: Option<crate::history::History>,
event_path: PathBuf,
indicator: crate::dictation::indicator::DictationIndicatorSender,
}
impl RuntimeHandle {
/// The listener's event log, which the tour reads for practice dictations.
pub(crate) fn event_path(&self) -> &Path {
&self.event_path
}
pub(crate) fn history(&self) -> Option<crate::history::History> {
self.history.clone()
}
/// The dictation HUD, for HUD Lab.
pub(crate) fn indicator(&self, event: DictationIndicatorEvent) {
self.indicator.send(event);
}
pub(crate) fn send(&self, request: Request) -> Result<()> {
if matches!(
&request,
Request::ChooseModel { .. }
| Request::SelectInstalledModel(_)
| Request::UseInstalledSelection(_)
| Request::CancelModel
| Request::ReloadSettings
) && let Some(mtm) = MainThreadMarker::new()
&& let Some(source) = crate::keyboard_input_sources::take_change(mtm)
{
// Deliver a source change not yet pumped before this UI/control
// choice, so it cannot later undo the newer manual choice.
self.requests
.send(Request::InputSourceChanged(source))
.map_err(|_| eyre!("Hex's runtime stopped"))?;
}
self.requests
.send(request)
.map_err(|_| eyre!("Hex's runtime stopped"))
}
pub(crate) fn published(&self) -> Option<Arc<Published>> {
lock(&self.shared.published).clone()
}
/// Wakes `wake` after every publication.
pub(crate) fn subscribe(&self, wake: Wake) {
lock(&self.shared.wakers).push(wake);
}
pub(crate) fn meeting(&self, request: MeetingRequest) -> Result<(), String> {
self.meeting_requests
.try_send(request)
.map_err(|error| format!("could not reach the meeting recorder: {error}"))
}
pub(crate) fn recognition(&self, control: RecognitionControl) -> Result<(), String> {
self.recognition_controls
.try_send(control)
.map_err(|error| format!("could not reach the listener: {error}"))
}
}
static RUNTIME: OnceLock<RuntimeHandle> = OnceLock::new();
static WINDOW: OnceLock<rune::AppHandle<Ui>> = OnceLock::new();
static UPDATER: OnceLock<crate::updater::Updater> = OnceLock::new();
/// The running app's runtime; `None` outside [`run`] (headless snapshots).
pub(crate) fn runtime() -> Option<RuntimeHandle> {
RUNTIME.get().cloned()
}
/// Carries out an update control from the window, a menu, or `hex`. Restart
/// to update finishes on the updater's worker; the pump then quits.
pub(crate) fn update_action(action: &crate::desktop::host::DesktopAction) -> Result<()> {
UPDATER
.get()
.ok_or_else(|| eyre!("the updater is not running"))?
.act(action)
}
pub(crate) fn update_status() -> DesktopUpdateStatus {
UPDATER.get().map_or(
DesktopUpdateStatus::Unavailable,
crate::updater::Updater::status,
)
}
/// Quits Hex from any thread.
pub(crate) fn quit() {
if let Some(window) = WINDOW.get() {
window.quit();
}
}
/// The window closed (hidden): the Dock follows the saved preference again.
pub(crate) fn window_closed() {
let show_dock_icon = AppSettings::load()
.map(|settings| settings.show_dock_icon)
.unwrap_or(false);
crate::app_settings::set_dock_icon_visible(crate::app_settings::dock_icon_visible(
show_dock_icon,
crate::macos_rune::status_item::installed(),
));
}
fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
let detail = payload
.downcast_ref::<&str>()
.copied()
.or_else(|| payload.downcast_ref::<String>().map(String::as_str))
.unwrap_or("unknown cause");
format!("the listener panicked: {detail}")
}
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(|error| error.into_inner())
}
/// Asks a running 2.3.1 or Swift Hex to quit once this Hex is ready to
/// listen, so the two never answer the same shortcut. The old app stays
/// installed.
fn quit_legacy_hex() {
objc2::rc::autoreleasepool(|_| {
for bundle_id in crate::desktop::onboarding::LEGACY_MAC_BUNDLE_IDS {
for app in objc2_app_kit::NSRunningApplication::runningApplicationsWithBundleIdentifier(
&NSString::from_str(bundle_id),
) {
if app.terminate() {
tracing::info!(bundle_id, "asked the old Hex to quit");
} else {
tracing::warn!(bundle_id, "the old Hex did not agree to quit");
}
}
}
});
}
/// Samples footprint and CPU for the life of the app (every 10 s in release, 2 s in debug
/// builds) and logs a warning on a large footprint, steady growth, or a busy core.
fn watch_process() {
let config = if cfg!(debug_assertions) {
procwatch::Config::dev("hex")
} else {
procwatch::Config::release("hex")
};
procwatch::watch_with(config, |event, _| tracing::warn!(%event, "process watch"));
}
pub fn run(shutdown: &'static AtomicBool, listener: ListenerConfig) -> Result<()> {
let Some(mtm) = MainThreadMarker::new() else {
return Err(eyre!("desktop startup requires the main thread"));
};
shutdown.store(false, Ordering::Relaxed);
watch_process();
crate::keyboard::initialize_layout()?;
crate::updater::finish_on_launch();
let _ = UPDATER.set(crate::updater::Updater::start());
// Never a silent launch failure: unreadable settings start with defaults
// and the window says why (#744).
let (mut settings, settings_error) = AppSettings::load_for_launch();
// Preload bundled feedback sounds on a worker so onboarding and the Sounds
// sheet play immediately even before permissions let `recognition` start.
// Opens no audio output device until a tone actually plays.
let _ = crate::feedback::preload();
// Known before the observer's first report, so launching keeps the saved
// model instead of applying the current source's mapping.
let initial_input_source = settings
.keyboard_model_switching
.enabled
.then(|| crate::keyboard_input_sources::current(mtm))
.flatten();
let setup_ready = crate::desktop::onboarding::status(&settings.transcription).ready();
crate::desktop::onboarding::recheck_after_identity_change(&mut settings, setup_ready);
let onboarding_completed = crate::desktop::onboarding::completion_recorded();
let history = match crate::history::History::open_default(settings.history_retention) {
Ok(history) => Some(history),
Err(error) => {
tracing::warn!(%error, "dictation history is unavailable");
None
}
};
let event_path = listener.event_path.clone();
let event_log = crate::desktop::events::EventLog::create(&event_path)?;
let drained_event_log = event_log.clone();
let (developer_sender, developer_receiver) = mpsc::sync_channel(8);
let (control_sender, control_receiver) = mpsc::sync_channel(8);
let (recognition_controls, recognition_control_receiver) = mpsc::sync_channel(8);
let mut local_api = crate::local_api::LocalApi::start(
event_log.clone(),
crate::local_api::LocalApiOptions {
developer_control: crate::DEVELOPER_FEATURES_ENABLED.then(|| developer_sender.clone()),
dictation_control: Some(recognition_controls.clone()),
control: Some(control_sender),
..Default::default()
},
)?;
let (controller_events_sender, controller_events) = mpsc::sync_channel(32);
let (controller_commands, controller_command_receiver) = mpsc::sync_channel(8);
let (meeting_requests, meeting_request_receiver) = mpsc::sync_channel(8);
let (indicator, indicator_events) = crate::dictation::indicator::channel();
// The controller idles without inspecting microphone activity until the
// user opts in to meetings (always available in developer builds).
let controller = thread::Builder::new()
.name("hex-meetings".into())
.spawn(move || {
if let Err(error) = crate::meeting::watcher::controller_loop(
shutdown,
controller_events_sender.clone(),
controller_command_receiver,
meeting_request_receiver,
) {
tracing::error!(%error, "meeting controller stopped");
let _ = controller_events_sender.send(ControllerEvent::Failed {
title: "Meeting detection stopped".into(),
error: error.to_string(),
});
}
})?;
// The microphone stays cold until setup is ready; the runtime starts it.
let (recognition_start, start_receiver) = mpsc::sync_channel(1);
let recognition_indicator = indicator.clone();
let recognition_history = history.clone();
let listener_failure = Arc::new(Mutex::new(None::<String>));
let recognition_failure = listener_failure.clone();
let recognition = thread::Builder::new()
.name("hex-listener".into())
.spawn(move || {
if !setup_ready {
loop {
if shutdown.load(Ordering::Relaxed) {
return;
}
match start_receiver.recv_timeout(Duration::from_millis(100)) {
Ok(()) => break,
Err(RecvTimeoutError::Timeout) => continue,
Err(RecvTimeoutError::Disconnected) => return,
}
}
}
quit_legacy_hex();
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
crate::recognition::listen(
event_log,
listener.device.as_deref(),
shutdown,
Some(recognition_indicator.clone()),
recognition_history,
Some(recognition_control_receiver),
)
}));
let failure = match result {
Ok(Ok(())) => return,
Ok(Err(error)) => {
tracing::error!(%error, "desktop recognition stopped");
let message = format!("{error:#}");
if message.contains("event tap") {
crate::desktop::onboarding::note_listener_failure();
}
message
}
// The panic hook has already logged it.
Err(payload) => panic_message(payload.as_ref()),
};
*lock(&recognition_failure) = Some(failure);
recognition_indicator.send(DictationIndicatorEvent::Failed);
})?;
let (requests, request_receiver) = mpsc::channel();
let shared = Arc::new(Shared::default());
let handle = RuntimeHandle {
requests: requests.clone(),
shared: shared.clone(),
meeting_requests: meeting_requests.clone(),
recognition_controls: recognition_controls.clone(),
history: history.clone(),
event_path,
indicator: indicator.clone(),
};
RUNTIME
.set(handle.clone())
.map_err(|_| eyre!("the Hex runtime already started"))?;
let runtime_settings = settings.clone();
let runtime = thread::Builder::new()
.name("hex-runtime".into())
.spawn(move || {
run_runtime(
runtime_settings,
initial_input_source,
request_receiver,
&shared,
shutdown,
(!setup_ready).then_some(recognition_start),
listener_failure,
)
})?;
// A closed window is only ordered out, and AppKit keeps it on the Space
// it was last shown on: reopening it from the menu bar would switch back
// to that Space. Bring it to the active Space instead.
let native = rune::MacWindowOptions::default()
.collection_behavior(objc2_app_kit::NSWindowCollectionBehavior::MoveToActiveSpace.0);
let mut app = crate::rune_ui::app(Default::default())
.args(Vec::new())
.accessory()
.macos_window(native);
// The first-run tour opens centred at one size; a tiling window manager
// would otherwise stretch it to half the screen.
if !onboarding_completed {
app = app.window_options(crate::rune_ui::fixed_window());
}
let window = app.handle();
let _ = WINDOW.set(window.clone());
// The status item is created inside the loop; Hex can't run without a
// way back to its window, so a failed item opens the window there.
let open_at_launch = settings_error.is_some()
|| crate::meeting::watcher::should_open_app_on_launch(
settings.show_dock_icon,
setup_ready,
onboarding_completed,
true,
);
if let Some(error) = settings_error {
window.update(move |ui, _| crate::rune_ui::show_error(ui, error));
}
app = if open_at_launch {
app.keep_running()
} else {
app.windowless()
};
let capsules = {
let window = window.clone();
crate::rune_ui::meeting_capsules::MeetingCapsules::install(
&mut app,
controller_commands,
{
let window = window.clone();
move |choice| {
crate::app_settings::save_meeting_provider(choice.clone());
window.update(move |ui, _| crate::rune_ui::meeting_provider_chosen(ui, choice));
}
},
move |corner| {
crate::app_settings::save_meeting_indicator_corner(corner);
window.update(move |ui, _| crate::rune_ui::meeting_corner_moved(ui, corner));
},
)
};
let hud = crate::rune_hud::install(&mut app);
crate::rune_ui::live_text::install(&mut app, crate::rune_hud::live_text_place);
// The capture capsule, picker, and ink.
#[cfg(hex_capture)]
let capture_overlays =
Some(crate::rune_ui::capture_capsule::feed::CaptureOverlays::install(&mut app));
let pump = Pump {
window: window.clone(),
capsules,
#[cfg(hex_capture)]
capture_overlays,
runtime: handle,
shutdown,
indicator_events,
hud,
status_actions: None,
controller_events,
developer_calls: developer_receiver,
control_calls: control_receiver,
meeting_waiters: Vec::new(),
meeting_state: MeetingMenuState::Idle,
meeting_menu_at: Instant::now(),
model_menu_at: Instant::now(),
show_dock_icon: settings.show_dock_icon,
};
// Quit ends the loop and finishes below; AppKit's own terminate (the quit
// Apple event, logout) would `exit` from inside it, so its
// will-terminate notification finishes there instead.
DRAIN.set(move || {
shutdown.store(true, Ordering::Relaxed);
if let Some(updater) = UPDATER.get() {
updater.stop();
updater.install_on_quit();
}
drop(requests);
local_api.shutdown();
// The listener owns the transcription engine; joining it frees the
// model after its last use.
for (name, worker) in [
("recognition", recognition),
("meeting controller", controller),
("runtime", runtime),
] {
if worker.join().is_err() {
tracing::error!("{name} worker panicked during shutdown");
}
}
crate::audio::recording_environment::wait_until_restored(Duration::from_secs(2));
if let Err(error) = drained_event_log.flush_within(Duration::from_millis(500)) {
tracing::warn!(%error, "could not flush the event log before quitting");
}
});
// AppKit's terminate may come from the loop's first turn, so its observer
// is in place before the loop runs; the rest of `target` waits below.
let target = MenuTarget::new(mtm);
observe_termination(&target);
// The status item, HUD, and main menu wait for the window's first frame
// so it reaches the screen without them; a launch without a window sets
// them up in the loop's first turn. None of these updates change what the
// window shows, so none asks for a frame.
LAUNCH.with(|slot| *slot.borrow_mut() = Some(Launch { pump, target }));
if open_at_launch {
let ready = window.clone();
app = app.on_ready(move |_| {
ready.update_if(|_, _| {
start_main_thread();
false
});
});
window.update_if(|_, _| {
start_main_thread_after(LAUNCH_SETUP_DEADLINE);
false
});
} else {
window.update_if(|_, _| {
start_main_thread();
false
});
}
app.run();
PUMP.with(|slot| {
if let Some(state) = slot.borrow_mut().take() {
state.timer.invalidate();
}
});
crate::desktop::process_exit::finish(&DRAIN)
}
/// Stops and joins the runtime, listener, meeting controller, and local API.
static DRAIN: crate::desktop::process_exit::Drain = crate::desktop::process_exit::Drain::new();
// ---------------------------------------------------------------------------
// Runtime thread
fn run_runtime(
settings: AppSettings,
initial_input_source: Option<String>,
requests: Receiver<Request>,
shared: &Shared,
shutdown: &AtomicBool,
recognition_start: Option<SyncSender<()>>,
listener_failure: Arc<Mutex<Option<String>>>,
) {
let mut runtime = Runtime {
keyboard_switcher: crate::transcription::keyboard_model_switching::Switcher::new(
settings.keyboard_model_switching.clone(),
initial_input_source,
),
automatic_preparation: false,
settings,
preparation: TranscriptionPreparation::default(),
recognition_start,
listener_failure,
};
loop {
let mut next = match requests.recv_timeout(RUNTIME_TICK) {
Ok(request) => Some(request),
Err(RecvTimeoutError::Timeout) => None,
Err(RecvTimeoutError::Disconnected) => break,
};
while let Some(request) = next {
runtime.handle(request);
next = requests.try_recv().ok();
}
if shutdown.load(Ordering::Relaxed) {
break;
}
runtime.tick();
let published = Arc::new(runtime.publish());
let changed = {
let mut current = lock(&shared.published);
let changed = current.as_deref() != Some(&published);
if changed {
*current = Some(published);
}
changed
};
if changed {
for wake in lock(&shared.wakers).iter() {
wake();
}
}
}
runtime.preparation.cancel();
}
/// Two selections that load the same thing.
fn same_model_and_language(left: &TranscriptionSelection, right: &TranscriptionSelection) -> bool {
left.model == right.model && left.language == right.language
}
struct Runtime {
settings: AppSettings,
preparation: TranscriptionPreparation,
keyboard_switcher: crate::transcription::keyboard_model_switching::Switcher,
automatic_preparation: bool,
/// Starts the listener once setup is ready; `None` once started.
recognition_start: Option<SyncSender<()>>,
/// Why the listener stopped, once it has.
listener_failure: Arc<Mutex<Option<String>>>,
}
impl Runtime {
fn handle(&mut self, request: Request) {
match request {
Request::ChooseModel { model, language } => {
self.manual_choice();
let selection = TranscriptionSelection { model, language };
self.preparation.start(selection, false);
}
Request::SelectInstalledModel(model) => {
self.reload_settings();
self.manual_choice();
self.preparation
.start(self.settings.transcription_for_model(model), true);
}
Request::UseInstalledSelection(selection) => {
self.manual_choice();
// `hex model use` replies "already in use" on the same test.
if !same_model_and_language(&selection, &self.settings.transcription) {
self.preparation.start(selection, true);
}
}
Request::InputSourceChanged(source) => {
if self
.keyboard_switcher
.source_changed(source, Instant::now())
{
self.supersede_automatic();
}
}
Request::CancelModel => {
self.manual_choice();
self.preparation.cancel();
}
Request::ReloadSettings => self.reload_settings(),
Request::Desktop(_)
| Request::CaptureShortcutFor(_)
| Request::CancelShortcut
| Request::SetShortcut { .. } => {}
}
}
fn reload_settings(&mut self) {
match AppSettings::load() {
Ok(settings) => {
if self
.keyboard_switcher
.configure(settings.keyboard_model_switching.clone(), Instant::now())
{
self.supersede_automatic();
}
self.settings = settings;
}
Err(error) => tracing::warn!(%error, "could not reload settings"),
}
}
fn manual_choice(&mut self) {
self.keyboard_switcher.manual_choice();
if self.automatic_preparation {
self.preparation.cancel();
self.automatic_preparation = false;
}
}
fn supersede_automatic(&mut self) {
// A source being cycled through must not cancel a manual operation.
// Manual work is superseded only when the debounced choice is due.
if self.automatic_preparation {
self.preparation.cancel();
self.automatic_preparation = false;
}
}
/// Commits a prepared model and starts a listener that waited for setup.
fn tick(&mut self) {
self.tick_at(Instant::now());
}
fn tick_at(&mut self, now: Instant) {
if let Some(choice) = self.keyboard_switcher.take_due(now) {
let selection = TranscriptionSelection {
language: choice.language,
..self.settings.transcription_for_model(choice.model)
};
if !same_model_and_language(&selection, &self.settings.transcription) {
self.preparation.start(selection, true);
self.automatic_preparation = true;
} else {
// The debounced choice keeps the current model, but must
// still prevent an older manual preparation replacing it.
self.preparation.cancel();
self.automatic_preparation = false;
}
}
if let Some(result) = self.preparation.poll() {
self.automatic_preparation = false;
let result = result.and_then(|selection| {
crate::transcription::models::validate(&selection).map_err(|e| e.to_string())?;
let mut settings = AppSettings::load().map_err(|e| format!("{e:#}"))?;
settings
.save_transcription(selection)
.map_err(|e| format!("{e:#}"))?;
self.settings = settings;
Ok(())
});
match result {
Ok(()) => self.preparation.set_error(None),
Err(error) => {
tracing::warn!(%error, "could not select transcription model");
self.preparation.set_error(Some(error));
}
}
}
if self.recognition_start.is_some()
&& crate::desktop::onboarding::status(&self.settings.transcription).ready()
&& let Some(start) = self.recognition_start.take()
{
let _ = start.try_send(());
}
}
fn publish(&self) -> Published {
let preparation = self.preparation.status();
let failure = lock(&self.listener_failure).clone();
let running = self.recognition_start.is_none() && failure.is_none();
Published {
listener: DesktopListenerSnapshot {
running,
status: if failure.is_some() {
"Stopped"
} else if running {
"Enabled"
} else {
"Waiting for setup"
}
.into(),
warning: failure,
shortcuts: DesktopShortcuts::Registered,
shortcuts_configurable: false,
},
transcription: DesktopTranscriptionSnapshot {
downloaded_bytes: preparation.downloaded_bytes,
error: preparation.error.clone(),
preparation_stage: preparation
.model
.map(|_| ModelPreparationStage::Downloading),
selection: self.settings.transcription.clone(),
preparing: preparation.model,
},
update_status: update_status(),
update_notes: UPDATER.get().and_then(crate::updater::Updater::notes),
settings: self.settings.clone(),
preparation,
}
}
}
// ---------------------------------------------------------------------------
// Main thread: status item, menu, reopen, HUD
struct Pump {
window: rune::AppHandle<Ui>,
capsules: crate::rune_ui::meeting_capsules::MeetingCapsules,
#[cfg(hex_capture)]
capture_overlays: Option<crate::rune_ui::capture_capsule::feed::CaptureOverlays>,
runtime: RuntimeHandle,
shutdown: &'static AtomicBool,
indicator_events: Receiver<DictationIndicatorEvent>,
hud: crate::rune_hud::HudSender,
status_actions: Option<Receiver<StatusItemAction>>,
controller_events: Receiver<ControllerEvent>,
developer_calls: Receiver<crate::control::developer_control::DeveloperCall>,
control_calls: Receiver<crate::control::ControlCall>,
meeting_waiters: Vec<control::MeetingWaiter>,
meeting_state: MeetingMenuState,
meeting_menu_at: Instant,
model_menu_at: Instant,
show_dock_icon: bool,
}
struct PumpState {
pump: Pump,
/// Created on the main thread, so it stays out of the `Send` [`Pump`].
indicator: DictationIndicatorUi,
timer: Retained<NSTimer>,
_menu_target: Retained<MenuTarget>,
}
thread_local! {
static PUMP: RefCell<Option<PumpState>> = const { RefCell::new(None) };
/// What [`start_main_thread`] takes, once.
static LAUNCH: RefCell<Option<Launch>> = const { RefCell::new(None) };
}
struct Launch {
pump: Pump,
/// Already observing AppKit's terminate ([`observe_termination`]).
target: Retained<MenuTarget>,
}
/// AppKit's terminate (the quit Apple event, logout) calls `exit` right after
/// this notification, so Hex finishes there ([`crate::desktop::process_exit`]).
fn observe_termination(target: &MenuTarget) {
// SAFETY: the target outlives the observer (kept in LAUNCH, then PUMP,
// for the app's life), and the selector matches its method.
unsafe {
let _: () = msg_send![
&*objc2_foundation::NSNotificationCenter::defaultCenter(),
addObserver: target,
selector: sel!(applicationWillTerminate:),
name: objc2_app_kit::NSApplicationWillTerminateNotification,
object: std::ptr::null::<AnyObject>(),
];
}
}
/// Starts the main-thread setup after `seconds` if the window's first frame
/// hasn't by then, so a window that never draws (no GPU, displays asleep)
/// still leaves a status item.
fn start_main_thread_after(seconds: f64) {
let block = RcBlock::new(|_: std::ptr::NonNull<NSTimer>| start_main_thread());
// SAFETY: the timer runs its block on this (main) thread's run loop.
let _ =
unsafe { NSTimer::scheduledTimerWithTimeInterval_repeats_block(seconds, false, &block) };
}
/// Sets up the status item, Dock policy, HUD, main menu, reopen handler, and
/// the pump's timer; the first call does, later ones do nothing.
fn start_main_thread() {
let Some(mtm) = MainThreadMarker::new() else {
tracing::error!("Hex's main-thread setup ran off the main thread");
return;
};
let Some(Launch { mut pump, target }) = LAUNCH.with(|slot| slot.borrow_mut().take()) else {
return;
};
pump.status_actions = match crate::macos_rune::status_item::install() {
Ok(actions) => Some(actions),
Err(error) => {
tracing::error!(%error, "could not install Hex status item; opening the window");
show(&pump.window, Destination::Settings);
None
}
};
// An open window always shows the Dock icon (see [`show`]).
crate::app_settings::set_dock_icon_visible(
window_visible()
|| crate::app_settings::dock_icon_visible(
pump.show_dock_icon,
pump.status_actions.is_some(),
),
);
let indicator = DictationIndicatorUi::new(pump.hud.clone());
install_main_menu(&target, mtm);
// Inside the loop, once AppKit has started, so its own Apple event setup
// can't replace this handler.
// SAFETY: the target outlives the handler (kept in PUMP for the app's
// life), and the selector matches its method.
unsafe {
let _: () = msg_send![
&*NSAppleEventManager::sharedAppleEventManager(),
setEventHandler: &*target,
andSelector: sel!(handleReopen:withReplyEvent:),
forEventClass: CORE_EVENT_CLASS,
andEventID: REOPEN_APPLICATION,
];
}
let block = RcBlock::new(|_: std::ptr::NonNull<NSTimer>| {
PUMP.with(|slot| {
if let Some(state) = slot.borrow_mut().as_mut() {
if let Some(mtm) = MainThreadMarker::new() {
let switching = state.pump.runtime.published().is_some_and(|published| {
published.settings.keyboard_model_switching.enabled
});
crate::keyboard_input_sources::observe(mtm, switching);
if let Some(source) = crate::keyboard_input_sources::take_change(mtm) {
let _ = state.pump.runtime.send(Request::InputSourceChanged(source));
}
}
state.pump.tick(&mut state.indicator);
}
});
});
// SAFETY: the timer runs its block on this (main) thread's run loop.
let timer = unsafe {
NSTimer::scheduledTimerWithTimeInterval_repeats_block(PUMP_INTERVAL, true, &block)
};
// Keep firing while a menu is open (event-tracking run loop mode).
// SAFETY: adding a scheduled timer to the main run loop's common modes.
unsafe {
let run_loop = objc2_foundation::NSRunLoop::mainRunLoop();
run_loop.addTimer_forMode(&timer, objc2_foundation::NSRunLoopCommonModes);
}
PUMP.with(|slot| {
*slot.borrow_mut() = Some(PumpState {
pump,
indicator,
timer,
_menu_target: target,
});
});
}
/// Whether the window is on screen.
fn window_visible() -> bool {
WINDOW.get().is_some_and(rune::AppHandle::is_visible)
}
/// Opens the window at `destination`, in front of the app that was active.
fn show(window: &rune::AppHandle<Ui>, destination: Destination) {
window.update(move |ui, tx| crate::rune_ui::show(ui, destination, tx));
bring_forward(window);
}
/// Opens the window in front, from the main thread.
pub(crate) fn bring_window_forward() {
with_window(bring_forward);
}
fn bring_forward(window: &rune::AppHandle<Ui>) {
// An open window always shows the Dock icon: hiding it
// would deactivate Hex and drop the window behind other apps.
crate::app_settings::set_dock_icon_visible(true);
if let Some(mtm) = MainThreadMarker::new() {
let app = NSApplication::sharedApplication(mtm);
app.activate();
}
window.open();
}
impl Pump {
fn tick(&mut self, indicator: &mut DictationIndicatorUi) {
if self.shutdown.load(Ordering::Relaxed) {
self.runtime_cancel();
self.window.quit();
return;
}