//! 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 std::future::Future; 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); } } /// A stream of press and release events for one registered hotkey (`None` once /// the desktop removes it). trait EventStream: Send { fn recv(&mut self) -> impl Future> + Send; } impl EventStream for HotkeyEvents { fn recv(&mut self) -> impl Future> + Send { HotkeyEvents::recv(self) } } /// Registers and unregisters the global push-to-talk hotkey with the platform /// (or a test double). trait Registrar: Send { type Events: EventStream; fn register( &mut self, key: String, hotkey: Hotkey, ) -> impl Future> + Send; fn unregister(&mut self) -> impl Future + Send; } /// The real platform hotkey manager, opened lazily on the first registration. struct PlatformRegistrar { manager: Option, } impl Registrar for PlatformRegistrar { type Events = HotkeyEvents; async fn register( &mut self, key: String, hotkey: Hotkey, ) -> Result<(Self::Events, String), String> { if self.manager.is_none() { match HotkeyManager::new().await { Ok(m) => self.manager = Some(m), Err(e) => return Err(format!("Global hotkeys are not available: {e}")), } } let Some(m) = &mut self.manager else { return Err("Global hotkeys are not available.".into()); }; match m.register(PTT_ID, "Push to talk", hotkey).await { Ok(registered) => { let line = 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}"), }; Ok((registered, line)) } Err(e) => Err(format!("Could not register {key}: {e}")), } } async fn unregister(&mut self) { if let Some(m) = &mut self.manager { let _ = m.unregister(PTT_ID).await; } } } /// The next event of the registration, or never while there is none. async fn next_event(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( rx: mpsc::UnboundedReceiver>, status: impl Fn(String), transmit: impl Fn(bool), ) { run_loop(rx, PlatformRegistrar { manager: None }, status, transmit).await; } /// The event loop of [`run`], parameterised over `registrar` so the /// fail-closed release paths are tested without a portal or display. async fn run_loop( mut rx: mpsc::UnboundedReceiver>, mut registrar: R, status: impl Fn(String), transmit: impl Fn(bool), ) { let mut events: Option = None; loop { tokio::select! { key = rx.recv() => { let Some(key) = key else { // Fail closed on task exit: drop any hold that was still down. transmit(false); break; }; events = None; // Whatever was held no longer counts. transmit(false); registrar.unregister().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; } }; match registrar.register(key, hotkey).await { Ok((registered, line)) => { events = Some(registered); status(line); } Err(line) => status(line), } } event = next_event(&mut events) => match event { Some(HotkeyEvent::Pressed) => transmit(true), Some(HotkeyEvent::Released) => transmit(false), None => { events = None; // Fail closed if the desktop removes the shortcut mid-hold. transmit(false); status("The hotkey was removed by the desktop.".into()); } }, } } } #[cfg(test)] mod tests { use std::sync::{Arc, Mutex}; use std::time::Duration; use super::*; /// A channel-backed event stream for testing [`run_loop`] without a display. struct FakeEvents(mpsc::UnboundedReceiver); impl EventStream for FakeEvents { async fn recv(&mut self) -> Option { self.0.recv().await } } /// A registrar that hands out a prepared [`FakeEvents`] stream once. struct FakeRegistrar { stream: Option, } impl Registrar for FakeRegistrar { type Events = FakeEvents; async fn register( &mut self, _key: String, hotkey: Hotkey, ) -> Result<(Self::Events, String), String> { let events = self.stream.take().ok_or_else(|| "no fake stream left".to_owned())?; Ok((events, format!("Active: {hotkey} (test)"))) } async fn unregister(&mut self) {} } /// Next recorded message from the task, bounded only against a hang. async fn recv_log(rx: &mut mpsc::UnboundedReceiver) -> String { tokio::time::timeout(Duration::from_secs(30), rx.recv()) .await .expect("hotkey loop timed out") .expect("log channel closed unexpectedly") } /// 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() + Duration::from_secs(30); while log.lock().unwrap().len() < 4 { assert!(std::time::Instant::now() < deadline, "{:?}", log.lock().unwrap()); std::thread::sleep(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(Duration::from_secs(2)); } /// When the desktop removes the registered hotkey while it is pressed, the /// loop releases transmit before reporting the removal. #[test] fn desktop_removal_mid_hold_releases_transmit_before_reporting_status() { let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); runtime.block_on(async { let (tx_key, rx_key) = mpsc::unbounded_channel(); let (tx_evt, rx_evt) = mpsc::unbounded_channel(); let (tx_log, mut rx_log) = mpsc::unbounded_channel(); let (said, held) = (tx_log.clone(), tx_log); let registrar = FakeRegistrar { stream: Some(FakeEvents(rx_evt)) }; let task = tokio::spawn(run_loop( rx_key, registrar, move |line| { let _ = said.send(format!("status: {line}")); }, move |on| { let _ = held.send(format!("transmit: {on}")); }, )); tx_key.send(Some("Ctrl+Shift+T".into())).unwrap(); assert_eq!(recv_log(&mut rx_log).await, "transmit: false"); assert!(recv_log(&mut rx_log).await.starts_with("status: Active: ")); tx_evt.send(HotkeyEvent::Pressed).unwrap(); assert_eq!(recv_log(&mut rx_log).await, "transmit: true"); // Desktop removes the shortcut while held. drop(tx_evt); assert_eq!( recv_log(&mut rx_log).await, "transmit: false", "transmit must fail closed before reporting removal" ); assert_eq!( recv_log(&mut rx_log).await, "status: The hotkey was removed by the desktop." ); drop(tx_key); tokio::time::timeout(Duration::from_secs(30), task) .await .expect("task exit timed out") .unwrap(); }); } /// When the command channel closes (task exit) while the hotkey is pressed, /// the loop releases transmit before exiting. #[test] fn closing_command_channel_mid_hold_releases_transmit_before_exiting() { let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); runtime.block_on(async { let (tx_key, rx_key) = mpsc::unbounded_channel(); let (tx_evt, rx_evt) = mpsc::unbounded_channel(); let (tx_log, mut rx_log) = mpsc::unbounded_channel(); let (said, held) = (tx_log.clone(), tx_log); let registrar = FakeRegistrar { stream: Some(FakeEvents(rx_evt)) }; let task = tokio::spawn(run_loop( rx_key, registrar, move |line| { let _ = said.send(format!("status: {line}")); }, move |on| { let _ = held.send(format!("transmit: {on}")); }, )); tx_key.send(Some("Ctrl+Shift+T".into())).unwrap(); assert_eq!(recv_log(&mut rx_log).await, "transmit: false"); assert!(recv_log(&mut rx_log).await.starts_with("status: Active: ")); tx_evt.send(HotkeyEvent::Pressed).unwrap(); assert_eq!(recv_log(&mut rx_log).await, "transmit: true"); // Keep the event stream open while the handle drops (task exit). drop(tx_key); tokio::time::timeout(Duration::from_secs(30), task) .await .expect("task exit timed out") .unwrap(); assert_eq!( rx_log.try_recv().ok().as_deref(), Some("transmit: false"), "closing rx mid-hold must release transmit before breaking" ); drop(tx_evt); }); } }