From 0b55811e5a5dc007662437cb0f4ddc5282f5c5a6 Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 28 Oct 2026 10:13:46 +0300 Subject: [PATCH] voelin-gpui: the global push-to-talk hotkey, started on the engine's runtime docs/ui.md's list for the next slices: the hotkey portal calls tokio::spawn and panics where no tokio runtime is current, and a GPUI foreground task has none, so the task of voelin_platform's HotkeyManager is spawned on the engine's runtime (hotkey.rs, the Slint front end's GlobalPtt repeated as engine.rs repeats HostedEngine: it needs the runtime and the front end's own way back to its state, and the Slint crate cannot be a dependency; tokio's `macros` feature for its select!, Cargo.lock unchanged). It starts at launch with the settings' `ui` key (`global_ptt`, `ptt_key`) when there is an engine and no sample servers, and says how the key stands in the log and in AppState::ptt_status. Its presses and releases cross to GPUI's thread through Later: a press transmits into the session on screen while that has voice, and the release ends the session the press began in, whichever is on screen then; the voice that drops under a held key ends the hold. The window losing the focus does not cut it: the key is meant for use while another window has the focus. A change of the key at run time is the settings slice's (AppState::set_global_ptt is its entry). Co-Authored-By: Claude Sonnet 5.5 --- crates/voelin-gpui/Cargo.toml | 5 +- crates/voelin-gpui/src/app.rs | 217 ++++++++++++++++++++- crates/voelin-gpui/src/hotkey.rs | 160 +++++++++++++++ crates/voelin-gpui/src/lib.rs | 1 + crates/voelin-gpui/src/view/voice_tests.rs | 17 ++ 5 files changed, 394 insertions(+), 6 deletions(-) create mode 100644 crates/voelin-gpui/src/hotkey.rs diff --git a/crates/voelin-gpui/Cargo.toml b/crates/voelin-gpui/Cargo.toml index f7e8518..59779d3 100644 --- a/crates/voelin-gpui/Cargo.toml +++ b/crates/voelin-gpui/Cargo.toml @@ -21,8 +21,9 @@ anyhow = "1.0.104" # GPUI, gpui-component and gpui-kit-assets behind one pinned dependency. gpui-kit = { workspace = true } # The engine's runtime and the channel of its events (a tokio receiver needs no -# reactor, so GPUI's executor can await it). -tokio = { version = "1.53.1", features = ["rt-multi-thread", "sync", "time"] } +# reactor, so GPUI's executor can await it); `macros` for the hotkey task's +# `select!`. +tokio = { version = "1.53.1", features = ["macros", "rt-multi-thread", "sync", "time"] } tracing = "0.1.44" tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } # The TeamSpeak identity a connection is made with (the store hands it out). diff --git a/crates/voelin-gpui/src/app.rs b/crates/voelin-gpui/src/app.rs index 7528c78..e184933 100644 --- a/crates/voelin-gpui/src/app.rs +++ b/crates/voelin-gpui/src/app.rs @@ -52,13 +52,14 @@ use voelin_ui_vm::servers::logic; use voelin_ui_vm::servers::sequence::{self, Backing}; use voelin_ui_vm::settings::{ CLIENT_PLAYBACK, ThemeChoice, TreeStates, UI, UI_FONT_SCALE, UI_IMAGE_PREVIEW_KB, UI_THEME, - UI_TREE, UI_VOICE_COMPACT, UI_WINDOW, WindowState, + UI_TREE, UI_VOICE_COMPACT, UI_WINDOW, UiSettings, WindowState, }; use voelin_ui_vm::social::logic::Social; use voelin_ui_vm::tree::ChannelId; use crate::backend::Backend; use crate::dev::Switches; +use crate::hotkey::GlobalPtt; use crate::meter::Counters; use crate::pictures; use crate::signals::{Area, Signals}; @@ -181,6 +182,15 @@ pub fn appearance(prefs: &Settings, switches: &Switches) -> (Choice, f32) { (choice, switches.font_scale.unwrap_or_else(|| prefs.get(&UI_FONT_SCALE))) } +/// The key the global push-to-talk hotkey is registered with at start: the +/// settings' (`global_ptt`, `ptt_key`), with an engine to send the presses to +/// and not with the sample servers, which send nothing (and whose run must not +/// ask the desktop for a shortcut). +fn hotkey_wanted(settings: &UiSettings, demo_ui: bool, has_engine: bool) -> Option { + let key = settings.ptt_key.trim(); + (settings.global_ptt && !demo_ui && has_engine && !key.is_empty()).then(|| key.to_owned()) +} + /// Where the window's place is kept between ticks. #[derive(Debug, Default)] struct WindowKeeper { @@ -254,6 +264,12 @@ pub struct AppState { /// The voice page shows the smaller stage (`ui.voice_compact`, or the /// development switch that asks for it). voice_compact: bool, + /// The global push-to-talk hotkey's task, once one was wanted. + ptt: Option, + /// How the hotkey stands, as its task last said. + ptt_status: String, + /// The session the hotkey turned transmit on for and has not turned off. + hotkey_held: Option, /// Where the sample servers' pictures were written (`VOELIN_DEMO_UI`), /// removed with the state. demo_dir: Option, @@ -368,6 +384,9 @@ impl AppState { tree_states, tree_restored: HashSet::new(), voice_compact: false, + ptt: None, + ptt_status: String::new(), + hotkey_held: None, demo_dir: None, later: Later(later), #[cfg(test)] @@ -384,6 +403,11 @@ impl AppState { if state.switches.voice { state.transition(cx, |state, cx| logic::show_voice_view(state, cx, true)); } + state.set_global_ptt(hotkey_wanted( + &state.vm.settings, + state.switches.demo_ui, + state.engine.is_some(), + )); state } @@ -527,11 +551,18 @@ impl AppState { /// before a batch of events and is not after it, if it still says it /// transmits. The engine answers with a state without it, which this does /// not answer again. - fn release_lost_transmit(&self, were_connected: &[i64]) { + fn release_lost_transmit(&mut self, were_connected: &[i64]) { for &id in were_connected { let Some(view) = self.vm.sessions.get(&id) else { continue }; - if view.state.voice != VoiceState::Connected && view.state.transmitting { - self.send(Command::SetTransmitting { session: id as u64, on: false }); + if view.state.voice != VoiceState::Connected { + // The hotkey's hold is over with the voice; its release, when it + // comes, has nothing to end. + if self.hotkey_held == Some(id) { + self.hotkey_held = None; + } + if view.state.transmitting { + self.send(Command::SetTransmitting { session: id as u64, on: false }); + } } } } @@ -934,6 +965,63 @@ impl AppState { cx.notify(); } + /// Register the global push-to-talk hotkey with `key` in place of the one + /// registered, or none: the task starts on the engine's runtime with the + /// first key ([`crate::hotkey`]; the settings page of its slice calls this + /// when the choice changes). Nothing without an engine. + pub fn set_global_ptt(&mut self, key: Option) { + if self.ptt.is_none() && key.is_some() { + let Some(engine) = &self.engine else { return }; + let (status, held) = (self.later(), self.later()); + self.ptt = Some(GlobalPtt::start( + engine.runtime(), + move |line| { + status.run(move |app, _| app.ptt_status_changed(line)); + }, + move |on| { + held.run(move |app, cx| app.hotkey_transmit(on, cx)); + }, + )); + } + if let Some(ptt) = &self.ptt { + ptt.set(key); + } + } + + /// How the hotkey stands, as its task last said ("Active: Ctrl+Shift+T + /// (X11)", why it could not be registered); empty until it said. + pub fn ptt_status(&self) -> &str { + &self.ptt_status + } + + /// The hotkey task's word on how the key stands. + fn ptt_status_changed(&mut self, line: String) { + tracing::info!(target: "voelin_gpui::hotkey", "{line}"); + self.ptt_status = line; + } + + /// The global push-to-talk key went down or up. It transmits into the + /// session on screen while that has voice, and the release ends that same + /// session's transmit, whichever is on screen by then (a server chosen + /// while the key is down). A press without voice does nothing. + pub fn hotkey_transmit(&mut self, on: bool, cx: &mut Context) { + if on { + let connected = self.vm.current.filter(|id| { + self.vm + .sessions + .get(id) + .is_some_and(|view| view.state.voice == VoiceState::Connected) + }); + let Some(id) = connected else { return }; + if self.hotkey_held.replace(id) != Some(id) { + self.send(Command::SetTransmitting { session: id as u64, on: true }); + } + } else if let Some(id) = self.hotkey_held.take() { + self.send(Command::SetTransmitting { session: id as u64, on: false }); + } + cx.notify(); + } + /// A link to the voice channel we are in, copied to the clipboard with a /// note in the status line; the reason in the status line without one. pub fn invite(&mut self, cx: &mut Context) -> Option { @@ -1815,6 +1903,127 @@ mod tests { assert!(empty.read_with(cx, |app, _| app.take_sent()).is_empty(), "no session on screen"); } + /// The global push-to-talk key is registered at start with the settings' + /// key when there is an engine to send to, not with the sample servers. + #[test] + fn the_hotkey_is_wanted_with_an_engine_outside_the_sample_servers() { + let settings = |global_ptt, key: &str| UiSettings { + global_ptt, + ptt_key: key.into(), + ..Default::default() + }; + let on = settings(true, " Ctrl+Shift+T "); + assert_eq!(hotkey_wanted(&on, false, true).as_deref(), Some("Ctrl+Shift+T")); + assert_eq!(hotkey_wanted(&on, true, true), None, "the sample servers ask for nothing"); + assert_eq!(hotkey_wanted(&on, false, false), None, "no engine: nowhere to send"); + assert_eq!(hotkey_wanted(&settings(false, "F9"), false, true), None, "switched off"); + assert_eq!(hotkey_wanted(&settings(true, " "), false, true), None, "no key"); + assert_eq!( + hotkey_wanted(&UiSettings::default(), false, true).as_deref(), + Some("Ctrl+Shift+T"), + "the default is on, as in the Slint front end" + ); + } + + /// What the commands sent since the last call say about transmitting: the + /// session and whether it was turned on. + fn transmits(app: &Entity, cx: &mut TestAppContext) -> Vec<(u64, bool)> { + app.read_with(cx, |app, _| app.take_sent()) + .into_iter() + .filter_map(|command| match command { + Command::SetTransmitting { session, on } => Some((session, on)), + _ => None, + }) + .collect() + } + + /// The global key transmits into the session on screen while it has voice, + /// and its release ends that session's transmit, whichever is on screen by + /// then; a press without voice, or a second press, does nothing. + #[gpui::test] + fn the_hotkey_transmits_into_the_session_that_has_voice_and_its_release_ends_it( + cx: &mut TestAppContext, + ) { + let (app, tx, _) = entity_over( + cx, + backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]), + Switches::default(), + ); + let [first, second] = + app.read_with(cx, |app, _| [app.vm.bookmarks[0].id, app.vm.bookmarks[1].id]); + let hotkey = |app: &Entity, cx: &mut TestAppContext, on| { + app.update(cx, |app, cx| app.hotkey_transmit(on, cx)) + }; + hotkey(&app, cx, true); + assert_eq!(transmits(&app, cx), [], "no voice, no transmit"); + hotkey(&app, cx, false); + assert_eq!(transmits(&app, cx), [], "and nothing to release"); + + tx.send(Event::State { + session: first as u64, + state: SessionState { voice: VoiceState::Connected, ..Default::default() }, + }) + .unwrap(); + cx.run_until_parked(); + hotkey(&app, cx, true); + hotkey(&app, cx, true); + assert_eq!(transmits(&app, cx), [(first as u64, true)], "once"); + + // Another server is shown while the key is down: the release still ends + // the transmit of the one it began in. + app.update(cx, |app, cx| app.select_server(second, cx)); + app.read_with(cx, |app, _| assert_eq!(app.vm.current, Some(second))); + hotkey(&app, cx, false); + assert_eq!(transmits(&app, cx), [(first as u64, false)]); + hotkey(&app, cx, false); + assert_eq!(transmits(&app, cx), [], "released once"); + } + + /// The hotkey task runs on the engine's runtime and hands each press and + /// release to GPUI's thread through `Later`. + #[gpui::test] + fn the_hotkey_tasks_thread_reaches_the_entity_through_later(cx: &mut TestAppContext) { + let (app, _, _) = + entity_over(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + let id = app.update(cx, |app, _| { + let id = app.vm.bookmarks[0].id; + app.vm.sessions.entry(id).or_default().state.voice = VoiceState::Connected; + id as u64 + }); + let later = app.read_with(cx, |app, _| app.later()); + let queued = std::thread::spawn(move || later.run(|app, cx| app.hotkey_transmit(true, cx))) + .join() + .unwrap(); + assert!(queued); + cx.run_until_parked(); + assert_eq!(transmits(&app, cx), [(id, true)]); + } + + /// The voice that drops under a held key ends the hold: the session is told + /// once (the release guard), and the key's own release has nothing left to + /// end. + #[gpui::test] + fn voice_that_drops_under_the_hotkey_ends_its_hold(cx: &mut TestAppContext) { + let (app, tx, _) = + entity_over(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + let id = app.read_with(cx, |app, _| app.vm.bookmarks[0].id) as u64; + let state = |voice, transmitting| Event::State { + session: id, + state: SessionState { voice, transmitting, ..Default::default() }, + }; + tx.send(state(VoiceState::Connected, false)).unwrap(); + cx.run_until_parked(); + app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + tx.send(state(VoiceState::Connected, true)).unwrap(); + cx.run_until_parked(); + assert_eq!(transmits(&app, cx), [(id, true)]); + tx.send(state(VoiceState::Disconnected, true)).unwrap(); + cx.run_until_parked(); + assert_eq!(transmits(&app, cx), [(id, false)], "told once"); + app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!(transmits(&app, cx), [], "the release has nothing to end"); + } + /// Showing a server also observes it, invisibly, through the gateway it /// published or its own query login, as the Slint front end does. #[gpui::test] diff --git a/crates/voelin-gpui/src/hotkey.rs b/crates/voelin-gpui/src/hotkey.rs new file mode 100644 index 0000000..89d790b --- /dev/null +++ b/crates/voelin-gpui/src/hotkey.rs @@ -0,0 +1,160 @@ +//! Global push-to-talk: a task owns the [`voelin_platform::HotkeyManager`] (the +//! desktop's portal on Wayland, XInput2 on X11, a hook on Windows) and reports +//! the key's presses and releases, whichever window has the focus. +//! +//! It is the Slint front end's `GlobalPtt` (`crates/voelin-ui/src/hotkey.rs`), +//! repeated here as `engine.rs` repeats `HostedEngine`: the loop needs the +//! engine's runtime and the front end's own way back to its state, and the +//! Slint crate cannot be a dependency (it brings Slint in); both go into one +//! place when the Slint front end is retired. +//! +//! **The task runs on the engine's runtime** ([`GlobalPtt::start`] spawns on +//! it), not from a foreground task of GPUI: the portal's backend calls +//! `tokio::spawn` when it is made (`voelin-platform`, `hotkey/portal.rs`), which +//! panics where no tokio runtime is current, and GPUI's executor has none. + +use tokio::runtime::Handle; +use tokio::sync::mpsc; +use voelin_platform::{BackendKind, Hotkey, HotkeyEvent, HotkeyEvents, HotkeyManager}; + +/// The id of the push-to-talk registration (the portal remembers the user's +/// choice by it). +const PTT_ID: &str = "push-to-talk"; + +/// The handle to the hotkey task. +pub struct GlobalPtt { + tx: mpsc::UnboundedSender>, +} + +impl GlobalPtt { + /// Start the task on `runtime`. `status` gets a line that says how the key + /// stands ("Active: Ctrl+Shift+T (X11)", why it could not be registered), + /// `transmit` the key's state; both are called on the runtime, so they hand + /// over to GPUI's thread ([`crate::app::Later`]). + pub fn start( + runtime: &Handle, + status: impl Fn(String) + Send + 'static, + transmit: impl Fn(bool) + Send + 'static, + ) -> Self { + let (tx, rx) = mpsc::unbounded_channel(); + runtime.spawn(run(rx, status, transmit)); + Self { tx } + } + + /// Register `key` (such as `Ctrl+Shift+T`) in place of the one registered, + /// or nothing. + pub fn set(&self, key: Option) { + let _ = self.tx.send(key); + } +} + +/// The next event of the registration, or never while there is none. +async fn next(events: &mut Option) -> Option { + match events { + Some(events) => events.recv().await, + None => std::future::pending().await, + } +} + +/// The task: a key to register (or none) arrives on `rx`, the registered key's +/// events are reported through `transmit`, and `status` says what happened. +async fn run( + mut rx: mpsc::UnboundedReceiver>, + status: impl Fn(String), + transmit: impl Fn(bool), +) { + let mut manager: Option = None; + let mut events: Option = None; + loop { + tokio::select! { + key = rx.recv() => { + let Some(key) = key else { break }; + events = None; + // Whatever was held no longer counts. + transmit(false); + if let Some(m) = &mut manager { + let _ = m.unregister(PTT_ID).await; + } + let Some(key) = key else { + status("Off.".into()); + continue; + }; + let hotkey: Hotkey = match key.parse() { + Ok(h) => h, + Err(e) => { + status(format!("{e}")); + continue; + } + }; + if manager.is_none() { + match HotkeyManager::new().await { + Ok(m) => manager = Some(m), + Err(e) => { + status(format!("Global hotkeys are not available: {e}")); + continue; + } + } + } + let Some(m) = &mut manager else { continue }; + match m.register(PTT_ID, "Push to talk", hotkey).await { + Ok(registered) => { + events = Some(registered); + status(match m.backend() { + BackendKind::Portal => format!( + "Registered with the desktop: {}", + m.trigger_description(PTT_ID).unwrap_or(key) + ), + BackendKind::X11 => format!("Active: {hotkey} (X11)"), + BackendKind::WindowsHook => format!("Active: {hotkey}"), + }); + } + Err(e) => status(format!("Could not register {key}: {e}")), + } + } + event = next(&mut events) => match event { + Some(HotkeyEvent::Pressed) => transmit(true), + Some(HotkeyEvent::Released) => transmit(false), + None => { + events = None; + status("The hotkey was removed by the desktop.".into()); + } + }, + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::{Arc, Mutex}; + + use super::*; + + /// A key that is not one is said so and registers nothing, and the held + /// state is let go first; no display or desktop is needed to say it. + #[test] + fn a_key_that_cannot_be_parsed_is_reported_and_lets_go_of_the_hold() { + let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap(); + let log = Arc::new(Mutex::new(Vec::::new())); + let (said, held) = (log.clone(), log.clone()); + let ptt = GlobalPtt::start( + runtime.handle(), + move |line| said.lock().unwrap().push(format!("status: {line}")), + move |on| held.lock().unwrap().push(format!("transmit: {on}")), + ); + ptt.set(Some("Ctrl+Hyper+Banana".into())); + ptt.set(None); + // The task answers in order: the last answer says the end of the list. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while log.lock().unwrap().len() < 4 { + assert!(std::time::Instant::now() < deadline, "{:?}", log.lock().unwrap()); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let log = log.lock().unwrap().clone(); + assert_eq!(log[0], "transmit: false", "{log:?}"); + assert!(log[1].starts_with("status: "), "the parse error: {log:?}"); + assert_eq!(log[2], "transmit: false", "{log:?}"); + assert_eq!(log[3], "status: Off.", "{log:?}"); + drop(ptt); + runtime.shutdown_timeout(std::time::Duration::from_secs(2)); + } +} diff --git a/crates/voelin-gpui/src/lib.rs b/crates/voelin-gpui/src/lib.rs index 438db8d..de04d7b 100644 --- a/crates/voelin-gpui/src/lib.rs +++ b/crates/voelin-gpui/src/lib.rs @@ -11,6 +11,7 @@ pub mod backend; pub mod dev; pub mod engine; pub mod fonts; +pub mod hotkey; pub mod meter; pub mod pictures; pub mod shell; diff --git a/crates/voelin-gpui/src/view/voice_tests.rs b/crates/voelin-gpui/src/view/voice_tests.rs index b13eaf5..5df3794 100644 --- a/crates/voelin-gpui/src/view/voice_tests.rs +++ b/crates/voelin-gpui/src/view/voice_tests.rs @@ -480,3 +480,20 @@ fn a_window_that_holds_nothing_tells_the_session_nothing_when_it_loses_the_focus cx.update(|window, _| assert!(!window.is_window_active(), "the window lost the focus")); assert_eq!(transmits(&shell, cx), NOTHING); } + +/// The global hotkey is for use while another window has the focus: the window +/// losing it does not cut a hold the key began, and the key's release ends it. +#[gpui::test] +fn the_global_hotkey_is_not_cut_by_the_window_losing_the_focus(cx: &mut TestAppContext) { + let (shell, cx) = tall(cx, Switches::default()); + cx.update(|window, _| window.activate_window()); + cx.run_until_parked(); + transmits(&shell, cx); + shell.app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + assert_eq!(transmits(&shell, cx), [true]); + cx.deactivate_window(); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING, "the window's focus is not the key's"); + shell.app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!(transmits(&shell, cx), [false], "the key's release ends it"); +}