mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
Onboarding and the Windows listener disagreed about a catalog model already in the Hugging Face cache: onboarding, Settings, and the picker decided with is_installed, while the Windows listener also required is_verified, whose receipt only an adopt step writes. Onboarding finished ready and Enable refused with Model required. One readiness check (models::is_ready) now requires the pinned file check for GGUF. Enable and hex model use reuse the existing installed-only preparation to verify/adopt a file that is here; a model with no file still shows Model required without starting anything, and the picker/onboarding/list scan remains the only scan. Checks never replace a lost import's fallback, Disable cancels an in-flight check, a cancelled check re-evaluates instead of staying on Enabling, macOS keeps permissions in the setup decision and recognition waits for the check, and Linux reports the Verifying stage as checking.
2123 lines
81 KiB
Rust
2123 lines
81 KiB
Rust
//! 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`] (at once when a request changes it, else on
|
||
//! a short idle tick) 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, Condvar, Mutex, MutexGuard};
|
||
use std::thread::JoinHandle;
|
||
use std::time::{Duration, Instant};
|
||
|
||
use color_eyre::Result;
|
||
|
||
use crate::app_settings::{AppSettings, HotkeyBinding};
|
||
use crate::desktop::activity::DesktopActivity;
|
||
use crate::desktop::events::EventReader;
|
||
use crate::desktop::host::{
|
||
DesktopAction, DesktopListenerSnapshot, DesktopShortcut, DesktopSnapshot,
|
||
DesktopTranscriptionSnapshot, ListenerStatus,
|
||
};
|
||
use crate::linux::dictation::ListenerUpdate;
|
||
use crate::linux::input::{LinuxHotkey, ListenerCommand};
|
||
use crate::linux::service::{
|
||
self as linux_service, Activation, Control, Published, ShortcutRoute, Status,
|
||
};
|
||
|
||
mod control;
|
||
mod host;
|
||
mod model;
|
||
|
||
/// The host's refresh while it starts, stops, or prepares something.
|
||
const REFRESH_INTERVAL: Duration = Duration::from_millis(20);
|
||
/// How long the host waits with nothing in flight: requests and quits
|
||
/// notify it, so only an outside settings edit or the updater waits for a
|
||
/// tick.
|
||
const IDLE_REFRESH_INTERVAL: Duration = Duration::from_millis(250);
|
||
/// 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,
|
||
/// Labs › Transform typed text.
|
||
TypedText,
|
||
/// Labs › Terminal paste shortcut: dictates like the dictation shortcut
|
||
/// and always pastes with Ctrl+Shift+V.
|
||
TerminalPaste,
|
||
/// Labs › Second dictation shortcut: another key that dictates exactly
|
||
/// like the dictation shortcut.
|
||
SecondDictation,
|
||
/// Toggle mode's cancel shortcut.
|
||
Cancel,
|
||
}
|
||
|
||
struct PreparedTranscription {
|
||
selection: crate::transcription::models::TranscriptionSelection,
|
||
transcriber: crate::transcription::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: ListenerStatus,
|
||
error: Option<String>,
|
||
dismissed_failure_at: Option<u64>,
|
||
/// What Hex's GNOME custom shortcuts were last written for (#781).
|
||
gnome_shortcuts: Option<String>,
|
||
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::transcription::local_transcriber::LocalTranscriber>,
|
||
transcription_preparation: Option<TranscriptionPreparation>,
|
||
/// The preparation Enable started to check the selected model. Only this
|
||
/// one is canceled by Disable; a model download is left running.
|
||
checking: bool,
|
||
transcription_error: Option<String>,
|
||
updater: crate::updater::Updater,
|
||
output: crate::linux::dictation::DictationOutput,
|
||
/// The local API's `/dictations` controls, for whichever listener runs.
|
||
dictations: crate::dictation::service::DictationQueue,
|
||
/// Hosts the personal transformations workspace while a mode uses one.
|
||
personal_commands: Option<crate::personal_commands::PersonalCommands>,
|
||
personal_commands_checked_at: Instant,
|
||
/// When `settings.json` was last seen changed, so an edit made outside
|
||
/// the window (by hand or by an agent) is adopted instead of being
|
||
/// overwritten by the next save (#970).
|
||
settings_modified: Option<std::time::SystemTime>,
|
||
keyboard_switcher: crate::transcription::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),
|
||
ReloadSettings,
|
||
/// 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>>,
|
||
/// Bumped whenever something outside the host's own thread changed it,
|
||
/// so its next refresh is not left waiting for the idle tick.
|
||
refreshed: Mutex<u64>,
|
||
refreshed_cv: Condvar,
|
||
/// Whether the window shows, as its app reports it.
|
||
window_visible: Mutex<Option<WindowVisible>>,
|
||
/// Why the window's app stopped, once it panicked (#979): the window
|
||
/// and overlays are gone until Hex restarts.
|
||
window_failure: Mutex<Option<String>>,
|
||
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),
|
||
refreshed: Mutex::new(0),
|
||
refreshed_cv: Condvar::new(),
|
||
window_visible: Mutex::new(None),
|
||
window_failure: 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);
|
||
self.notify();
|
||
}
|
||
|
||
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::ReloadSettings => {
|
||
host.reload_changed_settings();
|
||
Ok(())
|
||
}
|
||
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();
|
||
if !host.is_running() && host.status == ListenerStatus::Enabling {
|
||
host.status = ListenerStatus::ModelRequired;
|
||
}
|
||
Ok(())
|
||
}
|
||
}
|
||
};
|
||
self.wake();
|
||
self.notify();
|
||
result
|
||
}
|
||
|
||
/// Saves the window's settings, then adopts them. A failed save leaves
|
||
/// the host's settings alone.
|
||
pub(crate) fn save_settings(
|
||
&self,
|
||
base: &AppSettings,
|
||
settings: &AppSettings,
|
||
) -> Result<AppSettings> {
|
||
let settings = base.update(settings)?;
|
||
self.lock().adopt_settings(settings.clone());
|
||
self.wake();
|
||
self.notify();
|
||
Ok(settings)
|
||
}
|
||
|
||
/// 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);
|
||
self.notify();
|
||
}
|
||
|
||
fn window_open(&self) -> bool {
|
||
if self.window_failure().is_some() {
|
||
return false;
|
||
}
|
||
let visible = self.0.window_visible.lock().unwrap().clone();
|
||
visible.is_some_and(|visible| visible())
|
||
}
|
||
|
||
/// Why the window's app stopped, if it did.
|
||
fn window_failure(&self) -> Option<String> {
|
||
self.0
|
||
.window_failure
|
||
.lock()
|
||
.unwrap_or_else(|error| error.into_inner())
|
||
.clone()
|
||
}
|
||
|
||
fn window_failed(&self, reason: String) {
|
||
*self
|
||
.0
|
||
.window_failure
|
||
.lock()
|
||
.unwrap_or_else(|error| error.into_inner()) = Some(reason);
|
||
self.notify();
|
||
}
|
||
|
||
/// 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();
|
||
}
|
||
drop(host);
|
||
self.notify();
|
||
}
|
||
|
||
fn wake(&self) {
|
||
let waker = self.0.waker.lock().unwrap().clone();
|
||
if let Some(waker) = waker {
|
||
waker();
|
||
}
|
||
}
|
||
|
||
/// The host thread's refresh counter.
|
||
fn refreshed(&self) -> u64 {
|
||
*self
|
||
.0
|
||
.refreshed
|
||
.lock()
|
||
.unwrap_or_else(|error| error.into_inner())
|
||
}
|
||
|
||
/// Wakes the host thread: the state it publishes changed outside its own
|
||
/// refresh.
|
||
fn notify(&self) {
|
||
let mut refreshed = self
|
||
.0
|
||
.refreshed
|
||
.lock()
|
||
.unwrap_or_else(|error| error.into_inner());
|
||
*refreshed = refreshed.wrapping_add(1);
|
||
self.0.refreshed_cv.notify_all();
|
||
}
|
||
|
||
/// Waits for the host's next refresh, at most `timeout`, unless it was
|
||
/// notified since `seen`.
|
||
fn wait_for_refresh(&self, seen: u64, timeout: Duration) {
|
||
let refreshed = self
|
||
.0
|
||
.refreshed
|
||
.lock()
|
||
.unwrap_or_else(|error| error.into_inner());
|
||
let _ = self
|
||
.0
|
||
.refreshed_cv
|
||
.wait_timeout_while(refreshed, timeout, |refreshed| *refreshed == seen);
|
||
}
|
||
|
||
fn status(&self, snapshot: HostSnapshot, session: linux_service::Session) -> Status {
|
||
// The HUD runs in the window's app, so it went with it.
|
||
let hud_limitation = self
|
||
.window_failure()
|
||
.map(|why| window_failure_message(&why))
|
||
.or_else(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");
|
||
}
|
||
// Off the main thread: the portal may take a moment to answer.
|
||
let _ = std::thread::Builder::new()
|
||
.name("hex-background-portal".into())
|
||
.spawn(crate::linux::login_item::announce_background);
|
||
crate::labs::log_launch();
|
||
// Once, at startup: a Wayland session without wl-copy can record but
|
||
// never copy or paste, and Settings and `hex status` repeat this warning.
|
||
crate::linux::paste::missing_wayland_helper().inspect(|warning| tracing::warn!("{warning}"));
|
||
crate::audio::hex_microphone::host_service();
|
||
let launch = AppSettings::load_for_launch();
|
||
crate::linux::dictation::initialize_feedback(&launch.settings);
|
||
// Before any thread can load a model or the window can create its GPU.
|
||
crate::transcription::local_transcriber::initialize_backends();
|
||
let (control_calls, control_receiver) = mpsc::sync_channel(8);
|
||
let (dictation_controls, dictations) = mpsc::sync_channel(8);
|
||
let processing = crate::dictation::modes::ProcessingState::from_settings(&launch.settings);
|
||
let local_api = crate::local_api::LocalApi::start_for_app(
|
||
&event_path,
|
||
control_calls,
|
||
Some(dictation_controls),
|
||
Some(crate::local_api::Processing::installed(
|
||
crate::local_api::processing::dictation_processor(processing.clone()),
|
||
)),
|
||
);
|
||
let enable_on_launch = launch.settings.enable_on_launch;
|
||
let mut host = LinuxDesktopHost::new(
|
||
event_path,
|
||
launch,
|
||
crate::updater::Updater::start(),
|
||
processing,
|
||
);
|
||
let dictations = crate::dictation::service::DictationQueue::from(dictations);
|
||
host.dictations = dictations.clone();
|
||
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(control::LinuxControl {
|
||
dictations,
|
||
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 || {
|
||
host::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);
|
||
// A window Quit ends the window before the host thread notices, so bound
|
||
// that wait even if the host is stuck and never arms it.
|
||
crate::desktop::process_exit::arm_deadline();
|
||
shutdown.store(true, Ordering::Release);
|
||
let _ = worker.join();
|
||
drop(local_api);
|
||
drop(tray);
|
||
Ok(())
|
||
}
|
||
|
||
/// Stores `value` for readers only when it differs from what they last saw.
|
||
/// Returns whether it was written.
|
||
fn publish_if_changed<T: PartialEq>(slot: &Mutex<Option<T>>, value: T) -> bool {
|
||
let mut slot = slot.lock().unwrap_or_else(|error| error.into_inner());
|
||
if slot.as_ref() == Some(&value) {
|
||
return false;
|
||
}
|
||
*slot = Some(value);
|
||
true
|
||
}
|
||
|
||
/// 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();
|
||
let failed = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||
crate::rune_ui::run_app(app, requests, first, shutdown)
|
||
})) {
|
||
Ok(Ok(())) => return,
|
||
Ok(Err(error)) => error,
|
||
Err(panic) => panic_reason(panic.as_ref()),
|
||
};
|
||
tracing::error!(%failed, "the Hex window failed; Hex keeps running without it");
|
||
// `hex window show` and `hex status` say so instead of reporting
|
||
// a window that can no longer open (#979).
|
||
host.window_failed(failed);
|
||
while !shutdown.load(Ordering::Acquire) {
|
||
std::thread::sleep(Duration::from_millis(100));
|
||
}
|
||
}
|
||
|
||
/// A panic's message, when it carries one.
|
||
fn panic_reason(panic: &(dyn std::any::Any + Send)) -> String {
|
||
panic
|
||
.downcast_ref::<&str>()
|
||
.map(|message| (*message).to_owned())
|
||
.or_else(|| panic.downcast_ref::<String>().cloned())
|
||
.unwrap_or_else(|| "no reason given".into())
|
||
}
|
||
|
||
/// What `hex status` and `hex window show` report once the window failed.
|
||
fn window_failure_message(reason: &str) -> String {
|
||
let reason = reason.lines().next().unwrap_or(reason);
|
||
format!(
|
||
"The Hex window and recording HUD stopped ({reason}). Dictation still works; restart Hex to try again."
|
||
)
|
||
}
|
||
|
||
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,
|
||
launch: crate::app_settings::LaunchLoad,
|
||
updater: crate::updater::Updater,
|
||
processing: crate::dictation::modes::ProcessingState,
|
||
) -> Self {
|
||
let crate::app_settings::LaunchLoad { settings, note } = launch;
|
||
let failed = matches!(note, Some(crate::app_settings::LaunchNote::Failed(_)));
|
||
let note = note.map(crate::app_settings::LaunchNote::into_message);
|
||
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)
|
||
.sharing(processing);
|
||
// Known before the first poll, so launching keeps the saved model
|
||
// instead of applying the current layout's mapping.
|
||
let keyboard_switcher = crate::transcription::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: ListenerStatus::Disabled,
|
||
error: None,
|
||
dismissed_failure_at: None,
|
||
gnome_shortcuts: None,
|
||
// A file that isn't a JSON object starts with defaults and says
|
||
// so, but still dictates; only a failed load blocks recording.
|
||
settings_valid: !failed,
|
||
settings_error: note,
|
||
settings,
|
||
shortcut_edit: None,
|
||
prepared_transcriber: None,
|
||
transcription_preparation: None,
|
||
checking: false,
|
||
transcription_error: None,
|
||
updater,
|
||
output,
|
||
dictations: crate::dictation::service::DictationQueue::default(),
|
||
personal_commands: None,
|
||
personal_commands_checked_at: Instant::now(),
|
||
settings_modified: settings_modified(),
|
||
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();
|
||
}
|
||
|
||
/// Adopts `settings.json` when something other than Hex changed it, so
|
||
/// its modes reach the listener and the window's next save keeps the
|
||
/// edit. Hex's own saves read back equal and change nothing.
|
||
fn reload_changed_settings(&mut self) {
|
||
if cfg!(test) || self.shortcut_edit.is_some() {
|
||
return;
|
||
}
|
||
let modified = settings_modified();
|
||
if modified == self.settings_modified {
|
||
return;
|
||
}
|
||
self.settings_modified = modified;
|
||
let Ok(path) = crate::app_settings::path() else {
|
||
return;
|
||
};
|
||
// The poll runs only on an mtime change, so a broken file is reported
|
||
// once per edit instead of every two seconds. Its defaults are never
|
||
// adopted; a later valid or removed file is.
|
||
match AppSettings::load_checked_from(&path) {
|
||
Ok((_, Some(issue))) => {
|
||
self.settings_error = Some(issue.reload_error());
|
||
}
|
||
Ok((settings, None)) => {
|
||
// Only the adopted snapshot gains permission to save.
|
||
if settings != self.settings {
|
||
tracing::info!("settings.json changed outside Hex; applying it");
|
||
}
|
||
self.adopt_settings(settings);
|
||
}
|
||
Err(error) => tracing::warn!(error = format!("{error:#}"), "could not reload settings"),
|
||
}
|
||
}
|
||
|
||
fn refresh_personal_commands(&mut self) {
|
||
if cfg!(test) {
|
||
return;
|
||
}
|
||
let enabled = crate::personal_commands::host_needed(
|
||
crate::personal_commands::custom_transformations_selected(
|
||
&self.settings.dictation_processing,
|
||
),
|
||
);
|
||
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 = ListenerStatus::CouldNotEnable;
|
||
return;
|
||
}
|
||
if !crate::desktop::onboarding::model_ready(&self.settings.transcription) {
|
||
if !self.check_selected_model() {
|
||
self.status = ListenerStatus::ModelRequired;
|
||
}
|
||
return;
|
||
}
|
||
let stop = Arc::new(AtomicBool::new(false));
|
||
let worker_stop = stop.clone();
|
||
let settings = self.settings.clone();
|
||
let output = self.output.clone();
|
||
let dictations = self.dictations.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::desktop::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(),
|
||
dictations,
|
||
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 = ListenerStatus::Enabling;
|
||
}
|
||
|
||
/// 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:#}"));
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Keeps Hex's GNOME custom shortcuts (#781) in step: written while Hex
|
||
/// listens with them on, for its current shortcuts; removed when Hex is
|
||
/// disabled or they're turned off.
|
||
fn sync_gnome_shortcuts(&mut self) {
|
||
if !self.settings_valid || !crate::linux::portal::gnome() {
|
||
return;
|
||
}
|
||
let requested = self.settings.gnome_keyboard_shortcuts && self.listen_when_ready;
|
||
let shortcuts = self.listener.as_ref().map(|l| l.hotkey_status.shortcuts());
|
||
let Some(wanted) = crate::linux::gnome_shortcuts::wanted(requested, shortcuts) else {
|
||
return;
|
||
};
|
||
let key = gnome_shortcuts_key(&self.settings, wanted);
|
||
if self.gnome_shortcuts.as_deref() == Some(key.as_str()) {
|
||
return;
|
||
}
|
||
// Nothing to remove that this Hex wrote or was asked to keep.
|
||
if !wanted && self.gnome_shortcuts.is_none() && !self.settings.gnome_keyboard_shortcuts {
|
||
self.gnome_shortcuts = Some(key);
|
||
return;
|
||
}
|
||
let result = if wanted {
|
||
crate::linux::login_item::launcher()
|
||
.and_then(|hex| crate::linux::gnome_shortcuts::install(&self.settings, &hex))
|
||
} else {
|
||
crate::linux::gnome_shortcuts::remove()
|
||
};
|
||
match result {
|
||
Ok(()) => tracing::info!(written = wanted, "updated Hex's GNOME keyboard shortcuts"),
|
||
Err(error) => {
|
||
self.error = Some(format!(
|
||
"Could not update GNOME keyboard shortcuts: {error:#}"
|
||
));
|
||
}
|
||
}
|
||
self.gnome_shortcuts = Some(key);
|
||
}
|
||
|
||
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 = ListenerStatus::Disabling;
|
||
return;
|
||
}
|
||
// Disable during a model check: stop the check too, and never leave
|
||
// the listener card on Enabling with nothing to finish. A model
|
||
// download the person started keeps running.
|
||
if self.status == ListenerStatus::Enabling {
|
||
if self.checking {
|
||
self.cancel_transcription_preparation();
|
||
}
|
||
self.status = ListenerStatus::Disabled;
|
||
}
|
||
}
|
||
|
||
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, and a restart that never
|
||
// happened must not reopen the window on the next launch.
|
||
if let Some(Err(error)) = self.updater.take_restart() {
|
||
if let Some(marker) = reopen_marker() {
|
||
let _ = std::fs::remove_file(marker);
|
||
}
|
||
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();
|
||
self.reload_changed_settings();
|
||
}
|
||
let mut start_listener = false;
|
||
if let Some(preparation) = self
|
||
.transcription_preparation
|
||
.take_if(|preparation| preparation.worker.is_finished())
|
||
{
|
||
self.checking = false;
|
||
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();
|
||
// Only a preparation that changes what Hex runs
|
||
// replaces the saved choice: a check of that same
|
||
// model, or of a lost import's fallback, leaves the
|
||
// saved selection alone.
|
||
let effective = crate::transcription::custom_models::runnable(
|
||
&self.settings.transcription,
|
||
);
|
||
let saved = if selection == effective {
|
||
Ok(self.settings.clone())
|
||
} else {
|
||
save_with(|settings| settings.remember_transcription(selection))
|
||
};
|
||
match saved {
|
||
Ok(candidate) => {
|
||
// Read from disk, so it may carry an outside
|
||
// edit the modes must pick up too.
|
||
self.settings = candidate;
|
||
self.settings_valid = true;
|
||
self.transcription_error = None;
|
||
self.settings_error = None;
|
||
self.apply_output_settings();
|
||
// 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 if !crate::desktop::onboarding::model_ready(
|
||
&self.settings.transcription,
|
||
) {
|
||
// One check per Enable: a finished check
|
||
// that did not make the model ready is
|
||
// not retried by itself.
|
||
self.status = ListenerStatus::ModelRequired;
|
||
} 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.note_model_check_failure();
|
||
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 = ListenerStatus::Disabled,
|
||
Err(error) => {
|
||
self.status = ListenerStatus::CouldNotEnable;
|
||
self.error = Some(error);
|
||
}
|
||
}
|
||
}
|
||
|
||
// A check canceled while waiting (a switch or an explicit cancel)
|
||
// must not leave the host on Enabling with nothing pending.
|
||
if self.listen_when_ready
|
||
&& !self.is_running()
|
||
&& self.status == ListenerStatus::Enabling
|
||
&& self.transcription_preparation.is_none()
|
||
{
|
||
self.start();
|
||
}
|
||
|
||
self.refresh_shortcut_edit();
|
||
self.sync_gnome_shortcuts();
|
||
|
||
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;
|
||
}
|
||
}
|
||
|
||
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 settings.source.revision != 0 && settings.source.revision < self.settings.source.revision
|
||
{
|
||
return;
|
||
}
|
||
// A valid file clears the parse error even when it loads the settings
|
||
// already running (a fixed file equal to what Hex had in memory).
|
||
self.settings_error = None;
|
||
if self.settings_valid && settings == self.settings {
|
||
self.settings.source = settings.source;
|
||
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.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()?;
|
||
match target {
|
||
// The cancel key is grabbed only while a recording runs,
|
||
// and never through the portal: nothing to try now.
|
||
ShortcutTarget::Cancel => {}
|
||
_ if crate::linux::session::LinuxSession::detect().is_wayland() => {
|
||
// The listener asks the desktop again and reports what it granted.
|
||
binding.portal_trigger()?;
|
||
}
|
||
_ => {
|
||
// 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)
|
||
}
|
||
ShortcutTarget::TypedText => settings.typed_text_hotkey = Some(binding),
|
||
ShortcutTarget::TerminalPaste => {
|
||
settings.terminal_paste_hotkey = Some(binding)
|
||
}
|
||
ShortcutTarget::SecondDictation => {
|
||
settings.second_dictation_hotkey = Some(binding)
|
||
}
|
||
ShortcutTarget::Cancel => settings.cancel_hotkey = 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 selection = crate::transcription::models::TranscriptionSelection { model, language };
|
||
self.prepare_transcription(selection, false, false)
|
||
}
|
||
|
||
/// A layout change not yet polled counts as before this choice, so it
|
||
/// cannot later undo it.
|
||
fn manual_choice(&mut self) {
|
||
if let Some(source) = self
|
||
.input_sources
|
||
.as_mut()
|
||
.and_then(|watcher| watcher.poll())
|
||
{
|
||
self.keyboard_switcher
|
||
.source_changed(source, Instant::now());
|
||
}
|
||
self.keyboard_switcher.manual_choice();
|
||
self.supersede_automatic();
|
||
}
|
||
|
||
/// Cancels only keyboard-switch work; a manual operation is superseded
|
||
/// once the debounced choice is due.
|
||
fn supersede_automatic(&mut self) {
|
||
self.keyboard_switch = None;
|
||
if let Some(preparation) = &self.transcription_preparation
|
||
&& preparation.automatic
|
||
{
|
||
preparation.canceled.store(true, Ordering::Relaxed);
|
||
}
|
||
}
|
||
|
||
/// Follows the XKB group while switching is on, and prepares a
|
||
/// mapping's installed model once it is due.
|
||
fn switch_with_keyboard(&mut self) {
|
||
let enabled = self.settings.keyboard_model_switching.enabled;
|
||
if !enabled {
|
||
self.input_sources = None;
|
||
} else if self.input_sources_polled_at.elapsed() >= INPUT_SOURCE_POLL {
|
||
self.input_sources_polled_at = Instant::now();
|
||
if self.input_sources.is_none() {
|
||
self.input_sources = crate::keyboard_input_sources::Watcher::connect();
|
||
}
|
||
if let Some(source) = self
|
||
.input_sources
|
||
.as_mut()
|
||
.and_then(|watcher| watcher.poll())
|
||
&& self
|
||
.keyboard_switcher
|
||
.source_changed(source, Instant::now())
|
||
{
|
||
self.supersede_automatic();
|
||
}
|
||
}
|
||
if let Some(choice) = self.keyboard_switcher.take_due(Instant::now()) {
|
||
let selection = crate::transcription::models::TranscriptionSelection {
|
||
language: choice.language,
|
||
..self.settings.transcription_for_model(choice.model)
|
||
};
|
||
// Whatever runs is superseded; the current model and language
|
||
// need no preparation.
|
||
if let Some(preparation) = &self.transcription_preparation {
|
||
preparation.canceled.store(true, Ordering::Relaxed);
|
||
}
|
||
self.keyboard_switch = (selection.model != self.settings.transcription.model
|
||
|| selection.language != self.settings.transcription.language)
|
||
.then_some(selection);
|
||
}
|
||
if self.transcription_preparation.is_none()
|
||
&& self.shortcut_edit.is_none()
|
||
&& let Some(selection) = self.keyboard_switch.take()
|
||
&& let Err(error) = self.prepare_transcription(selection, true, true)
|
||
{
|
||
self.transcription_error = Some(format!("{error:#}"));
|
||
}
|
||
}
|
||
|
||
fn cancel_transcription_preparation(&mut self) {
|
||
if let Some(preparation) = &self.transcription_preparation {
|
||
preparation.canceled.store(true, Ordering::Relaxed);
|
||
}
|
||
self.checking = false;
|
||
self.transcription_error = None;
|
||
}
|
||
}
|
||
|
||
/// Saves one host-owned change on top of the current `settings.json`, so
|
||
/// edits the window saved meanwhile survive.
|
||
/// Annotate's shortcut, while Annotate is on.
|
||
fn capture_shortcut(settings: &AppSettings) -> Option<&crate::app_settings::HotkeyBinding> {
|
||
#[cfg(hex_capture)]
|
||
if settings.capture.enabled {
|
||
return Some(&settings.capture.hotkey);
|
||
}
|
||
let _ = settings;
|
||
None
|
||
}
|
||
|
||
/// What the GNOME custom shortcuts were last synced for: a new key means an
|
||
/// entry was added, removed, or rebound. Typed text is included while its
|
||
/// lab is on and its shortcut is bound, so toggling either resyncs.
|
||
fn gnome_shortcuts_key(settings: &AppSettings, wanted: bool) -> String {
|
||
format!(
|
||
"{wanted} {:?} {:?} {:?} {:?}",
|
||
settings.dictation_hotkey,
|
||
settings.paste_last_hotkey,
|
||
capture_shortcut(settings),
|
||
settings.active_typed_text_hotkey()
|
||
)
|
||
}
|
||
|
||
fn settings_modified() -> Option<std::time::SystemTime> {
|
||
let path = crate::app_settings::path().ok()?;
|
||
std::fs::metadata(path)
|
||
.and_then(|metadata| metadata.modified())
|
||
.ok()
|
||
}
|
||
|
||
fn save_with(change: impl FnOnce(&mut AppSettings)) -> Result<AppSettings> {
|
||
let mut settings = AppSettings::load()?;
|
||
let base = settings.clone();
|
||
change(&mut settings);
|
||
base.update(&settings)
|
||
}
|
||
|
||
#[cfg(not(test))]
|
||
fn save_listening(_: &AppSettings, enabled: bool) -> Result<AppSettings> {
|
||
save_with(|settings| settings.enable_on_launch = enabled)
|
||
}
|
||
|
||
/// Tests never write the person's `settings.json`.
|
||
#[cfg(test)]
|
||
fn save_listening(current: &AppSettings, enabled: bool) -> Result<AppSettings> {
|
||
let mut settings = current.clone();
|
||
settings.enable_on_launch = enabled;
|
||
Ok(settings)
|
||
}
|
||
|
||
impl Drop for LinuxDesktopHost {
|
||
fn drop(&mut self) {
|
||
self.updater.stop();
|
||
self.stop();
|
||
self.cancel_transcription_preparation();
|
||
}
|
||
}
|
||
|
||
impl LinuxDesktopHost {
|
||
fn host_snapshot(&self) -> HostSnapshot {
|
||
HostSnapshot {
|
||
desktop: self.snapshot(),
|
||
settings: self.settings.clone(),
|
||
editing: self.shortcut_edit.is_some(),
|
||
}
|
||
}
|
||
|
||
fn snapshot(&self) -> DesktopSnapshot {
|
||
let update_status = self.updater.status();
|
||
DesktopSnapshot {
|
||
activity: self.activity.clone(),
|
||
listener: DesktopListenerSnapshot {
|
||
running: self.is_running(),
|
||
warming: self.listener.as_ref().is_some_and(|listener| {
|
||
matches!(listener.startup, ListenerStartup::Awaiting { .. })
|
||
}),
|
||
status: self.status,
|
||
notice: crate::linux::paste::listener_warning(self.is_running()),
|
||
shortcuts: self
|
||
.listener
|
||
.as_ref()
|
||
.map(|listener| listener.hotkey_status.shortcuts())
|
||
.unwrap_or_default(),
|
||
shortcuts_configurable: self
|
||
.listener
|
||
.as_ref()
|
||
.is_some_and(|listener| listener.hotkey_status.configurable()),
|
||
..DesktopListenerSnapshot::default()
|
||
},
|
||
operation_error: self
|
||
.error
|
||
.clone()
|
||
.or_else(|| self.settings_error.clone())
|
||
.or_else(|| {
|
||
self.activity
|
||
.last_failure
|
||
.as_ref()
|
||
.filter(|(at, _)| Some(*at) != self.dismissed_failure_at)
|
||
.map(|(_, message)| message.clone())
|
||
}),
|
||
transcription: DesktopTranscriptionSnapshot {
|
||
downloaded_bytes: self
|
||
.transcription_preparation
|
||
.as_ref()
|
||
.map_or(0, |preparation| {
|
||
preparation.progress.load(Ordering::Relaxed)
|
||
}),
|
||
error: self.transcription_error.clone(),
|
||
preparation_stage: self.transcription_preparation.as_ref().map(|preparation| {
|
||
crate::transcription::models::ModelPreparationStage::load(&preparation.stage)
|
||
}),
|
||
selection: self.settings.transcription.clone(),
|
||
preparing: self
|
||
.transcription_preparation
|
||
.as_ref()
|
||
.map(|preparation| preparation.model),
|
||
// The listener shares its engine with this process, so its
|
||
// last finished command says where the model runs.
|
||
backend: crate::transcription::engine::TranscriptionEngine::shared()
|
||
.and_then(|engine| engine.held_backend()),
|
||
},
|
||
update_status,
|
||
update_notes: self.updater.notes(),
|
||
}
|
||
}
|
||
|
||
/// Where `hex` shortcut commands go: the listener, once it reports its
|
||
/// session (a listener still loading its model would replay them late).
|
||
fn shortcut_route(&self) -> Option<ShortcutRoute> {
|
||
self.listener
|
||
.as_ref()
|
||
.filter(|listener| matches!(listener.startup, ListenerStartup::Observed))
|
||
.map(|listener| ShortcutRoute {
|
||
commands: listener.commands.clone(),
|
||
})
|
||
}
|
||
|
||
fn dispatch(&mut self, action: DesktopAction) -> Result<()> {
|
||
match action {
|
||
DesktopAction::ClearError => {
|
||
self.error = None;
|
||
self.settings_error = None;
|
||
self.dismissed_failure_at = self.activity.last_failure.as_ref().map(|(at, _)| *at);
|
||
}
|
||
DesktopAction::CheckForUpdates
|
||
| DesktopAction::OpenUpdate
|
||
| DesktopAction::RestartIntoUpdate
|
||
| DesktopAction::ConfirmUpdateSwitch
|
||
| DesktopAction::WindowFocused => {
|
||
if let Err(error) = self.updater.act(&action) {
|
||
self.error = Some(format!("Could not restart Hex: {error:#}"));
|
||
return Err(error);
|
||
}
|
||
// Only an accepted restart relaunches with the window open;
|
||
// a refused one leaves the next launch as it was.
|
||
if matches!(action, DesktopAction::RestartIntoUpdate)
|
||
&& let Some(marker) = reopen_marker()
|
||
{
|
||
let _ = std::fs::write(marker, b"");
|
||
}
|
||
}
|
||
DesktopAction::SetDictationShortcut(shortcut) => {
|
||
self.set_hotkey(ShortcutTarget::Dictation, shortcut)?;
|
||
}
|
||
DesktopAction::StartListening => {
|
||
self.error = None;
|
||
self.dismissed_failure_at = self.activity.last_failure.as_ref().map(|(at, _)| *at);
|
||
self.start();
|
||
self.remember_listening(true);
|
||
}
|
||
DesktopAction::StopListening => {
|
||
if let Some(listener) = &self.listener {
|
||
listener.hotkey_status.forget_on_stop();
|
||
}
|
||
self.stop();
|
||
self.remember_listening(false);
|
||
}
|
||
DesktopAction::ConfigureShortcuts => {
|
||
if let Some(listener) = &self.listener {
|
||
listener.hotkey_status.configure();
|
||
}
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use crate::transcription::models::{
|
||
ModelPreparationStage, TranscriptionModelId, TranscriptionSelection,
|
||
};
|
||
|
||
fn test_host(launch: crate::app_settings::LaunchLoad) -> LinuxDesktopHost {
|
||
let processing = crate::dictation::modes::ProcessingState::from_settings(&launch.settings);
|
||
LinuxDesktopHost::new(
|
||
PathBuf::new(),
|
||
launch,
|
||
crate::updater::Updater::idle(),
|
||
processing,
|
||
)
|
||
}
|
||
|
||
fn host_for_edit(running: bool) -> LinuxDesktopHost {
|
||
let settings = AppSettings {
|
||
transcription: TranscriptionSelection {
|
||
// Prevent the restart assertions from opening a real microphone.
|
||
model: TranscriptionModelId::AppleSpeech,
|
||
..Default::default()
|
||
},
|
||
..Default::default()
|
||
};
|
||
let mut host = test_host(crate::app_settings::LaunchLoad {
|
||
settings,
|
||
note: None,
|
||
});
|
||
if running {
|
||
host.listener = Some(Listener {
|
||
worker: std::thread::spawn(|| Ok(())),
|
||
stop: Arc::new(AtomicBool::new(false)),
|
||
startup: ListenerStartup::Observed,
|
||
hotkey_status: Default::default(),
|
||
commands: mpsc::sync_channel(1).0,
|
||
updates: mpsc::channel().0,
|
||
});
|
||
host.listen_when_ready = true;
|
||
}
|
||
host
|
||
}
|
||
|
||
fn set_finished_edit(host: &mut LinuxDesktopHost, result: Result<AppSettings>) {
|
||
let worker = std::thread::spawn(move || result);
|
||
while !worker.is_finished() {
|
||
std::thread::yield_now();
|
||
}
|
||
host.shortcut_edit.as_mut().unwrap().worker = Some(worker);
|
||
}
|
||
|
||
#[test]
|
||
fn a_failed_window_never_reports_itself_open() {
|
||
static SHUTDOWN: AtomicBool = AtomicBool::new(false);
|
||
let host = HostHandle::new(host_for_edit(false), &SHUTDOWN);
|
||
host.set_window_visible(Arc::new(|| true));
|
||
assert!(host.window_open());
|
||
let panic = std::panic::catch_unwind(|| panic!("Invalid surface")).unwrap_err();
|
||
host.window_failed(panic_reason(panic.as_ref()));
|
||
assert!(!host.window_open());
|
||
let status = host.status(host.snapshot(), linux_service::Session::current());
|
||
assert!(!status.window_open);
|
||
assert!(
|
||
status
|
||
.hud_limitation
|
||
.is_some_and(|why| why.contains("Invalid surface"))
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn a_notification_wakes_the_idle_host_before_its_tick() {
|
||
static SHUTDOWN: AtomicBool = AtomicBool::new(false);
|
||
let host = HostHandle::new(host_for_edit(false), &SHUTDOWN);
|
||
let seen = host.refreshed();
|
||
let waiter = host.clone();
|
||
let started = Instant::now();
|
||
let waiting = std::thread::spawn(move || {
|
||
waiter.wait_for_refresh(seen, Duration::from_secs(5));
|
||
started.elapsed()
|
||
});
|
||
std::thread::sleep(Duration::from_millis(20));
|
||
host.notify();
|
||
assert!(waiting.join().unwrap() < Duration::from_secs(1));
|
||
}
|
||
|
||
#[test]
|
||
fn unchanged_status_is_not_published_again() {
|
||
let published = Mutex::new(None);
|
||
assert!(publish_if_changed(&published, 1));
|
||
assert!(!publish_if_changed(&published, 1));
|
||
assert!(publish_if_changed(&published, 2));
|
||
assert_eq!(*published.lock().unwrap(), Some(2));
|
||
}
|
||
|
||
/// The GNOME sync cache key must move when the typed-text lab or its
|
||
/// binding changes, or stale `hex-typed-text` entries stay behind.
|
||
#[test]
|
||
fn the_gnome_shortcut_key_tracks_typed_text() {
|
||
use crate::app_settings::{HotkeyKey, HotkeyModifiers};
|
||
|
||
let binding = HotkeyBinding {
|
||
modifiers: HotkeyModifiers::control_option(),
|
||
key: Some(HotkeyKey::named("t")),
|
||
};
|
||
let mut settings = AppSettings {
|
||
typed_text_hotkey: Some(binding.clone()),
|
||
..AppSettings::default()
|
||
};
|
||
let lab_off = gnome_shortcuts_key(&settings, true);
|
||
|
||
settings.labs.typed_text = true;
|
||
let bound = gnome_shortcuts_key(&settings, true);
|
||
assert_ne!(lab_off, bound, "turning the lab on adds an entry");
|
||
|
||
settings.typed_text_hotkey = Some(HotkeyBinding {
|
||
modifiers: HotkeyModifiers::control(),
|
||
..binding
|
||
});
|
||
let rebound = gnome_shortcuts_key(&settings, true);
|
||
assert_ne!(bound, rebound, "changing the binding rewrites it");
|
||
|
||
settings.typed_text_hotkey = None;
|
||
let unbound = gnome_shortcuts_key(&settings, true);
|
||
assert_ne!(rebound, unbound, "unbinding removes it");
|
||
assert_eq!(
|
||
lab_off, unbound,
|
||
"no bound typed-text shortcut means no entry either way"
|
||
);
|
||
|
||
settings.labs.typed_text = false;
|
||
assert_eq!(
|
||
gnome_shortcuts_key(&settings, true),
|
||
lab_off,
|
||
"turning the lab off returns to the lab-off key"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn a_settings_parse_note_does_not_block_capture() {
|
||
let mut host = test_host(
|
||
// A model never installed on Linux keeps `start` from opening a
|
||
// real microphone while still proving the validity gate passed.
|
||
crate::app_settings::LaunchLoad {
|
||
settings: host_for_edit(false).settings.clone(),
|
||
note: Some(crate::app_settings::LaunchNote::Unparseable(
|
||
"Hex couldn't read settings.json and started with defaults.".into(),
|
||
)),
|
||
},
|
||
);
|
||
assert!(host.settings_valid);
|
||
assert!(host.settings_error.is_some());
|
||
host.start();
|
||
assert!(host.listen_when_ready);
|
||
assert_eq!(host.status, ListenerStatus::ModelRequired);
|
||
assert!(!host.is_running());
|
||
}
|
||
|
||
#[test]
|
||
fn malformed_settings_cannot_start_even_after_dismissing_the_error() {
|
||
let mut host = test_host(
|
||
// A model never installed on Linux, so the resumed start below
|
||
// cannot open the microphone where the real model is installed.
|
||
crate::app_settings::LaunchLoad {
|
||
settings: host_for_edit(false).settings.clone(),
|
||
note: Some(crate::app_settings::LaunchNote::Failed(
|
||
"Could not load Linux settings: invalid JSON".into(),
|
||
)),
|
||
},
|
||
);
|
||
host.start();
|
||
assert!(!host.is_running());
|
||
assert_eq!(host.status, ListenerStatus::CouldNotEnable);
|
||
host.dispatch(DesktopAction::ClearError).unwrap();
|
||
host.start();
|
||
assert!(!host.is_running());
|
||
assert_eq!(host.status, ListenerStatus::CouldNotEnable);
|
||
assert!(!host.settings_valid);
|
||
|
||
let mut recovered = host.settings.clone();
|
||
recovered.double_tap_lock = false;
|
||
host.adopt_settings(recovered.clone());
|
||
assert!(host.settings_valid);
|
||
assert_eq!(host.settings, recovered);
|
||
assert!(!host.is_running());
|
||
assert_eq!(host.status, ListenerStatus::ModelRequired);
|
||
}
|
||
|
||
#[test]
|
||
fn listener_startup_ignores_the_previous_session_until_a_new_one_arrives() {
|
||
for previous_session in [None, Some(10)] {
|
||
let mut listener = Listener {
|
||
stop: Arc::new(AtomicBool::new(false)),
|
||
worker: std::thread::spawn(|| Ok(())),
|
||
startup: ListenerStartup::Awaiting { previous_session },
|
||
hotkey_status: Default::default(),
|
||
commands: mpsc::sync_channel(1).0,
|
||
updates: mpsc::channel().0,
|
||
};
|
||
listener.observe_session(previous_session);
|
||
assert!(matches!(listener.startup, ListenerStartup::Awaiting { .. }));
|
||
listener.observe_session(Some(20));
|
||
assert!(matches!(listener.startup, ListenerStartup::Observed));
|
||
listener.observe_session(previous_session);
|
||
assert!(matches!(listener.startup, ListenerStartup::Observed));
|
||
listener.stop();
|
||
assert!(listener.stop.load(Ordering::Relaxed));
|
||
listener.finish().unwrap();
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn a_listener_still_starting_is_warming_until_its_session_begins() {
|
||
let mut host = host_for_edit(true);
|
||
assert!(!host.snapshot().listener.warming);
|
||
host.listener.as_mut().unwrap().startup = ListenerStartup::Awaiting {
|
||
previous_session: None,
|
||
};
|
||
assert!(host.snapshot().listener.warming);
|
||
host.listener.as_mut().unwrap().startup = ListenerStartup::Observed;
|
||
assert!(!host.snapshot().listener.warming);
|
||
}
|
||
|
||
#[test]
|
||
fn listener_completion_waits_for_the_worker_and_preserves_errors() {
|
||
for outcome in [Some(Ok(())), Some(Err("listener failed".into())), None] {
|
||
let expected = outcome
|
||
.clone()
|
||
.unwrap_or_else(|| Err("listener worker stopped unexpectedly".into()))
|
||
.err();
|
||
let mut host = host_for_edit(true);
|
||
let (release, held) = mpsc::channel();
|
||
host.listener.as_mut().unwrap().worker = std::thread::spawn(move || {
|
||
held.recv_timeout(Duration::from_secs(5)).unwrap();
|
||
outcome.expect("fixture listener panic")
|
||
});
|
||
host.refresh();
|
||
assert!(host.is_running());
|
||
assert!(!host.listener.as_ref().unwrap().stop.load(Ordering::Relaxed));
|
||
release.send(()).unwrap();
|
||
while !host.listener.as_ref().unwrap().worker.is_finished() {
|
||
std::thread::yield_now();
|
||
}
|
||
host.refresh();
|
||
assert!(!host.is_running());
|
||
assert!(host.listener.is_none());
|
||
assert_eq!(host.error, expected);
|
||
assert_eq!(
|
||
host.status,
|
||
if expected.is_some() {
|
||
ListenerStatus::CouldNotEnable
|
||
} else {
|
||
ListenerStatus::Disabled
|
||
}
|
||
);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn disabling_during_a_model_check_cancels_it_and_sets_disabled() {
|
||
let mut host = host_for_edit(false);
|
||
host.status = ListenerStatus::Enabling;
|
||
host.listen_when_ready = true;
|
||
let canceled = Arc::new(AtomicBool::new(false));
|
||
let worker_canceled = canceled.clone();
|
||
host.transcription_preparation = Some(TranscriptionPreparation {
|
||
canceled: canceled.clone(),
|
||
model: TranscriptionModelId::default(),
|
||
progress: Arc::new(AtomicU64::new(0)),
|
||
stage: Arc::new(AtomicU8::new(ModelPreparationStage::Verifying as u8)),
|
||
worker: std::thread::spawn(move || {
|
||
while !worker_canceled.load(Ordering::Relaxed) {
|
||
std::thread::yield_now();
|
||
}
|
||
Err("check canceled".into())
|
||
}),
|
||
automatic: false,
|
||
});
|
||
// The preparation is Enable's own installed-only check.
|
||
host.checking = true;
|
||
host.stop();
|
||
assert_eq!(host.status, ListenerStatus::Disabled);
|
||
assert!(canceled.load(Ordering::Relaxed));
|
||
if let Some(preparation) = host.transcription_preparation.take() {
|
||
assert!(preparation.worker.join().unwrap().is_err());
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn disabling_during_a_model_download_does_not_cancel_it() {
|
||
let mut host = host_for_edit(false);
|
||
host.status = ListenerStatus::Enabling;
|
||
host.listen_when_ready = true;
|
||
let canceled = Arc::new(AtomicBool::new(false));
|
||
host.transcription_preparation = Some(TranscriptionPreparation {
|
||
canceled: canceled.clone(),
|
||
model: TranscriptionModelId::default(),
|
||
progress: Arc::new(AtomicU64::new(10)),
|
||
stage: Arc::new(AtomicU8::new(ModelPreparationStage::Downloading as u8)),
|
||
worker: std::thread::spawn(|| Err("download finished".into())),
|
||
automatic: false,
|
||
});
|
||
host.checking = false;
|
||
host.stop();
|
||
assert!(!canceled.load(Ordering::Relaxed));
|
||
assert_eq!(host.status, ListenerStatus::Disabled);
|
||
assert!(
|
||
host.transcription_preparation
|
||
.take()
|
||
.unwrap()
|
||
.worker
|
||
.join()
|
||
.unwrap()
|
||
.is_err()
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn a_cancelled_model_check_does_not_leave_the_host_enabling() {
|
||
let mut host = host_for_edit(false);
|
||
host.listen_when_ready = true;
|
||
host.status = ListenerStatus::Enabling;
|
||
// The state a switch or an explicit cancel leaves behind: a canceled
|
||
// preparation whose worker has finished.
|
||
host.transcription_preparation = Some(TranscriptionPreparation {
|
||
canceled: Arc::new(AtomicBool::new(true)),
|
||
model: TranscriptionModelId::default(),
|
||
progress: Arc::new(AtomicU64::new(0)),
|
||
stage: Arc::new(AtomicU8::new(ModelPreparationStage::Verifying as u8)),
|
||
worker: std::thread::spawn(|| Err("check canceled".into())),
|
||
automatic: false,
|
||
});
|
||
while !host
|
||
.transcription_preparation
|
||
.as_ref()
|
||
.unwrap()
|
||
.worker
|
||
.is_finished()
|
||
{
|
||
std::thread::yield_now();
|
||
}
|
||
host.refresh();
|
||
assert_eq!(host.status, ListenerStatus::ModelRequired);
|
||
}
|
||
|
||
#[test]
|
||
fn preparation_completion_preserves_selection_and_honors_cancellation() {
|
||
for (canceled, panics) in [(false, false), (false, true), (true, false), (true, true)] {
|
||
let mut host = host_for_edit(false);
|
||
let original = host.settings.clone();
|
||
let (release, held) = mpsc::channel();
|
||
host.transcription_preparation = Some(TranscriptionPreparation {
|
||
canceled: Arc::new(AtomicBool::new(false)),
|
||
model: TranscriptionModelId::default(),
|
||
progress: Arc::new(AtomicU64::new(0)),
|
||
stage: Arc::new(AtomicU8::new(ModelPreparationStage::Loading as u8)),
|
||
worker: std::thread::spawn(move || {
|
||
held.recv_timeout(Duration::from_secs(5)).unwrap();
|
||
assert!(!panics, "fixture preparation panic");
|
||
Err("model unavailable".into())
|
||
}),
|
||
automatic: false,
|
||
});
|
||
if canceled {
|
||
host.cancel_transcription_preparation();
|
||
}
|
||
host.refresh();
|
||
assert!(host.has_pending_work());
|
||
release.send(()).unwrap();
|
||
while !host
|
||
.transcription_preparation
|
||
.as_ref()
|
||
.unwrap()
|
||
.worker
|
||
.is_finished()
|
||
{
|
||
std::thread::yield_now();
|
||
}
|
||
host.refresh();
|
||
assert!(!host.has_pending_work());
|
||
assert_eq!(host.settings, original);
|
||
assert_eq!(
|
||
host.transcription_error.as_deref(),
|
||
if canceled {
|
||
None
|
||
} else if panics {
|
||
Some("model preparation worker stopped unexpectedly")
|
||
} else {
|
||
Some("model unavailable")
|
||
}
|
||
);
|
||
}
|
||
}
|
||
|
||
/// A running fixture listener that keeps what the host sends it.
|
||
fn listening_host() -> (LinuxDesktopHost, Receiver<ListenerUpdate>) {
|
||
let mut host = host_for_edit(true);
|
||
let (updates, received) = mpsc::channel();
|
||
let listener = host.listener.as_mut().unwrap();
|
||
listener.updates = updates;
|
||
// Runs until stopped, as a real listener does.
|
||
let stop = listener.stop.clone();
|
||
listener.worker = std::thread::spawn(move || {
|
||
while !stop.load(Ordering::Relaxed) {
|
||
std::thread::sleep(Duration::from_millis(5));
|
||
}
|
||
Ok(())
|
||
});
|
||
host.status = ListenerStatus::Enabled;
|
||
(host, received)
|
||
}
|
||
|
||
#[test]
|
||
fn settings_changes_apply_in_place_without_stopping_the_listener() {
|
||
let (mut host, received) = listening_host();
|
||
let before = host.snapshot();
|
||
let mut candidate = host.settings.clone();
|
||
candidate.paste_with_shift = !candidate.paste_with_shift;
|
||
candidate.indicator_position = crate::app_settings::IndicatorPosition::Bottom;
|
||
candidate.sound_effect_volume = 0.25;
|
||
host.adopt_settings(candidate.clone());
|
||
assert_eq!(host.settings, candidate);
|
||
assert!(!host.listener.as_ref().unwrap().stop.load(Ordering::Relaxed));
|
||
assert!(matches!(
|
||
received.try_iter().collect::<Vec<_>>().as_slice(),
|
||
[ListenerUpdate::Settings(sent)] if **sent == candidate
|
||
));
|
||
host.refresh();
|
||
assert!(host.is_running());
|
||
assert_eq!(host.snapshot().listener, before.listener);
|
||
}
|
||
|
||
#[test]
|
||
fn a_shortcut_edit_suspends_matching_without_stopping_the_listener() {
|
||
let (mut host, received) = listening_host();
|
||
host.begin_shortcut_edit(ShortcutTarget::Dictation, None);
|
||
assert!(host.listen_when_ready);
|
||
assert!(!host.listener.as_ref().unwrap().stop.load(Ordering::Relaxed));
|
||
host.cancel_shortcut_edit();
|
||
host.refresh_shortcut_edit();
|
||
assert!(host.shortcut_edit.is_none());
|
||
assert_eq!(host.status, ListenerStatus::Enabled);
|
||
let updates = received.try_iter().collect::<Vec<_>>();
|
||
assert!(matches!(
|
||
updates.as_slice(),
|
||
[
|
||
ListenerUpdate::SuspendShortcuts(true),
|
||
ListenerUpdate::Settings(_),
|
||
ListenerUpdate::SuspendShortcuts(false)
|
||
]
|
||
));
|
||
}
|
||
|
||
#[test]
|
||
fn canceled_or_failed_capture_restores_prior_listening_without_changing_settings() {
|
||
for running in [false, true] {
|
||
for cancel in [false, true] {
|
||
let mut host = host_for_edit(running);
|
||
let original = host.settings.clone();
|
||
host.begin_shortcut_edit(ShortcutTarget::Dictation, None);
|
||
assert!(host.capturing_hotkey());
|
||
host.listener = None;
|
||
if cancel {
|
||
host.cancel_shortcut_edit();
|
||
} else {
|
||
set_finished_edit(
|
||
&mut host,
|
||
Err(color_eyre::eyre::eyre!("input permission denied")),
|
||
);
|
||
}
|
||
host.refresh_shortcut_edit();
|
||
assert_eq!(host.settings, original);
|
||
assert_eq!(host.listen_when_ready, running);
|
||
assert_eq!(host.error.is_some(), !cancel);
|
||
assert!(host.shortcut_edit.is_none());
|
||
assert!(!host.capturing_hotkey());
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn cancel_signals_worker_and_does_not_wait_or_restart_until_it_finishes() {
|
||
let mut host = host_for_edit(true);
|
||
host.begin_shortcut_edit(ShortcutTarget::Dictation, None);
|
||
host.listener = None;
|
||
let (release, held) = mpsc::channel();
|
||
host.shortcut_edit.as_mut().unwrap().worker = Some(std::thread::spawn(move || {
|
||
let _ = held.recv();
|
||
Err(color_eyre::eyre::eyre!("capture canceled"))
|
||
}));
|
||
host.cancel_shortcut_edit();
|
||
host.refresh_shortcut_edit();
|
||
let edit = host.shortcut_edit.as_mut().unwrap();
|
||
assert!(edit.canceled.load(Ordering::Acquire));
|
||
assert!(edit.worker.is_some());
|
||
assert!(host.listen_when_ready);
|
||
release.send(()).unwrap();
|
||
let _ = host
|
||
.shortcut_edit
|
||
.as_mut()
|
||
.unwrap()
|
||
.worker
|
||
.take()
|
||
.unwrap()
|
||
.join()
|
||
.unwrap()
|
||
.unwrap_err();
|
||
host.refresh_shortcut_edit();
|
||
assert!(host.listen_when_ready);
|
||
assert!(host.shortcut_edit.is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn closing_the_window_cancels_only_an_uncommitted_capture() {
|
||
static SHUTDOWN: AtomicBool = AtomicBool::new(false);
|
||
let mut host = host_for_edit(true);
|
||
host.begin_shortcut_edit(ShortcutTarget::Dictation, None);
|
||
let handle = HostHandle::new(host, &SHUTDOWN);
|
||
handle.window_closed();
|
||
{
|
||
let mut host = handle.lock();
|
||
let edit = host.shortcut_edit.as_ref().unwrap();
|
||
assert!(edit.canceled.load(Ordering::Acquire));
|
||
host.listener = None;
|
||
host.refresh_shortcut_edit();
|
||
assert!(host.listen_when_ready);
|
||
}
|
||
|
||
// Without a capture, closing the window leaves dictation alone.
|
||
let handle = HostHandle::new(host_for_edit(true), &SHUTDOWN);
|
||
handle.window_closed();
|
||
let host = handle.lock();
|
||
assert!(host.is_running());
|
||
assert!(host.listen_when_ready);
|
||
assert!(!host.listener.as_ref().unwrap().stop.load(Ordering::Acquire));
|
||
}
|
||
|
||
#[test]
|
||
fn commands_route_only_to_a_started_listener() {
|
||
let mut host = host_for_edit(false);
|
||
assert!(host.shortcut_route().is_none());
|
||
let (commands, received) = mpsc::sync_channel(4);
|
||
host.listener = Some(Listener {
|
||
worker: std::thread::spawn(|| Ok(())),
|
||
stop: Arc::new(AtomicBool::new(false)),
|
||
startup: ListenerStartup::Awaiting {
|
||
previous_session: None,
|
||
},
|
||
hotkey_status: Default::default(),
|
||
commands,
|
||
updates: mpsc::channel().0,
|
||
});
|
||
// A listener still loading its model would replay the command late.
|
||
assert!(host.shortcut_route().is_none());
|
||
host.listener.as_mut().unwrap().startup = ListenerStartup::Observed;
|
||
let route = host.shortcut_route().unwrap();
|
||
linux_service::route_shortcut(
|
||
Some(&route),
|
||
crate::linux::input::ShortcutCommand::PasteLast,
|
||
)
|
||
.unwrap();
|
||
assert_eq!(
|
||
received.try_iter().collect::<Vec<_>>(),
|
||
[ListenerCommand::from(
|
||
crate::linux::input::ShortcutCommand::PasteLast
|
||
)]
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn dismiss_clears_operational_and_settings_errors() {
|
||
let mut host = host_for_edit(false);
|
||
host.error = Some("listener failed".into());
|
||
host.settings_error = Some("settings failed".into());
|
||
host.dispatch(DesktopAction::ClearError).unwrap();
|
||
assert!(host.snapshot().operation_error.is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn output_failures_are_visible_and_dismissal_only_acknowledges_that_failure() {
|
||
let mut host = host_for_edit(false);
|
||
host.activity.last_failure = Some((10, "paste helper failed".into()));
|
||
assert_eq!(
|
||
host.snapshot().operation_error.as_deref(),
|
||
Some("paste helper failed")
|
||
);
|
||
host.dispatch(DesktopAction::ClearError).unwrap();
|
||
assert!(host.snapshot().operation_error.is_none());
|
||
host.activity.last_failure = Some((11, "paste helper failed".into()));
|
||
assert_eq!(
|
||
host.snapshot().operation_error.as_deref(),
|
||
Some("paste helper failed")
|
||
);
|
||
host.dispatch(DesktopAction::StartListening).unwrap();
|
||
assert!(host.snapshot().operation_error.is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn start_during_preparation_defers_listening_and_stop_clears_the_request() {
|
||
let settings = AppSettings {
|
||
// An unavailable model prevents a regressed guard from opening audio.
|
||
transcription: TranscriptionSelection {
|
||
model: TranscriptionModelId::AppleSpeech,
|
||
..Default::default()
|
||
},
|
||
..Default::default()
|
||
};
|
||
let mut host = test_host(crate::app_settings::LaunchLoad {
|
||
settings,
|
||
note: None,
|
||
});
|
||
host.transcription_preparation = Some(TranscriptionPreparation {
|
||
canceled: Arc::new(AtomicBool::new(false)),
|
||
model: TranscriptionModelId::default(),
|
||
progress: Arc::new(AtomicU64::new(0)),
|
||
stage: Arc::new(AtomicU8::new(ModelPreparationStage::Downloading as u8)),
|
||
worker: std::thread::spawn(|| Err("fixture preparation".into())),
|
||
automatic: false,
|
||
});
|
||
|
||
host.dispatch(DesktopAction::StartListening).unwrap();
|
||
|
||
assert!(host.listen_when_ready);
|
||
assert_eq!(host.status, ListenerStatus::Disabled);
|
||
assert!(!host.is_running());
|
||
assert!(host.listener.is_none());
|
||
assert!(host.transcription_preparation.is_some());
|
||
|
||
host.dispatch(DesktopAction::StopListening).unwrap();
|
||
|
||
assert!(!host.listen_when_ready);
|
||
assert!(host.transcription_preparation.is_some());
|
||
// Disabled stays disabled at the next launch (#575).
|
||
assert!(!host.settings.enable_on_launch);
|
||
host.dispatch(DesktopAction::StartListening).unwrap();
|
||
assert!(host.settings.enable_on_launch);
|
||
}
|
||
}
|