Repository navigation
Expand file tree
/
Copy pathlinux_app.rs
More file actions
1901 lines (1784 loc) · 71.2 KB
/
Copy pathlinux_app.rs
File metadata and controls
1901 lines (1784 loc) · 71.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
//! The one Linux Hex process: the dictation host (listener, shortcut
//! registration, model preparation, updates, History writes, paste), the
//! single-instance socket, and the window and HUD, opened on demand and
//! closed without stopping anything.
//!
//! Threads: the main thread runs Rune's event loop; the host thread
//! refreshes [`LinuxDesktopHost`] every 20 ms and publishes its status;
//! the socket's workers answer `hex` commands from that published status
//! and hand shortcut commands straight to the listener.
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
use std::sync::mpsc::{self, Receiver};
use std::sync::{Arc, Mutex, MutexGuard};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use color_eyre::Result;
use crate::app_settings::{AppSettings, HotkeyBinding};
use crate::control::{CaptureAction, ControlError, ControlReply, Pane};
use crate::desktop_activity::DesktopActivity;
use crate::desktop_host::{
DesktopAction, DesktopListenerSnapshot, DesktopShortcut, DesktopSnapshot,
DesktopTranscriptionSnapshot,
};
use crate::events::EventReader;
use crate::linux_dictation::ListenerUpdate;
use crate::linux_input::{LinuxHotkey, ListenerCommand, ShortcutCommand};
use crate::linux_service::{self, Activation, Control, Published, ShortcutRoute, Status};
const REFRESH_INTERVAL: Duration = Duration::from_millis(20);
/// How often the host asks X11 for the active keyboard group.
const INPUT_SOURCE_POLL: Duration = Duration::from_millis(250);
/// Left by "Update" so the restarted process shows the window again; a
/// crash restart finds none and stays in the background.
const REOPEN_MARKER: &str = "reopen-window";
type ListenerResult = std::result::Result<(), String>;
type PreparationResult = std::result::Result<PreparedTranscription, String>;
pub(crate) type Waker = Arc<dyn Fn() + Send + Sync>;
/// A shortcut Settings records for the listener.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) enum ShortcutTarget {
#[default]
Dictation,
PasteLast,
Capture,
RawDictation,
}
struct PreparedTranscription {
selection: crate::transcription_models::TranscriptionSelection,
transcriber: crate::local_transcriber::LocalTranscriber,
}
struct TranscriptionPreparation {
canceled: Arc<AtomicBool>,
model: crate::transcription_models::TranscriptionModelId,
progress: Arc<AtomicU64>,
stage: Arc<AtomicU8>,
worker: JoinHandle<PreparationResult>,
/// A keyboard switch, which a manual choice or a later layout change
/// supersedes.
automatic: bool,
}
struct ShortcutEdit {
target: ShortcutTarget,
hotkey: Option<LinuxHotkey>,
canceled: Arc<AtomicBool>,
worker: Option<JoinHandle<Result<AppSettings>>>,
}
struct Listener {
stop: Arc<AtomicBool>,
worker: JoinHandle<ListenerResult>,
startup: ListenerStartup,
hotkey_status: crate::linux_input::HotkeyStatus,
/// `hex` commands for the listener's shortcut state machine.
commands: mpsc::SyncSender<ListenerCommand>,
/// Settings, models, and shortcut suspension the listener applies in place.
updates: mpsc::Sender<crate::linux_dictation::ListenerUpdate>,
}
enum ListenerStartup {
Awaiting { previous_session: Option<u64> },
Observed,
}
impl Listener {
fn stop(&self) {
self.stop.store(true, Ordering::Relaxed);
}
/// A listener that already stopped has nothing to apply.
fn update(&self, update: crate::linux_dictation::ListenerUpdate) {
let _ = self.updates.send(update);
}
fn finish(self) -> ListenerResult {
self.worker
.join()
.unwrap_or_else(|_| Err("listener worker stopped unexpectedly".into()))
}
fn observe_session(&mut self, session: Option<u64>) {
if let ListenerStartup::Awaiting { previous_session } = self.startup
&& session != previous_session
{
self.startup = ListenerStartup::Observed;
}
}
}
struct LinuxDesktopHost {
event_path: PathBuf,
event_reader: EventReader,
activity: DesktopActivity,
listener: Option<Listener>,
listen_when_ready: bool,
status: String,
error: Option<String>,
dismissed_failure_at: Option<u64>,
settings_error: Option<String>,
settings: AppSettings,
// Dismissing a load error must not authorize recording with fallback defaults.
settings_valid: bool,
shortcut_edit: Option<ShortcutEdit>,
prepared_transcriber: Option<crate::local_transcriber::LocalTranscriber>,
transcription_preparation: Option<TranscriptionPreparation>,
transcription_error: Option<String>,
updater: crate::updater::Updater,
output: crate::linux_dictation::DictationOutput,
/// Hosts the personal transformations workspace while a mode uses one.
personal_commands: Option<crate::personal_commands::PersonalCommands>,
personal_commands_checked_at: Instant,
keyboard_switcher: crate::keyboard_model_switching::Switcher,
/// The XKB connection, only while keyboard model switching is on.
input_sources: Option<crate::keyboard_input_sources::Watcher>,
input_sources_polled_at: Instant,
/// A due keyboard switch waiting for the preparation it superseded to stop.
keyboard_switch: Option<crate::transcription_models::TranscriptionSelection>,
}
/// What the window shows of the host.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct HostSnapshot {
pub(crate) desktop: DesktopSnapshot,
pub(crate) settings: AppSettings,
/// The host is recording or saving a shortcut.
pub(crate) editing: bool,
}
/// What the window asks of the host. Settings edits go through
/// [`HostHandle::save_settings`].
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum HostRequest {
Desktop(DesktopAction),
/// Stops listening while the window records a shortcut.
CaptureShortcutFor(ShortcutTarget),
CancelShortcut,
/// The chord the window recorded, for the host to register and save.
SetShortcut {
target: ShortcutTarget,
shortcut: DesktopShortcut,
},
ChooseModel {
model: crate::transcription_models::TranscriptionModelId,
language: String,
},
CancelModel,
}
struct Shared {
host: Mutex<LinuxDesktopHost>,
waker: Mutex<Option<Waker>>,
/// Whether the window shows, as its app reports it.
window_visible: Mutex<Option<WindowVisible>>,
shutdown: &'static AtomicBool,
}
type WindowVisible = Arc<dyn Fn() -> bool + Send + Sync>;
/// The window's handle to the host it runs beside. Every call is a short
/// lock on the host; nothing here waits for the listener or a model.
#[derive(Clone)]
pub(crate) struct HostHandle(Arc<Shared>);
impl HostHandle {
fn new(host: LinuxDesktopHost, shutdown: &'static AtomicBool) -> Self {
Self(Arc::new(Shared {
host: Mutex::new(host),
waker: Mutex::new(None),
window_visible: Mutex::new(None),
shutdown,
}))
}
/// The window's "Quit Hex": drains accepted work, then exits.
pub(crate) fn quit(&self) {
self.0.shutdown.store(true, Ordering::Release);
}
fn lock(&self) -> MutexGuard<'_, LinuxDesktopHost> {
self.0
.host
.lock()
.unwrap_or_else(|error| error.into_inner())
}
pub(crate) fn snapshot(&self) -> HostSnapshot {
self.lock().host_snapshot()
}
pub(crate) fn request(&self, request: HostRequest) -> Result<()> {
let result = {
let mut host = self.lock();
match request {
HostRequest::Desktop(action) => host.dispatch(action),
HostRequest::CaptureShortcutFor(target) => {
host.begin_shortcut_edit(target, None);
Ok(())
}
HostRequest::CancelShortcut => {
host.cancel_shortcut_edit();
Ok(())
}
HostRequest::SetShortcut { target, shortcut } => host.set_hotkey(target, shortcut),
HostRequest::ChooseModel { model, language } => {
host.choose_transcription(model, language)
}
HostRequest::CancelModel => {
host.manual_choice();
host.cancel_transcription_preparation();
Ok(())
}
}
};
self.wake();
result
}
/// Saves the window's settings, then adopts them. A failed save leaves
/// the host's settings alone.
pub(crate) fn save_settings(&self, settings: AppSettings) -> Result<()> {
settings.save()?;
self.lock().adopt_settings(settings);
self.wake();
Ok(())
}
/// The host's retained-history store; one store per process.
pub(crate) fn history(&self) -> Option<crate::history::History> {
self.lock().output.history.clone()
}
/// The window wakes on host changes through `waker`.
pub(crate) fn set_waker(&self, waker: Waker) {
*self.0.waker.lock().unwrap() = Some(waker);
}
/// `hex status` asks `visible` whether the window shows.
pub(crate) fn set_window_visible(&self, visible: WindowVisible) {
*self.0.window_visible.lock().unwrap() = Some(visible);
}
fn window_open(&self) -> bool {
let visible = self.0.window_visible.lock().unwrap().clone();
visible.is_some_and(|visible| visible())
}
/// A closed window leaves no shortcut capture behind.
pub(crate) fn window_closed(&self) {
let mut host = self.lock();
if host.capturing_hotkey() {
host.cancel_shortcut_edit();
}
}
fn wake(&self) {
let waker = self.0.waker.lock().unwrap().clone();
if let Some(waker) = waker {
waker();
}
}
fn status(&self, snapshot: HostSnapshot, session: linux_service::Session) -> Status {
let hud_limitation = crate::linux_rune_hud::limitation();
let mut desktop = snapshot.desktop;
// A running listener also reports the missing HUD as its warning.
if desktop.listener.running && desktop.listener.warning.is_none() {
desktop.listener.warning = hud_limitation.clone();
}
Status {
desktop,
labs: crate::labs::active_names(&snapshot.settings),
settings: snapshot.settings,
editing: snapshot.editing,
hud_limitation,
window_open: self.window_open(),
pid: std::process::id(),
session,
}
}
}
/// Becomes the Linux instance: claims the data root, starts the host, and
/// runs the window's event loop on this (the main) thread until `hex quit`,
/// a signal, or the window's Quit. `activation` opens the window at once.
pub(crate) fn run(
event_path: PathBuf,
shutdown: &'static AtomicBool,
activation: Option<Activation>,
) -> Result<()> {
let mut server = linux_service::Server::bind()?;
// Installs before #579 named the entries hex.desktop.
if let Err(error) = crate::linux_icons::install() {
tracing::warn!(%error, "could not install Hex's icon");
}
if let Err(error) = crate::linux_portal::tidy_desktop_entries() {
tracing::warn!(%error, "could not move Hex's desktop entry");
}
if let Err(error) = crate::linux_portal::forget_legacy_gnome_shortcuts() {
tracing::warn!(%error, "could not remove Hex's old GNOME shortcuts");
}
if let Err(error) = crate::linux_login_item::tidy() {
tracing::warn!(%error, "could not tidy Hex's autostart entry");
}
crate::labs::log_launch();
crate::hex_microphone::host_service();
let (settings, error) = match AppSettings::load() {
Ok(settings) => (settings, None),
Err(error) => (
AppSettings::default(),
Some(format!("Could not load settings: {error:#}")),
),
};
crate::linux_dictation::initialize_feedback(&settings);
// Before any thread can load a model or the window can create its GPU.
crate::local_transcriber::initialize_backends();
let (control_calls, control_receiver) = mpsc::sync_channel(8);
let local_api = crate::local_api::LocalApi::start_for_app(&event_path, control_calls);
let enable_on_launch = settings.enable_on_launch;
let mut host = LinuxDesktopHost::new(
event_path,
settings,
error,
crate::updater::Updater::start(),
);
if enable_on_launch {
host.start();
}
let host = HostHandle::new(host, shutdown);
let session = linux_service::Session::current();
let published = Arc::new(Published::default());
*published.status.lock().unwrap() = Some(host.status(host.snapshot(), session.clone()));
let (control, requests) = mpsc::sync_channel(8);
crate::control::host::serve(
control_receiver,
Arc::new(LinuxControl {
host: host.clone(),
published: Arc::downgrade(&published),
window: control.clone(),
}),
);
server.serve(published.clone(), control.clone());
let tray = crate::linux_tray::start(host.clone(), published.clone(), control.clone(), shutdown)
.map(Arc::new);
linux_service::notify("READY=1");
tracing::info!(pid = std::process::id(), "Hex instance ready");
let worker = {
let host = host.clone();
let tray = tray.clone();
std::thread::Builder::new()
.name("hex-host".into())
.spawn(move || {
run_host(
host,
published,
server,
control,
session,
tray.as_deref(),
shutdown,
)
})?
};
let reopen = take_reopen_marker();
let first = activation.or(reopen.then(Activation::default));
run_window(&host, requests, first, shutdown);
shutdown.store(true, Ordering::Release);
let _ = worker.join();
drop(local_api);
drop(tray);
Ok(())
}
/// The host thread: refreshes the host, publishes what the socket answers
/// with, wakes the window on changes, and drains accepted work on quit.
fn run_host(
host: HostHandle,
published: Arc<Published>,
server: linux_service::Server,
control: mpsc::SyncSender<Control>,
session: linux_service::Session,
tray: Option<&rune::Tray>,
shutdown: &'static AtomicBool,
) {
let mut stopping = false;
let mut shown: Option<HostSnapshot> = None;
let mut tray_view = None;
let mut tray_meetings = None;
loop {
let (done, route, snapshot) = {
let mut guard = host.lock();
if shutdown.load(Ordering::Acquire) && !stopping {
stopping = true;
linux_service::notify("STOPPING=1");
guard.stop();
guard.cancel_transcription_preparation();
// The main thread may be waiting for the next window request.
let _ = control.try_send(Control::Quit);
}
guard.refresh();
(
stopping && !guard.has_pending_work(),
guard.shortcut_route(),
guard.host_snapshot(),
)
};
*published.shortcuts.lock().unwrap() = route;
*published.status.lock().unwrap() = Some(host.status(snapshot.clone(), session.clone()));
let meetings = crate::meeting_runtime::tray_state();
if shown.as_ref() != Some(&snapshot) || tray_meetings != meetings {
tray_meetings = meetings;
if let Some(tray) = tray {
let view = crate::linux_tray::view(&snapshot);
if tray_view.as_ref() != Some(&view) {
crate::linux_tray::show(tray, &view);
tray_view = Some(view);
}
}
shown = Some(snapshot);
host.wake();
}
if done {
break;
}
std::thread::sleep(REFRESH_INTERVAL);
}
*published.shortcuts.lock().unwrap() = None;
drop(server);
}
/// The one seam between the process and its window, on the main thread
/// until Hex quits. `first` opens the window at once. A missing display or
/// GPU fails the window, never Hex.
fn run_window(
host: &HostHandle,
requests: Receiver<Control>,
first: Option<Activation>,
shutdown: &'static AtomicBool,
) {
let app = host.clone();
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
crate::rune_ui::run_app(app, requests, first, shutdown)
}))
.is_err()
{
tracing::error!("the Hex window failed; Hex keeps running without it");
while !shutdown.load(Ordering::Acquire) {
std::thread::sleep(Duration::from_millis(100));
}
}
}
fn reopen_marker() -> Option<PathBuf> {
crate::app_paths::support_dir()
.ok()
.map(|directory| directory.join(REOPEN_MARKER))
}
/// True when "Update" restarted this process with its window open.
fn take_reopen_marker() -> bool {
let Some(path) = reopen_marker() else {
return false;
};
let fresh = std::fs::metadata(&path)
.and_then(|metadata| metadata.modified())
.is_ok_and(|modified| {
modified
.elapsed()
.is_ok_and(|age| age < Duration::from_secs(60))
});
let _ = std::fs::remove_file(&path);
fresh
}
impl LinuxDesktopHost {
fn new(
event_path: PathBuf,
settings: AppSettings,
error: Option<String>,
updater: crate::updater::Updater,
) -> Self {
let mut event_reader = EventReader::open(&event_path);
let mut activity = DesktopActivity::default();
activity.refresh(&mut event_reader);
// Tests never touch the user's history.
let history = if cfg!(test) {
None
} else {
crate::history::History::open_default(settings.history_retention)
.inspect_err(|error| tracing::warn!(%error, "could not open retained history"))
.ok()
};
let output = crate::linux_dictation::DictationOutput::from_settings(&settings, history);
// Known before the first poll, so launching keeps the saved model
// instead of applying the current layout's mapping.
let keyboard_switcher = crate::keyboard_model_switching::Switcher::new(
settings.keyboard_model_switching.clone(),
settings
.keyboard_model_switching
.enabled
.then(crate::keyboard_input_sources::current)
.flatten(),
);
let mut host = Self {
event_reader,
event_path,
activity,
listener: None,
listen_when_ready: false,
status: "Disabled".into(),
error: None,
dismissed_failure_at: None,
settings_valid: error.is_none(),
settings_error: error,
settings,
shortcut_edit: None,
prepared_transcriber: None,
transcription_preparation: None,
transcription_error: None,
updater,
output,
personal_commands: None,
personal_commands_checked_at: Instant::now(),
keyboard_switcher,
input_sources: None,
input_sources_polled_at: Instant::now(),
keyboard_switch: None,
};
host.refresh_personal_commands();
host
}
/// Applies saved settings the host owns: sounds, modes, history
/// retention, and the transformations workspace.
fn apply_output_settings(&mut self) {
crate::feedback::set_enabled(self.settings.sound_effects);
crate::feedback::set_volume(self.settings.sound_effect_volume.clamp(0.0, 1.0));
crate::feedback::set_sound_set(self.settings.sound_theme);
*self
.output
.modes
.write()
.unwrap_or_else(|error| error.into_inner()) =
crate::dictation_modes::ModeRuntime::from_settings(&self.settings);
if let Some(history) = &self.output.history
&& let Err(error) = history.set_retention(self.settings.history_retention)
{
tracing::warn!(%error, "could not apply the history retention");
}
self.refresh_personal_commands();
}
fn refresh_personal_commands(&mut self) {
if cfg!(test) {
return;
}
let enabled =
crate::app_settings::transformations_used(&self.settings.dictation_processing)
|| crate::personal_commands::workspace_configured();
match (enabled, self.personal_commands.is_some()) {
(true, false) => {
self.personal_commands = crate::personal_commands::PersonalCommands::start(
self.output.transformations.clone(),
);
}
(false, true) => self.personal_commands = None,
_ => {}
}
}
fn start(&mut self) {
if self.shortcut_edit.is_some() {
return;
}
self.listen_when_ready = true;
if self.is_running() || self.transcription_preparation.is_some() {
return;
}
// Defaults are only an editable recovery projection after a failed load.
// They must never become a recording configuration until saved successfully.
if !self.settings_valid {
self.status = "Couldn't enable".into();
return;
}
let model = crate::transcription_models::definition(self.settings.transcription.model);
if !crate::transcription_models::is_installed(model, &self.settings.transcription.language)
{
self.status = "Model required".into();
return;
}
let stop = Arc::new(AtomicBool::new(false));
let worker_stop = stop.clone();
let settings = self.settings.clone();
let output = self.output.clone();
let event_path = self.event_path.clone();
let prepared_transcriber = self.prepared_transcriber.take();
let hotkey_status = crate::linux_input::HotkeyStatus::default();
let worker_hotkey_status = hotkey_status.clone();
let (commands, command_receiver) = mpsc::sync_channel(16);
let (updates, update_receiver) = mpsc::channel();
let worker = std::thread::spawn(move || {
let result = crate::instance::acquire("listener").and_then(|_instance| {
crate::linux_dictation::run(
&event_path,
None,
&worker_stop,
&settings,
output,
prepared_transcriber,
worker_hotkey_status,
command_receiver.into(),
update_receiver,
)
});
result.map_err(|error| format!("{error:#}"))
});
self.listener = Some(Listener {
stop,
worker,
startup: ListenerStartup::Awaiting {
previous_session: self.activity.session_started_at,
},
hotkey_status,
commands,
updates,
});
self.status = "Enabling…".into();
}
/// Enable and Disable also decide whether Hex listens at its next launch,
/// so a disabled Hex stays disabled after a restart (#575).
fn remember_listening(&mut self, enabled: bool) {
if self.settings.enable_on_launch == enabled {
return;
}
match save_listening(&self.settings, enabled) {
Ok(settings) => self.adopt_settings(settings),
Err(error) => {
self.settings_error = Some(format!("Could not save settings: {error:#}"));
}
}
}
fn stop(&mut self) {
self.listen_when_ready = false;
if let Some(edit) = &self.shortcut_edit {
edit.canceled.store(true, Ordering::Release);
}
if let Some(listener) = &self.listener {
listener.stop();
self.status = "Disabling…".into();
}
}
fn refresh(&mut self) {
self.switch_with_keyboard();
// Restart to update asks systemd to restart Hex after the updater's
// final check; only a failure needs showing.
if let Some(Err(error)) = self.updater.take_restart() {
self.error = Some(format!("Could not restart Hex: {error:#}"));
}
// Settings may set up the transformations workspace at any time.
if self.personal_commands_checked_at.elapsed() >= Duration::from_secs(2) {
self.personal_commands_checked_at = Instant::now();
self.refresh_personal_commands();
}
let mut start_listener = false;
if let Some(preparation) = self
.transcription_preparation
.take_if(|preparation| preparation.worker.is_finished())
{
let was_canceled = preparation.canceled.load(Ordering::Relaxed);
let result = preparation
.worker
.join()
.unwrap_or_else(|_| Err("model preparation worker stopped unexpectedly".into()));
if was_canceled {
self.transcription_error = None;
} else {
match result {
Ok(prepared) => {
let selection = prepared.selection.clone();
match save_with(|settings| settings.remember_transcription(selection)) {
Ok(candidate) => {
self.settings = candidate;
self.settings_valid = true;
self.transcription_error = None;
self.settings_error = None;
// A running listener swaps the model in place.
if let Some(listener) = &self.listener {
listener.update(ListenerUpdate::Transcriber {
selection: prepared.selection,
transcriber: Box::new(prepared.transcriber),
});
listener.update(ListenerUpdate::Settings(Box::new(
self.settings.clone(),
)));
} else {
self.prepared_transcriber = Some(prepared.transcriber);
start_listener = self.listen_when_ready;
}
}
Err(error) => {
self.transcription_error = Some(format!(
"Could not save transcription selection: {error:#}"
));
}
}
}
Err(error) => {
self.transcription_error = Some(error);
}
}
}
}
if start_listener {
self.start();
}
if let Some(listener) = self
.listener
.take_if(|listener| listener.worker.is_finished())
{
match listener.finish() {
Ok(()) => self.status = "Disabled".into(),
Err(error) => {
self.status = "Couldn't enable".into();
self.error = Some(error);
}
}
}
self.refresh_shortcut_edit();
self.activity.refresh(&mut self.event_reader);
if let Some(listener) = &mut self.listener {
listener.observe_session(self.activity.session_started_at);
}
if self
.listener
.as_ref()
.is_some_and(|listener| matches!(listener.startup, ListenerStartup::Observed))
&& self.listen_when_ready
&& let Some(status) = self.activity.state_label()
{
self.status = status.into();
}
}
fn is_running(&self) -> bool {
self.listener.is_some()
}
fn set_hotkey(&mut self, target: ShortcutTarget, shortcut: DesktopShortcut) -> Result<()> {
let binding = match LinuxHotkey::try_from(shortcut) {
Ok(binding) => binding,
Err(error) => {
self.error = Some("The Fn modifier cannot be registered on Linux".into());
self.cancel_shortcut_edit();
return Err(error);
}
};
if let Some(edit) = &mut self.shortcut_edit {
if edit.target == target && edit.hotkey.is_none() && edit.worker.is_none() {
edit.hotkey = Some(binding);
}
} else {
self.begin_shortcut_edit(target, Some(binding));
}
Ok(())
}
fn begin_shortcut_edit(&mut self, target: ShortcutTarget, hotkey: Option<LinuxHotkey>) {
if self.shortcut_edit.is_some() {
return;
}
if self.transcription_preparation.is_some() {
self.error = Some("Wait for model preparation before editing shortcut settings".into());
return;
}
// Global matching stops while the window records; listening goes on.
if let Some(listener) = &self.listener {
listener.update(ListenerUpdate::SuspendShortcuts(true));
}
self.error = None;
self.shortcut_edit = Some(ShortcutEdit {
target,
hotkey,
canceled: Arc::new(AtomicBool::new(false)),
worker: None,
});
}
fn cancel_shortcut_edit(&mut self) {
if let Some(edit) = &self.shortcut_edit {
edit.canceled.store(true, Ordering::Release);
}
}
/// Adopts settings the window saved. A running listener applies them in
/// place, so listening never stops for a settings change.
fn adopt_settings(&mut self, settings: AppSettings) {
if self.settings_valid && settings == self.settings {
return;
}
if self
.keyboard_switcher
.configure(settings.keyboard_model_switching.clone(), Instant::now())
{
self.supersede_automatic();
}
let was_valid = self.settings_valid;
self.settings = settings;
self.settings_valid = true;
self.settings_error = None;
self.apply_output_settings();
if let Some(listener) = &self.listener {
listener.update(ListenerUpdate::Settings(Box::new(self.settings.clone())));
} else if self.listen_when_ready && !was_valid {
self.start();
}
}
fn capturing_hotkey(&self) -> bool {
self.shortcut_edit
.as_ref()
.is_some_and(|edit| !edit.canceled.load(Ordering::Acquire) && edit.hotkey.is_none())
}
fn has_pending_work(&self) -> bool {
self.is_running()
|| self.shortcut_edit.is_some()
|| self.transcription_preparation.is_some()
}
fn refresh_shortcut_edit(&mut self) {
let Some(edit) = &mut self.shortcut_edit else {
return;
};
if edit
.worker
.as_ref()
.is_some_and(|worker| !worker.is_finished())
{
return;
}
let canceled = edit.canceled.load(Ordering::Acquire);
if let Some(worker) = edit.worker.take() {
match worker.join() {
// Once persistence completed, keep the in-memory projection consistent even
// if Cancel raced with the final atomic save.
Ok(Ok(settings)) => {
self.settings = settings;
self.settings_valid = true;
self.settings_error = None;
self.apply_output_settings();
}
Ok(Err(error)) if !canceled => {
self.error = Some(format!("Could not update dictation settings: {error:#}"));
}
Err(_) if !canceled => {
self.error = Some("Settings worker stopped unexpectedly".into())
}
_ => {}
}
} else if !canceled {
let Some(binding) = edit.hotkey.clone() else {
// The window records the chord from its own key events.
return;
};
let target = edit.target;
let canceled = edit.canceled.clone();
edit.worker = Some(std::thread::spawn(move || {
binding.validate()?;
if crate::linux_session::LinuxSession::detect().is_wayland() {
// The listener asks the desktop again and reports what it granted.
binding.portal_trigger()?;
} else {
// Fail before saving when another X11 client holds the chord.
crate::linux_input::LinuxHotkeyMonitor::start(
binding.clone(),
Default::default(),
Default::default(),
mpsc::channel().1.into(),
)?;
}
if canceled.load(Ordering::Acquire) {
return Err(color_eyre::eyre::eyre!("Shortcut edit canceled"));
}
save_with(|settings| {
let binding = HotkeyBinding::from(&binding);
match target {
ShortcutTarget::Dictation => settings.dictation_hotkey = binding,
ShortcutTarget::PasteLast => settings.paste_last_hotkey = Some(binding),
ShortcutTarget::Capture => settings.capture.hotkey = binding,
ShortcutTarget::RawDictation => {
settings.raw_dictation_hotkey = Some(binding)
}
}
})
}));
return;
}
self.shortcut_edit = None;
// The listener registers the saved (or unchanged) shortcuts again.
if let Some(listener) = &self.listener {
listener.update(ListenerUpdate::Settings(Box::new(self.settings.clone())));
listener.update(ListenerUpdate::SuspendShortcuts(false));
}
}
fn choose_transcription(
&mut self,
model: crate::transcription_models::TranscriptionModelId,
language: String,
) -> Result<()> {
self.manual_choice();
let definition = crate::transcription_models::definition(model);
let selection = crate::transcription_models::TranscriptionSelection {
model,
language,
// Hints persist across models that can use them.
recognition_hints: if definition.supports_recognition_hints {
self.settings.transcription.recognition_hints.clone()
} else {
String::new()
},
};
self.prepare_transcription(selection, false)
}
/// Downloads (or, for a keyboard switch, only verifies) and loads a
/// model off the host thread.
fn prepare_transcription(
&mut self,
selection: crate::transcription_models::TranscriptionSelection,
automatic: bool,
) -> Result<()> {
if self.shortcut_edit.is_some() {
let error = "Finish the shortcut change before changing the model".to_string();
self.transcription_error = Some(error.clone());
return Err(color_eyre::eyre::eyre!(error));
}
if self.transcription_preparation.is_some() {
self.cancel_transcription_preparation();
let error = "The previous model preparation is still stopping".to_string();
self.transcription_error = Some(error.clone());
return Err(color_eyre::eyre::eyre!(error));
}
let model = selection.model;
let definition = crate::transcription_models::validate(&selection)?;
// A running listener keeps the current model until the new one is ready.
let canceled = Arc::new(AtomicBool::new(false));
let progress = Arc::new(AtomicU64::new(0));
let stage = Arc::new(AtomicU8::new(
crate::transcription_models::ModelPreparationStage::Downloading as u8,
));
let worker_canceled = canceled.clone();
let worker_progress = progress.clone();
let worker_stage = stage.clone();
let worker = std::thread::spawn(move || {
(|| {
if automatic {
crate::transcription_models::verify_installed(definition, &worker_canceled)?;
} else {
crate::transcription_models::download_with_stage_progress(
definition,
&worker_canceled,
&worker_progress,
&worker_stage,
)?;
}
if worker_canceled.load(Ordering::Relaxed) {