diff --git a/crates/voelin-gpui/src/hotkey.rs b/crates/voelin-gpui/src/hotkey.rs index 89d790b..32652f9 100644 --- a/crates/voelin-gpui/src/hotkey.rs +++ b/crates/voelin-gpui/src/hotkey.rs @@ -13,6 +13,8 @@ //! `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}; @@ -48,8 +50,79 @@ impl GlobalPtt { } } +/// 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(events: &mut Option) -> Option { +async fn next_event(events: &mut Option) -> Option { match events { Some(events) => events.recv().await, None => std::future::pending().await, @@ -59,22 +132,34 @@ async fn next(events: &mut Option) -> Option { /// 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>, + rx: mpsc::UnboundedReceiver>, status: impl Fn(String), transmit: impl Fn(bool), ) { - let mut manager: Option = None; - let mut events: Option = None; + 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 { break }; + 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); - if let Some(m) = &mut manager { - let _ = m.unregister(PTT_ID).await; - } + registrar.unregister().await; let Some(key) = key else { status("Off.".into()); continue; @@ -86,36 +171,21 @@ async fn run( 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) => { + match registrar.register(key, hotkey).await { + Ok((registered, line)) => { 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}"), - }); + status(line); } - Err(e) => status(format!("Could not register {key}: {e}")), + Err(line) => status(line), } } - event = next(&mut events) => match event { + 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()); } }, @@ -126,9 +196,47 @@ async fn run( #[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] @@ -144,10 +252,10 @@ mod tests { 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); + 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(std::time::Duration::from_millis(5)); + std::thread::sleep(Duration::from_millis(5)); } let log = log.lock().unwrap().clone(); assert_eq!(log[0], "transmit: false", "{log:?}"); @@ -155,6 +263,99 @@ mod tests { 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)); + 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); + }); } }