hex/src/linux/rune_hud.rs
Dax 7a2c78ace2
feat(labs): model switch shortcut (#2679)
One key swaps the dictation model and language with a saved other one, and back, installed only, through the same save and reload path the speech-model picker uses. Requested in #2654.
2026-11-24 12:57:57 -05:00

234 lines
9.1 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! The Linux recording HUD: the shared Rune HUD (`rune_hud`), the capsule or
//! Dot scope drawn on the GPU, as an overlay in the Hex process.
//! Rune makes it a layer-shell surface on Wayland (overlay layer, no
//! keyboard, empty input region) and an override-redirect window with an
//! empty input shape on X11, so it never takes focus or a click. On a
//! Wayland compositor without layer-shell (GNOME), Rune opens only the HUD
//! as that X11 window on XWayland; the rest of Hex stays on Wayland.
//!
//! It only observes: the listener reports its capture, meter, and pending
//! output through `LinuxIndicator`, which never waits on the HUD and turns
//! those reports into the HUD's events. The listener can start before the
//! window's app exists; reports before `install` are dropped.
use std::collections::VecDeque;
use std::sync::{Mutex, OnceLock};
use rune::Availability;
use crate::app_settings::IndicatorPosition;
use crate::rune_hud::{HudEvent, HudSender};
/// The newest listener's generation: an older listener's reports stop counting.
static GENERATION: Mutex<u64> = Mutex::new(0);
/// Where the newest listener wants the HUD, for an `install` after it starts.
static POSITION: Mutex<IndicatorPosition> = Mutex::new(IndicatorPosition::Top);
static HUD: OnceLock<HudSender> = OnceLock::new();
/// A listener's handle on the HUD; dropping it hides what it reported.
pub(crate) struct LinuxIndicator {
generation: Option<u64>,
recording: bool,
/// Submitted dictations still being transcribed or pasted, oldest first.
jobs: VecDeque<u64>,
next_job: u64,
}
impl LinuxIndicator {
pub(crate) fn new(position: IndicatorPosition) -> Self {
*POSITION.lock().unwrap_or_else(|error| error.into_inner()) = position;
if let Some(sender) = HUD.get() {
sender.set_position(position);
}
let generation = (position != IndicatorPosition::Hidden).then(|| {
let mut current = GENERATION.lock().unwrap_or_else(|error| error.into_inner());
*current += 1;
*current
});
let indicator = Self {
generation,
recording: false,
jobs: VecDeque::new(),
next_job: 0,
};
indicator.send(HudEvent::Reset);
indicator
}
fn sender(&self) -> Option<&'static HudSender> {
let generation = self.generation?;
let current = *GENERATION.lock().unwrap_or_else(|error| error.into_inner());
(generation == current).then(|| HUD.get()).flatten()
}
fn send(&self, event: HudEvent) {
if let Some(sender) = self.sender() {
sender.send(event);
}
}
/// The listener's state after each turn: whether it records, and how
/// many dictations it submitted that have not finished.
pub(crate) fn update(&mut self, recording: bool, pending: usize) {
if recording && !self.recording {
self.send(HudEvent::Started);
}
let submitted = pending > self.jobs.len();
while pending > self.jobs.len() {
self.next_job += 1;
self.jobs.push_back(self.next_job);
self.send(HudEvent::Submitted {
job_id: self.next_job,
});
}
if !recording && self.recording && !submitted {
self.send(HudEvent::Cancelled);
}
// Dictations that ended without `finished` (the listener stopping).
while pending < self.jobs.len() {
if let Some(job_id) = self.jobs.pop_front() {
self.send(HudEvent::JobCancelled { job_id });
}
}
self.recording = recording;
}
/// The oldest submitted dictation finished: pasted, or failed with why.
pub(crate) fn finished(&mut self, failure: Option<&str>) {
if let Some(job_id) = self.jobs.pop_front() {
self.send(if let Some(message) = failure {
HudEvent::JobFailed {
job_id,
message: Some(message.to_owned()),
}
} else {
HudEvent::JobCompleted { job_id }
});
}
}
/// Shows `message` as the HUD's failure notice (Labs › Failure
/// notices) for something that failed outside a dictation job, such as a
/// model switch with no installed model. No sound plays.
pub(crate) fn failed(&mut self, message: String) {
self.send(HudEvent::Failed {
message: Some(message),
});
}
/// The oldest submitted dictation was deliberately discarded: close it
/// as cancelled, as [`Self::finished`] closes a completed one.
pub(crate) fn discarded(&mut self) {
if let Some(job_id) = self.jobs.pop_front() {
self.send(HudEvent::JobCancelled { job_id });
}
}
/// Captured audio while recording, for the level the HUD shows.
pub(crate) fn meter(&self, samples: &[f32]) {
if let Some(sender) = self.sender() {
sender.meter(samples);
}
}
}
impl Drop for LinuxIndicator {
fn drop(&mut self) {
self.send(HudEvent::Reset);
}
}
/// Adds the HUD overlay to the window's app.
pub(crate) fn install<S: 'static>(app: &mut rune::App<S>) {
let sender = crate::rune_hud::install(app);
sender.set_position(*POSITION.lock().unwrap_or_else(|error| error.into_inner()));
let _ = HUD.set(sender);
}
/// Why the HUD can't show, logged once per reason: Hex reaches no display at
/// all (a service started without the session's environment, #756), the
/// Wayland compositor offers no layer-shell (GNOME's Mutter) and there is no
/// XWayland for Rune to show it on instead, or Rune could not open the overlay.
pub(crate) fn limitation() -> Option<String> {
static DISPLAY: OnceLock<Option<Limitation>> = OnceLock::new();
static LOGGED: Mutex<Option<String>> = Mutex::new(None);
let refused = HUD
.get()
.filter(|hud| hud.availability() == Availability::Unavailable)
.map(|hud| Limitation::Refused(hud.failure()));
let limitation = match DISPLAY.get_or_init(display_limitation) {
Some(Limitation::NoDisplay) => Limitation::NoDisplay,
display => refused.or_else(|| display.clone())?,
};
let (log, user) = limitation.describe();
let mut logged = LOGGED.lock().unwrap_or_else(|error| error.into_inner());
if logged.as_deref() != Some(log.as_str()) {
tracing::warn!("HUD unavailable: {log}; dictation still works");
*logged = Some(log);
}
Some(user)
}
#[derive(Clone, Debug, PartialEq)]
enum Limitation {
/// Neither `WAYLAND_DISPLAY` reaches a compositor nor is `DISPLAY` set.
NoDisplay,
/// The compositor has no layer-shell, and there is no XWayland.
NoLayerShell,
/// Rune could not open the overlay, with its reason when it gives one.
Refused(Option<String>),
}
impl Limitation {
/// The log line and the text Settings shows.
fn describe(&self) -> (String, String) {
match self {
Self::NoDisplay => (
"Hex has no Wayland or X11 display (no WAYLAND_DISPLAY or DISPLAY in its environment)".into(),
"Recording HUD unavailable: Hex can't reach your display. If Hex runs as a systemd service, import the session's environment (on Hyprland: exec-once = dbus-update-activation-environment --systemd WAYLAND_DISPLAY XDG_CURRENT_DESKTOP). Dictation still works.".into(),
),
Self::NoLayerShell => (
"compositor has no layer-shell and XWayland is not running".into(),
"Recording HUD unavailable: this compositor does not support Wayland layer-shell and XWayland is not running. Dictation still works.".into(),
),
Self::Refused(failure) => {
let reason = failure.as_deref().unwrap_or("no reason given");
(
format!("Rune could not open the overlay ({reason})"),
format!("Recording HUD unavailable: the overlay could not open ({reason}). Dictation still works."),
)
}
}
}
}
/// What the display alone says about the HUD, checked once.
fn display_limitation() -> Option<Limitation> {
let wayland = crate::linux::session::LinuxSession::detect().is_wayland();
let reachable = wayland && wayland_reachable();
if !reachable && !xwayland() {
return Some(Limitation::NoDisplay);
}
if reachable && !crate::linux::paste::wayland_offers(LAYER_SHELL) {
if xwayland() {
tracing::info!("HUD shows on XWayland: compositor has no layer-shell");
return None;
}
return Some(Limitation::NoLayerShell);
}
None
}
pub(crate) const LAYER_SHELL: &str = "zwlr_layer_shell_v1";
/// Whether a Wayland connection opens at all, so a missing display is never
/// read as a compositor without layer-shell.
fn wayland_reachable() -> bool {
wayland_client::Connection::connect_to_env().is_ok()
}
/// Whether the session runs XWayland, which Rune shows the HUD on when the
/// compositor has no layer-shell.
fn xwayland() -> bool {
std::env::var_os("DISPLAY").is_some_and(|display| !display.is_empty())
}