diff --git a/changelog.d/perf-bridge.fixed.md b/changelog.d/perf-bridge.fixed.md new file mode 100644 index 000000000..3ca5b0c6f --- /dev/null +++ b/changelog.d/perf-bridge.fixed.md @@ -0,0 +1 @@ +The desktop helper no longer wakes every 8 ms while a dictation shortcut is set, so the installed app stays idle in the background (#3924) diff --git a/native/desktop-bridge/README.md b/native/desktop-bridge/README.md index 5f76cb395..dce8bfc00 100644 --- a/native/desktop-bridge/README.md +++ b/native/desktop-bridge/README.md @@ -43,11 +43,19 @@ cover shortcut recording/save, early hold release, toggle and disabling registra On macOS, the helper pumps Core Foundation sources and explicitly drains and dispatches Carbon events on the registration thread. Core Foundation alone does not deliver the queued application hotkeys used by `global-hotkey`. -Each tick drains at most 64 events without waiting, so shortcut traffic cannot +Each pass drains at most 64 events without waiting, so shortcut traffic cannot starve registration changes or shutdown. +Between events the shortcut thread sleeps in each OS's own wait instead of +polling (#3924): the macOS main run loop, the Windows thread message queue, or +the Linux command channel. Commands and off-thread hotkey events (Windows +release detection, the X11 thread, the Wayland portal) wake it explicitly, so +it never wakes while no shortcut is set and only every 500 ms as a backstop +while one is. + `cargo run --locked --manifest-path native/desktop-bridge/Cargo.toml --example macos-shortcut-pump-smoke` posts an application hotkey event and verifies dispatch through the production -pump. It sends no OS keystrokes, changes no global shortcut registration and +pump, then checks that a run-loop sleep honours its limit and ends on the +helper's cross-thread wake. It sends no OS keystrokes, changes no global shortcut registration and requires no Accessibility permission. CI runs it in the Apple Silicon backend smoke job; it can also be run manually on an Intel Mac without installing the Python backend. diff --git a/native/desktop-bridge/examples/macos-shortcut-pump-smoke.rs b/native/desktop-bridge/examples/macos-shortcut-pump-smoke.rs index 28bc307ee..0d72c2081 100644 --- a/native/desktop-bridge/examples/macos-shortcut-pump-smoke.rs +++ b/native/desktop-bridge/examples/macos-shortcut-pump-smoke.rs @@ -87,8 +87,29 @@ fn main() { "queued Carbon hotkey was never dispatched" ); // Empty queues must also return promptly so the helper can process Stop. - macos_event_pump::pump(); + assert!(!macos_event_pump::pump(), "idle pump reported a backlog"); + // The helper sleeps in the run loop between events (#3924): a bounded wait + // must return, and the cross-thread wake (an empty main-queue block) must + // end a sleep long before its limit. + use std::time::{Duration, Instant}; + let started = Instant::now(); + macos_event_pump::wait(Some(Duration::from_millis(50))); + assert!( + started.elapsed() < Duration::from_secs(2), + "bounded wait overran" + ); + std::thread::spawn(|| { + std::thread::sleep(Duration::from_millis(100)); + dispatch2::DispatchQueue::main().exec_async(|| {}); + }); + let started = Instant::now(); + macos_event_pump::wait(Some(Duration::from_secs(20))); + assert!( + started.elapsed() < Duration::from_secs(5), + "a main-queue wake did not end the run-loop sleep" + ); println!("PASS: Carbon application hotkey dispatch and idle pump"); + println!("PASS: run-loop sleep ends on the cross-thread wake"); } #[cfg(not(target_os = "macos"))] diff --git a/native/desktop-bridge/src/macos_event_pump.rs b/native/desktop-bridge/src/macos_event_pump.rs index f67dbabd6..679f2f4b7 100644 --- a/native/desktop-bridge/src/macos_event_pump.rs +++ b/native/desktop-bridge/src/macos_event_pump.rs @@ -1,6 +1,7 @@ //! Dispatch Carbon hotkeys as well as Core Foundation sources on the main thread. use std::ffi::c_void; use std::ptr; +use std::time::Duration; #[link(name = "CoreFoundation", kind = "framework")] unsafe extern "C" { @@ -22,20 +23,36 @@ unsafe extern "C" { fn ReleaseEvent(event: *mut c_void); } -pub fn pump() { +/// A flood of events must not starve the helper's command channel. +const MAX_EVENTS_PER_PUMP: usize = 64; +/// CFRunLoopRunInMode needs a finite limit; this one is effectively "until woken". +const FOREVER_SECONDS: f64 = 1.0e9; + +/// Sleep in the main run loop until one source fires (a window-server event +/// such as a hotkey, a main-queue block, a media-key tap) or `timeout` passes. +pub fn wait(timeout: Option) { + let seconds = timeout.map_or(FOREVER_SECONDS, |timeout| timeout.as_secs_f64()); + unsafe { + CFRunLoopRunInMode(kCFRunLoopDefaultMode, seconds, true); + } +} + +/// Dispatch what is already queued without waiting. Returns `true` when the +/// per-call cap left Carbon events behind, so the caller must not sleep. +pub fn pump() -> bool { // CF sources deliver media keys, but Carbon hotkeys also need their queued // events explicitly dispatched. Never wait for an event here: registration // commands and EOF/Stop still need a turn when no shortcut is pressed. unsafe { - CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, true); - // A flood of events must not starve the helper's command channel. - for _ in 0..64 { + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0, true); + for _ in 0..MAX_EVENTS_PER_PUMP { let mut event = ptr::null_mut(); if ReceiveNextEvent(0, ptr::null(), 0.0, 1, &mut event) != 0 || event.is_null() { - break; + return false; } SendEventToEventTarget(event, GetEventDispatcherTarget()); ReleaseEvent(event); } } + true } diff --git a/native/desktop-bridge/src/shortcuts.rs b/native/desktop-bridge/src/shortcuts.rs index 88b8d546a..c5233b797 100644 --- a/native/desktop-bridge/src/shortcuts.rs +++ b/native/desktop-bridge/src/shortcuts.rs @@ -1,30 +1,84 @@ //! Native press/release service. Registration and platform event pumping share //! the main thread (required by macOS Carbon and Windows message-only windows). +//! +//! The thread sleeps in the OS's own wait (macOS run loop, Windows message +//! queue, Linux channel) until a hotkey, portal signal or command arrives; +//! commands and off-thread hotkey events wake it explicitly. It never ticks +//! while no shortcut is set, and only a slow backstop runs while one is. use global_hotkey::{hotkey::HotKey, GlobalHotKeyEvent, GlobalHotKeyManager, HotKeyState}; -use std::{str::FromStr, sync::mpsc, time::Duration}; +use std::{ + str::FromStr, + sync::{mpsc, Mutex}, + time::Duration, +}; -enum Command { +/// Backstop wake while a shortcut is registered. Every delivery path wakes the +/// thread itself, so this only bounds the damage of a wake an OS drops. +pub(crate) const REGISTERED_BACKSTOP: Duration = Duration::from_millis(500); + +enum Message { Replace(Option, mpsc::SyncSender>), Stop, + Hotkey { + id: u32, + pressed: bool, + }, + #[cfg(target_os = "linux")] + Portal { + generation: u64, + pressed: bool, + }, } + #[derive(Clone)] -pub struct Control(mpsc::Sender); -pub struct Events(mpsc::Receiver); +pub struct Control(mpsc::Sender); +pub struct Events { + tx: mpsc::Sender, + rx: mpsc::Receiver, +} pub fn channel() -> (Control, Events) { let (tx, rx) = mpsc::channel(); - (Control(tx), Events(rx)) + (Control(tx.clone()), Events { tx, rx }) } impl Control { + fn send(&self, message: Message) -> Result<(), String> { + self.0 + .send(message) + .map_err(|_| "Shortcut service stopped")?; + waker::wake(); + Ok(()) + } pub fn replace(&self, accelerator: Option) -> Result<(), String> { let (tx, rx) = mpsc::sync_channel(1); - self.0 - .send(Command::Replace(accelerator, tx)) - .map_err(|_| "Shortcut service stopped")?; + self.send(Message::Replace(accelerator, tx))?; rx.recv_timeout(Duration::from_secs(300)) .map_err(|_| "Shortcut registration timed out")? } pub fn stop(&self) { - let _ = self.0.send(Command::Stop); + let _ = self.send(Message::Stop); + } +} + +/// Where global-hotkey delivers events. Its handler can only be set once per +/// process and may run off the main thread (Windows release detection, the +/// Linux X11 thread), so it forwards into whichever service is running. +static HOTKEY_SINK: Mutex>> = Mutex::new(None); + +fn forward_hotkey(event: GlobalHotKeyEvent) { + let sink = HOTKEY_SINK + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + if let Some(sink) = sink.as_ref() { + let pressed = event.state == HotKeyState::Pressed; + if sink + .send(Message::Hotkey { + id: event.id, + pressed, + }) + .is_ok() + { + waker::wake(); + } } } @@ -39,10 +93,46 @@ fn parse(raw: &str) -> Result { Ok(hotkey) } +/// How long the service may sleep before looking again. `None` means until +/// woken: commands and every hotkey path wake the thread explicitly. +pub(crate) fn wait_budget(backlog: bool, registered: bool) -> Option { + if backlog { + Some(Duration::ZERO) + } else if registered { + Some(REGISTERED_BACKSTOP) + } else { + None + } +} + +/// Collapses repeated press/release reports into edges. +#[derive(Default)] +pub(crate) struct Latch { + down: bool, +} +impl Latch { + /// The edge to emit, if `pressed` changes the held state. + pub(crate) fn apply(&mut self, pressed: bool) -> Option { + (pressed != self.down).then(|| { + self.down = pressed; + pressed + }) + } + /// A synthetic release when the shortcut goes away mid-hold. + pub(crate) fn reset(&mut self) -> Option { + self.apply(false) + } +} + pub fn run(events: Events, mut emit: impl FnMut(bool)) { + waker::bind_current_thread(); + *HOTKEY_SINK + .lock() + .unwrap_or_else(|poison| poison.into_inner()) = Some(events.tx.clone()); + GlobalHotKeyEvent::set_event_handler(Some(forward_hotkey)); let mut manager: Option = None; let mut current: Option = None; - let mut down = false; + let mut latch = Latch::default(); #[cfg(target_os = "linux")] let portal = crate::wayland_shortcut_core::PortalShortcutState::for_desktop( "com.voicestudio.desktop", @@ -51,107 +141,121 @@ pub fn run(events: Events, mut emit: impl FnMut(bool)) { .unwrap_or_else(|| std::env::current_exe().unwrap_or_default()), ); #[cfg(target_os = "linux")] - let (portal_tx, portal_rx) = mpsc::channel::<(u64, bool)>(); - #[cfg(target_os = "linux")] let mut portal_generation = 0u64; - loop { - pump(); - #[cfg(target_os = "linux")] - while let Ok((generation, pressed)) = portal_rx.try_recv() { - if generation == portal_generation && pressed != down { - down = pressed; - emit(pressed); - } - } - while let Ok(event) = GlobalHotKeyEvent::receiver().try_recv() { - if current.as_ref().map(|key| key.id()) != Some(event.id) { - continue; - } - let pressed = event.state == HotKeyState::Pressed; - if pressed != down { - down = pressed; - emit(pressed); - } - } - match events - .0 - .recv_timeout(Duration::from_millis(if current.is_some() { - 8 - } else { - 250 - })) { - Ok(Command::Stop) | Err(mpsc::RecvTimeoutError::Disconnected) => break, - Err(mpsc::RecvTimeoutError::Timeout) => {} - Ok(Command::Replace(raw, reply)) => { - let result = (|| { - let next = raw.as_deref().map(parse).transpose()?; - if next == current { - return Ok(()); - } - #[cfg(target_os = "linux")] - if crate::wayland_shortcut_core::is_wayland_session() { - let next_generation = portal_generation.wrapping_add(1); - if let Some(raw) = raw { - let sender = portal_tx.clone(); - portal.replace( - std::sync::Arc::new(move |pressed| { - let _ = sender.send((next_generation, pressed)); - }), - raw, - )?; - } else { - portal.close(); + let mut backlog = true; + 'service: loop { + let mut next = match waker::wait(&events.rx, wait_budget(backlog, current.is_some())) { + Err(mpsc::RecvTimeoutError::Disconnected) => break, + Err(mpsc::RecvTimeoutError::Timeout) => None, + Ok(message) => Some(message), + }; + backlog = pump(); + loop { + let message = match next.take() { + Some(message) => message, + None => match events.rx.try_recv() { + Ok(message) => message, + Err(mpsc::TryRecvError::Empty) => break, + Err(mpsc::TryRecvError::Disconnected) => break 'service, + }, + }; + match message { + Message::Stop => break 'service, + Message::Hotkey { id, pressed } => { + if current.as_ref().map(|key| key.id()) == Some(id) { + if let Some(edge) = latch.apply(pressed) { + emit(edge); } - if down { - down = false; - emit(false); - } - portal_generation = next_generation; - current = next; - return Ok(()); } - if manager.is_none() && next.is_some() { - manager = - Some(GlobalHotKeyManager::new().map_err(|error| error.to_string())?); - } - if let Some(manager) = &manager { - // Bind replacement first so an invalid/conflicting shortcut - // cannot destroy a previously working registration. - if let Some(next) = next { - manager.register(next).map_err(|error| error.to_string())?; + } + #[cfg(target_os = "linux")] + Message::Portal { + generation, + pressed, + } => { + if generation == portal_generation { + if let Some(edge) = latch.apply(pressed) { + emit(edge); } - if let Some(previous) = current { - if let Err(error) = manager.unregister(previous) { - if let Some(next) = next { - let _ = manager.unregister(next); + } + } + Message::Replace(raw, reply) => { + let result = (|| { + let next = raw.as_deref().map(parse).transpose()?; + if next == current { + return Ok(()); + } + #[cfg(target_os = "linux")] + if crate::wayland_shortcut_core::is_wayland_session() { + let next_generation = portal_generation.wrapping_add(1); + if let Some(raw) = raw { + let sender = events.tx.clone(); + portal.replace( + std::sync::Arc::new(move |pressed| { + let _ = sender.send(Message::Portal { + generation: next_generation, + pressed, + }); + }), + raw, + )?; + } else { + portal.close(); + } + if let Some(edge) = latch.reset() { + emit(edge); + } + portal_generation = next_generation; + current = next; + return Ok(()); + } + if manager.is_none() && next.is_some() { + manager = Some( + GlobalHotKeyManager::new().map_err(|error| error.to_string())?, + ); + } + if let Some(manager) = &manager { + // Bind replacement first so an invalid/conflicting shortcut + // cannot destroy a previously working registration. + if let Some(next) = next { + manager.register(next).map_err(|error| error.to_string())?; + } + if let Some(previous) = current { + if let Err(error) = manager.unregister(previous) { + if let Some(next) = next { + let _ = manager.unregister(next); + } + return Err(error.to_string()); } - return Err(error.to_string()); } } - } - if down { - down = false; - emit(false); - } - current = next; - Ok(()) - })(); - let _ = reply.send(result); + if let Some(edge) = latch.reset() { + emit(edge); + } + current = next; + Ok(()) + })(); + let _ = reply.send(result); + } } } } + *HOTKEY_SINK + .lock() + .unwrap_or_else(|poison| poison.into_inner()) = None; #[cfg(target_os = "linux")] portal.close(); - if down { - emit(false); + if let Some(edge) = latch.reset() { + emit(edge); } if let (Some(manager), Some(current)) = (manager, current) { let _ = manager.unregister(current); } } +/// Dispatch queued OS events without waiting. `true` means more were left. #[cfg(target_os = "windows")] -fn pump() { +fn pump() -> bool { use windows::Win32::UI::WindowsAndMessaging::{ DispatchMessageW, PeekMessageW, TranslateMessage, MSG, PM_REMOVE, }; @@ -162,13 +266,106 @@ fn pump() { DispatchMessageW(&message); } } + false } #[cfg(target_os = "macos")] -fn pump() { - crate::macos_event_pump::pump(); +fn pump() -> bool { + crate::macos_event_pump::pump() +} +#[cfg(not(any(target_os = "windows", target_os = "macos")))] +fn pump() -> bool { + false // global-hotkey owns the X11 connection's event thread. +} + +/// Sleeping and waking the service thread with each OS's native primitive. +mod waker { + use std::{sync::mpsc, time::Duration}; + + /// Windows: block in the thread's message queue (WM_HOTKEY lands there); + /// other threads post a null message to it. + #[cfg(target_os = "windows")] + mod os { + use std::sync::atomic::{AtomicU32, Ordering}; + use std::time::Duration; + use windows::Win32::Foundation::{LPARAM, WPARAM}; + use windows::Win32::System::Threading::{GetCurrentThreadId, INFINITE}; + use windows::Win32::UI::WindowsAndMessaging::{ + MsgWaitForMultipleObjectsEx, PostThreadMessageW, MWMO_INPUTAVAILABLE, QS_ALLINPUT, + WM_NULL, + }; + static THREAD: AtomicU32 = AtomicU32::new(0); + pub fn bind_current_thread() { + THREAD.store(unsafe { GetCurrentThreadId() }, Ordering::SeqCst); + } + pub fn wake() { + // Before the service's first pump there is no queue to post to, + // but the loop drains the channel before it ever sleeps. + let thread = THREAD.load(Ordering::SeqCst); + if thread != 0 { + let _ = unsafe { PostThreadMessageW(thread, WM_NULL, WPARAM(0), LPARAM(0)) }; + } + } + pub fn sleep(timeout: Option) { + let millis = timeout.map_or(INFINITE, |timeout| { + u32::try_from(timeout.as_millis()).unwrap_or(INFINITE - 1) + }); + unsafe { + let _ = MsgWaitForMultipleObjectsEx(None, millis, QS_ALLINPUT, MWMO_INPUTAVAILABLE); + } + } + } + + /// macOS: block in the main run loop, which also serves the main dispatch + /// queue (keyboard output) and the window-server port carrying hotkeys. + /// Other threads wake it by queueing an empty main-queue block. + #[cfg(target_os = "macos")] + mod os { + use std::time::Duration; + pub fn bind_current_thread() {} + pub fn wake() { + dispatch2::DispatchQueue::main().exec_async(|| {}); + } + pub fn sleep(timeout: Option) { + crate::macos_event_pump::wait(timeout); + } + } + + pub fn bind_current_thread() { + #[cfg(any(target_os = "windows", target_os = "macos"))] + os::bind_current_thread(); + } + + pub fn wake() { + #[cfg(any(target_os = "windows", target_os = "macos"))] + os::wake(); + } + + /// Sleep until woken or `timeout`. macOS/Windows sleep in the OS queue and + /// leave the channel to the caller. + #[cfg(any(target_os = "windows", target_os = "macos"))] + pub fn wait( + _rx: &mpsc::Receiver, + timeout: Option, + ) -> Result { + if timeout != Some(Duration::ZERO) { + os::sleep(timeout); + } + Err(mpsc::RecvTimeoutError::Timeout) + } + + /// Linux has no main-thread event source of its own (X11 and the portal + /// run on their own threads), so it blocks on the channel itself. + #[cfg(not(any(target_os = "windows", target_os = "macos")))] + pub fn wait( + rx: &mpsc::Receiver, + timeout: Option, + ) -> Result { + match timeout { + Some(timeout) => rx.recv_timeout(timeout), + None => rx.recv().map_err(|_| mpsc::RecvTimeoutError::Disconnected), + } + } } -#[cfg(target_os = "linux")] -fn pump() {} // global-hotkey owns the X11 connection's event thread. #[cfg(test)] mod tests { @@ -181,4 +378,63 @@ mod tests { assert!(parse("Ctrl+NotAKey").is_err()); assert!(parse(&"x".repeat(101)).is_err()); } + + #[test] + fn never_ticks_without_a_shortcut_and_only_slowly_with_one() { + // #3924: the service woke every 8 ms whenever a shortcut was set. + assert_eq!(wait_budget(false, false), None); + assert_eq!(wait_budget(false, true), Some(REGISTERED_BACKSTOP)); + assert!(REGISTERED_BACKSTOP >= Duration::from_millis(250)); + } + + #[test] + fn a_backlog_is_drained_without_sleeping() { + assert_eq!(wait_budget(true, false), Some(Duration::ZERO)); + assert_eq!(wait_budget(true, true), Some(Duration::ZERO)); + } + + #[test] + fn latch_reports_only_edges() { + let mut latch = Latch::default(); + assert_eq!(latch.reset(), None); + assert_eq!(latch.apply(true), Some(true)); + assert_eq!(latch.apply(true), None, "auto-repeat is not a new press"); + assert_eq!(latch.apply(false), Some(false)); + assert_eq!(latch.apply(false), None); + latch.apply(true); + assert_eq!(latch.reset(), Some(false), "replacing mid-hold releases"); + } + + #[cfg(not(any(target_os = "windows", target_os = "macos")))] + #[test] + fn commands_wake_a_service_sleeping_without_a_shortcut() { + let (control, events) = channel(); + let sender = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(50)); + control.stop(); + }); + assert!(matches!(waker::wait(&events.rx, None), Ok(Message::Stop))); + sender.join().unwrap(); + } + + #[test] + fn hotkeys_reach_the_running_service_only() { + let (_control, events) = channel(); + let event = |id| GlobalHotKeyEvent { + id, + state: HotKeyState::Pressed, + }; + *HOTKEY_SINK.lock().unwrap() = Some(events.tx.clone()); + forward_hotkey(event(7)); + assert!(matches!( + events.rx.try_recv(), + Ok(Message::Hotkey { + id: 7, + pressed: true + }) + )); + *HOTKEY_SINK.lock().unwrap() = None; + forward_hotkey(event(8)); + assert!(events.rx.try_recv().is_err()); + } } diff --git a/tests/smoke/test_macos_hotkey_pump.py b/tests/smoke/test_macos_hotkey_pump.py index a30ced0af..072a24fa0 100644 --- a/tests/smoke/test_macos_hotkey_pump.py +++ b/tests/smoke/test_macos_hotkey_pump.py @@ -19,3 +19,5 @@ def test_native_carbon_shortcut_event_delivery(): ) assert result.returncode == 0, result.stdout + result.stderr assert "PASS: Carbon application hotkey dispatch and idle pump" in result.stdout + # #3924: the helper sleeps in the run loop and must wake for commands. + assert "PASS: run-loop sleep ends on the cross-thread wake" in result.stdout