From 3bccedc83c3f02090c1b83ad7b46653149acaff9 Mon Sep 17 00:00:00 2001 From: Devan <68340659+DevanMetz@users.noreply.github.com> Date: Tue, 27 Oct 2026 23:04:07 -0500 Subject: [PATCH] Add native Wayland dictation typing --- Cargo.lock | 2 + Cargo.toml | 3 + PARITY.md | 2 +- src/dictation.rs | 6 +- src/gui/mod.rs | 2 + src/main.rs | 2 + src/wayland_type.rs | 314 ++++++++++++++++++++++++++++++++++++++++++++ src/x11_type.rs | 4 +- 8 files changed, 331 insertions(+), 4 deletions(-) create mode 100644 src/wayland_type.rs diff --git a/Cargo.lock b/Cargo.lock index f261020..a3b5280 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3829,6 +3829,8 @@ dependencies = [ "tract-pulse", "tray-icon", "ureq", + "wayland-client", + "wayland-protocols-misc", "windows", "windows-core", "winreg", diff --git a/Cargo.toml b/Cargo.toml index 8d17319..9f11939 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -62,6 +62,9 @@ audio_thread_priority = { version = "0.35", default-features = false, features = # X11 dictation and monitor placement share this connection. x11rb = { version = "0.13.2", default-features = false, features = ["xtest", "randr", "resource_manager"] } xkeysym = "0.2.1" +# Reuse the Wayland client and protocol bindings already linked by winit. +wayland-client = "0.31.15" +wayland-protocols-misc = { version = "0.3.12", features = ["client"] } # Enable window surfaces on both Wayland and X11. glutin = { version = "=0.32.3", default-features = false, features = ["egl", "glx", "wayland", "x11"] } glutin-winit = { version = "=0.5.0", default-features = false, features = ["egl", "glx", "wayland", "x11"] } diff --git a/PARITY.md b/PARITY.md index c61085f..4a939b1 100644 --- a/PARITY.md +++ b/PARITY.md @@ -23,7 +23,7 @@ Status of each Windows user-facing feature on Linux in this tree: `working`, `pa | Global hotkeys on X11 (mute, bypass, stop clips, dictation, pads) | working | `src/hotkeys.rs` | | Global hotkeys on Wayland | working | `src/portal_shortcuts.rs`, `src/hotkeys.rs` — the desktop global-shortcuts portal when it is installed (one confirmation). Without it, the X11 grab is used and only X11 windows receive the keys | | Dictation transcription on this computer, including model download | working | `src/dictation.rs` | -| Dictation typed into the focused app | X11 | `src/x11_type.rs` — on Wayland the transcript is shown and can be copied | +| Dictation typed into the focused app | working | `src/x11_type.rs`, `src/wayland_type.rs` — X11 XTEST; Wayland RemoteDesktop keyboard portal (saved restore token when supported), then the wlroots virtual keyboard protocol (up to 247 distinct characters per phrase). OpenMic focus blocks Wayland typing; unavailable or denied backends leave the transcript to copy | | Notification area, close-to-tray, and the tray menu | working | `src/tray.rs`, `src/gui/settings_tab.rs` — requires a StatusNotifier host; closing quits if the tray cannot start | | A second launch shows the running window | working | `src/instance.rs` | | Start on login | working | `src/config.rs` — respects disabled XDG autostart entries | diff --git a/src/dictation.rs b/src/dictation.rs index e9d836d..e3ae892 100644 --- a/src/dictation.rs +++ b/src/dictation.rs @@ -1097,7 +1097,11 @@ fn type_text(text: &str, cancel: &AtomicBool) -> Result<()> { #[cfg(target_os = "linux")] fn type_text(text: &str, cancel: &AtomicBool) -> Result<()> { - crate::x11_type::type_text(text, cancel) + if crate::wayland_type::is_wayland() { + crate::wayland_type::type_text(text, cancel) + } else { + crate::x11_type::type_text(text, cancel) + } } #[cfg(not(any(windows, target_os = "linux")))] diff --git a/src/gui/mod.rs b/src/gui/mod.rs index e040a80..e5b94be 100644 --- a/src/gui/mod.rs +++ b/src/gui/mod.rs @@ -1598,6 +1598,8 @@ impl eframe::App for App { /// Runs before every frame, and on its own while the window is hidden. fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { + #[cfg(target_os = "linux")] + crate::wayland_type::observe_context(ctx); self.tick(ctx); if self.quitting { return; diff --git a/src/main.rs b/src/main.rs index b1f6938..650b6c8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -27,6 +27,8 @@ mod tray; mod update; mod virtual_mic; mod viz; +#[cfg(target_os = "linux")] +mod wayland_type; mod widgets; #[cfg(target_os = "linux")] mod x11_above; diff --git a/src/wayland_type.rs b/src/wayland_type.rs new file mode 100644 index 0000000..12f368c --- /dev/null +++ b/src/wayland_type.rs @@ -0,0 +1,314 @@ +//! Native Wayland dictation. Only backend setup may fall through: retrying a +//! phrase after an injection failure would duplicate already inserted text. +use anyhow::{Context, Result, bail}; +use ashpd::desktop::{ + PersistMode, Session, + remote_desktop::{DeviceType, KeyState, RemoteDesktop}, +}; +use std::io::{Seek, Write}; +use std::os::fd::AsFd; +use std::sync::{ + OnceLock, + atomic::{AtomicBool, Ordering}, +}; +use std::time::{Duration, Instant}; +use wayland_client::{ + Connection, Dispatch, QueueHandle, delegate_noop, + globals::{GlobalListContents, registry_queue_init}, + protocol::{wl_registry, wl_seat}, +}; +use wayland_protocols_misc::zwp_virtual_keyboard_v1::client::{ + zwp_virtual_keyboard_manager_v1::ZwpVirtualKeyboardManagerV1, + zwp_virtual_keyboard_v1::ZwpVirtualKeyboardV1, +}; + +const KEY_INTERVAL: Duration = Duration::from_millis(12); + +type PortalKeyboard = ( + RemoteDesktop<'static>, + Session<'static, RemoteDesktop<'static>>, +); +// Keep the grant alive even on older portals without persistent restore tokens. +static PORTAL: futures_util::lock::Mutex> = + futures_util::lock::Mutex::new(None); +static CONTEXT: OnceLock = OnceLock::new(); + +pub(crate) fn observe_context(ctx: &eframe::egui::Context) { + CONTEXT.get_or_init(|| ctx.clone()); +} + +pub(crate) fn is_wayland() -> bool { + ["WAYLAND_DISPLAY", "WAYLAND_SOCKET"] + .iter() + .any(|name| std::env::var_os(name).is_some_and(|v| !v.is_empty())) + || std::env::var("XDG_SESSION_TYPE").is_ok_and(|v| v.eq_ignore_ascii_case("wayland")) +} + +fn safe_to_type(cancel: &AtomicBool) -> Result<()> { + if cancel.load(Ordering::Relaxed) { + bail!("Transcription cancelled"); + } + let ctx = CONTEXT.get().context("OpenMic focus is unknown")?; + if openmic_focused(ctx) { + bail!("Focus another app to type dictation"); + } + Ok(()) +} + +fn openmic_focused(ctx: &eframe::egui::Context) -> bool { + ctx.input(|i| i.focused || i.raw.viewports.values().any(|v| v.focused == Some(true))) +} + +fn keysyms(text: &str) -> Result> { + text.chars() + .map(|ch| { + let ch = if matches!(ch, '\r' | '\n') { ' ' } else { ch }; + if ch.is_control() { + bail!("can't type control character {ch:?}"); + } + let sym = xkeysym::Keysym::from_char(ch); + if sym == xkeysym::Keysym::NoSymbol { + bail!("can't type {ch:?}"); + } + Ok(sym.raw()) + }) + .collect() +} + +pub(crate) fn type_text(text: &str, cancel: &AtomicBool) -> Result<()> { + let symbols = keysyms(text)?; + if symbols.is_empty() { + return Ok(()); + } + safe_to_type(cancel)?; + pollster::block_on(async { + let mut cached = PORTAL.lock().await; + if cached.is_none() { + match portal_session().await { + Ok(session) => *cached = Some(session), + Err(err) => { + crate::logfile::warn(format_args!( + "Wayland keyboard portal unavailable: {err}" + )); + return virtual_keyboard(&symbols, cancel); + } + } + } + let (portal, session) = cached.as_ref().expect("portal session was established"); + let result = async { + // Approval can change focus. Recheck after setup and before every key. + for sym in symbols { + safe_to_type(cancel)?; + let pressed = portal + .notify_keyboard_keysym(session, sym as i32, KeyState::Pressed) + .await; + // Even a failed D-Bus reply can follow a delivered press. + let released = portal + .notify_keyboard_keysym(session, sym as i32, KeyState::Released) + .await; + if released.is_err() { + let _ = portal + .notify_keyboard_keysym(session, sym as i32, KeyState::Released) + .await; + } + pressed?; + released?; + std::thread::sleep(KEY_INTERVAL); + } + Ok(()) + } + .await; + if result.is_err() { + let _ = session.close().await; + *cached = None; + } + result + }) +} +async fn portal_session() -> Result { + let portal = RemoteDesktop::new().await?; + let session = portal.create_session().await?; + let result = async { + let path = crate::config::settings_path().with_file_name("dictation-remote-desktop-token"); + let token = std::fs::read_to_string(&path).ok(); + portal + .select_devices( + &session, + DeviceType::Keyboard.into(), + token.as_deref(), + PersistMode::ExplicitlyRevoked, + ) + .await? + .response()?; + let devices = portal.start(&session, None).await?.response()?; + if !devices.devices().contains(DeviceType::Keyboard) { + bail!("keyboard access was not granted"); + } + if let Some(token) = devices.restore_token() + && let Err(err) = save_token(&path, token) + { + crate::logfile::warn(format_args!( + "could not save the Wayland keyboard grant: {err}" + )); + } + Ok(()) + } + .await; + if let Err(err) = result { + let _ = session.close().await; + return Err(err); + } + Ok((portal, session)) +} + +fn save_token(path: &std::path::Path, token: &str) -> Result<()> { + // Atomic replacement also gives the token private permissions on Unix. + let parent = path.parent().context("token directory")?; + std::fs::create_dir_all(parent)?; + let mut file = tempfile::NamedTempFile::new_in(parent)?; + file.write_all(token.as_bytes())?; + file.persist(path)?; + Ok(()) +} + +struct State; +impl Dispatch for State { + fn event( + _: &mut Self, + _: &wl_registry::WlRegistry, + _: wl_registry::Event, + _: &GlobalListContents, + _: &Connection, + _: &QueueHandle, + ) { + } +} +delegate_noop!(State: ignore wl_seat::WlSeat); +delegate_noop!(State: ignore ZwpVirtualKeyboardManagerV1); +delegate_noop!(State: ignore ZwpVirtualKeyboardV1); + +fn virtual_keyboard(symbols: &[u32], cancel: &AtomicBool) -> Result<()> { + let conn = Connection::connect_to_env()?; + let (globals, mut queue) = registry_queue_init::(&conn)?; + let qh = queue.handle(); + let manager: ZwpVirtualKeyboardManagerV1 = globals + .bind(&qh, 1..=1, ()) + .context("Wayland typing unavailable; copy the transcript instead")?; + let seat: wl_seat::WlSeat = globals.bind(&qh, 1..=1, ())?; + let keyboard = manager.create_virtual_keyboard(&seat, &qh, ()); + // One immutable keymap per phrase avoids racing keymap replacement with + // application key processing. Evdev codes 1..=247 map to XKB codes 9..=255. + let unique: std::collections::BTreeSet<_> = symbols.iter().copied().collect(); + if unique.len() > 247 { + bail!("too many distinct characters for the virtual keyboard"); + } + let codes: std::collections::BTreeMap<_, _> = unique + .into_iter() + .enumerate() + .map(|(i, sym)| (sym, i as u32 + 1)) + .collect(); + let mut names = String::new(); + let mut bindings = String::new(); + for (sym, code) in &codes { + names.push_str(&format!(" = {};", code + 8)); + bindings.push_str(&format!("key {{ [ 0x{sym:x} ] }};")); + } + let map = format!( + "xkb_keymap {{ xkb_keycodes {{ minimum = 8; maximum = 255; {names} }}; xkb_types {{ type \"ONE_LEVEL\" {{ modifiers = None; map[None] = Level1; level_name[Level1] = \"Any\"; }}; }}; xkb_compatibility {{ }}; xkb_symbols {{ {bindings} }}; }};\0" + ); + let mut file = tempfile::tempfile()?; + file.write_all(map.as_bytes())?; + file.rewind()?; + keyboard.keymap(1, file.as_fd(), u32::try_from(map.len())?); + keyboard.modifiers(0, 0, 0, 0); + queue.roundtrip(&mut State)?; + let started = Instant::now(); + let result = (|| { + for sym in symbols { + safe_to_type(cancel)?; + let time = started.elapsed().as_millis() as u32; + keyboard.key(time, codes[sym], 1); + keyboard.key(time, codes[sym], 0); + conn.flush()?; + std::thread::sleep(KEY_INTERVAL); + } + Ok(()) + })(); + keyboard.destroy(); + let _ = conn.flush(); + result +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn restore_token_replacement_stays_private() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir_in(".").unwrap(); + let path = dir.path().join("config/remote-desktop-token"); + save_token(&path, "first").unwrap(); + save_token(&path, "replacement").unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "replacement"); + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o077, + 0 + ); + } + + #[test] + fn focus_guard_includes_secondary_windows() { + use eframe::egui::{Context, RawInput, ViewportId, ViewportInfo}; + let ctx = Context::default(); + ctx.begin_pass(RawInput::default()); + assert!(openmic_focused(&ctx)); + let _ = ctx.end_pass(); + let mut input = RawInput { + focused: false, + ..Default::default() + }; + input.viewports.get_mut(&ViewportId::ROOT).unwrap().focused = Some(false); + ctx.begin_pass(input.clone()); + assert!(!openmic_focused(&ctx)); + let _ = ctx.end_pass(); + input.viewports.insert( + ViewportId::from_hash_of("strip"), + ViewportInfo { + focused: Some(true), + ..Default::default() + }, + ); + ctx.begin_pass(input); + assert!(openmic_focused(&ctx)); + let _ = ctx.end_pass(); + } + + #[test] + fn cancelled_and_empty_text_need_no_desktop() { + type_text("", &AtomicBool::new(false)).unwrap(); + assert!( + type_text("hello", &AtomicBool::new(true)) + .unwrap_err() + .to_string() + .contains("cancelled") + ); + } + + #[test] + fn unicode_keysyms_round_trip() { + let text = "Hello, café Ελληνικά 中文 🎵"; + let back: String = keysyms(text) + .unwrap() + .into_iter() + .map(|s| xkeysym::Keysym::new(s).key_char().unwrap()) + .collect(); + assert_eq!(back, text); + assert_eq!(keysyms("🎵").unwrap(), [0x0101f3b5]); + } + #[test] + fn normalize_and_validate_before_typing() { + assert_eq!(keysyms("a\r\nb").unwrap(), keysyms("a b").unwrap()); + assert!(keysyms("\t").is_err()); + assert!(keysyms("\u{fdd0}").is_err()); + assert!(keysyms("").unwrap().is_empty()); + } +} diff --git a/src/x11_type.rs b/src/x11_type.rs index f9e3d92..9b90a0d 100644 --- a/src/x11_type.rs +++ b/src/x11_type.rs @@ -3,8 +3,8 @@ //! Each character is bound to an unused keycode and sent with the XTEST //! extension, then that keycode is cleared. The keysym is the character //! itself, so the active layout and Caps Lock do not change what is typed. -//! Wayland clients never receive XTEST events, so those sessions keep the -//! transcript for copying. +//! Wayland clients never receive XTEST events; `wayland_type` handles those +//! sessions with native keyboard backends. use std::sync::atomic::{AtomicBool, Ordering}; use std::thread;