diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index d991bac7..39eefa1a 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -119,6 +119,7 @@ jobs: - os: windows-latest updates: updates-velopack runs-on: ${{ matrix.os }} + # Cold Windows builds and inspection fixtures need time for the remaining view tests. timeout-minutes: ${{ matrix.os == 'windows-latest' && 90 || 60 }} env: RUST_BACKTRACE: "1" @@ -174,6 +175,12 @@ jobs: if: runner.os == 'Windows' run: | cargo test -p rake-app-cli --bin rake project_build:: --locked + - name: Global shortcut lifecycle (Windows) + if: runner.os == 'Windows' + run: cargo run -p rake-shortcuts --example shortcut-probe --locked + - name: Global shortcut lifecycle (X11) + if: runner.os == 'Linux' + run: xvfb-run -a env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 cargo run -p rake-shortcuts --example shortcut-probe --locked - name: Default desktop lints run: >- cargo clippy -p rake-app -p rake-desktop-example -p rake-notes @@ -347,6 +354,7 @@ jobs: - run: cargo clippy -p rake-native --features native-tests --all-targets --locked -- -D warnings - run: cargo test -p rake-native --doc --locked - run: cargo test -p rake-native --features native-tests --test appkit --locked + - run: cargo run -p rake-shortcuts --example shortcut-probe --locked - run: cargo test -p rake-tray --locked - run: cargo test --workspace --locked --no-fail-fast - run: cargo test -p rake-files --lib --locked @@ -355,6 +363,7 @@ jobs: - run: cargo test -p rake-app --features tray,view-test-support --lib --locked - run: cargo check -p rake-app --features tray,gpui-fast --all-targets --locked - run: cargo check -p renamed-facade --features tray --locked + - run: cargo check -p rake-tray-example --locked - run: cargo test -p rake-app --features view-test-support --lib --test view_state --test actions --test inspection_compiled_out --locked - run: cargo test -p rake-view --features view-test-support --lib --locked - run: cargo test -p rake-app --features view-test-support,devtools --lib --test view_state --test element_inspection --locked diff --git a/Cargo.lock b/Cargo.lock index f9cbef0e..f19e94a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7171,6 +7171,7 @@ dependencies = [ "rake-native", "rake-protocol", "rake-resources", + "rake-shortcuts", "rake-tray", "rake-ui", "rake-updates", @@ -7556,6 +7557,21 @@ dependencies = [ "tracing", ] +[[package]] +name = "rake-shortcuts" +version = "0.1.0-alpha.4" +dependencies = [ + "ashpd", + "async-io", + "blocking", + "futures", + "objc2 0.6.5", + "rake-tray", + "thiserror 2.0.21", + "windows-sys 0.61.2", + "x11rb", +] + [[package]] name = "rake-tray" version = "0.1.0-alpha.4" diff --git a/Cargo.toml b/Cargo.toml index be73c88e..dceccbdd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["vendor/blaze-live", "crates/rake-autostart", "crates/rake-view-syntax", "crates/rake-tray", "crates/rake-native", "crates/rake-dist-linux", "crates/rake-updates", "crates/rake-dist-macos", "crates/rake-build", "crates/rake-resources", "crates/rake-dist-windows", "crates/rake-dist-core", "crates/rake-dist", "crates/rake", "crates/rake-diagnostics", "crates/rake-http", "crates/rake-ui", "crates/rake-protocol", "crates/rake-client", "crates/rake-macros", "crates/rake-cli", "examples/tray", "examples/gpu-surface", "examples/gpu-surface/renderer", "examples/kit", "examples/desktop", "examples/distribution", "examples/foundation", "examples/files", "examples/routing", "examples/notes", "examples/view", "examples/preview", "examples/file-icons", "examples/agent", "tests/renamed-facade", "tests/web-platform"] +members = ["crates/rake-shortcuts", "vendor/blaze-live", "crates/rake-autostart", "crates/rake-view-syntax", "crates/rake-tray", "crates/rake-native", "crates/rake-dist-linux", "crates/rake-updates", "crates/rake-dist-macos", "crates/rake-build", "crates/rake-resources", "crates/rake-dist-windows", "crates/rake-dist-core", "crates/rake-dist", "crates/rake", "crates/rake-diagnostics", "crates/rake-http", "crates/rake-ui", "crates/rake-protocol", "crates/rake-client", "crates/rake-macros", "crates/rake-cli", "examples/tray", "examples/gpu-surface", "examples/gpu-surface/renderer", "examples/kit", "examples/desktop", "examples/distribution", "examples/foundation", "examples/files", "examples/routing", "examples/notes", "examples/view", "examples/preview", "examples/file-icons", "examples/agent", "tests/renamed-facade", "tests/web-platform"] exclude = ["crates/rake-cli/lints/rake-gpui", "examples/inspector", "vendor/gpui-base", "vendor/gpui-pre-web"] resolver = "3" diff --git a/crates/rake-shortcuts/Cargo.toml b/crates/rake-shortcuts/Cargo.toml new file mode 100644 index 00000000..6935e873 --- /dev/null +++ b/crates/rake-shortcuts/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "rake-shortcuts" +version = "0.1.0-alpha.4" +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +description = "Owned native global shortcut registrations for Rake" + +[lints] +workspace = true + +[dependencies] +rake-tray = { version = "=0.1.0-alpha.4", path = "../rake-tray" } +futures.workspace = true +thiserror.workspace = true + +[target.'cfg(target_os = "macos")'.dependencies] +objc2 = "0.6.5" + +[target.'cfg(target_os = "windows")'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_System_LibraryLoader", "Win32_Graphics_Gdi"] } + +[target.'cfg(target_os = "linux")'.dependencies] +ashpd = { version = "0.13.13", default-features = false, features = ["async-io", "global_shortcuts"] } +x11rb = "0.13.2" +async-io = "2.6" +blocking = "1.7" + +[[example]] +name = "shortcut-probe" diff --git a/crates/rake-shortcuts/examples/shortcut-probe.rs b/crates/rake-shortcuts/examples/shortcut-probe.rs new file mode 100644 index 00000000..0f92fc8a --- /dev/null +++ b/crates/rake-shortcuts/examples/shortcut-probe.rs @@ -0,0 +1,37 @@ +//! Short-lived real registration/conflict/cleanup probe; never simulates key presses. +use rake_shortcuts::{Error, Shortcut}; + +fn main() -> Result<(), Box> { + futures::executor::block_on(async { + let key = "Ctrl+Alt+Shift+9"; + let mut first = Shortcut::register(key).await?; + + assert!(matches!( + Shortcut::register(key).await, + Err(Error::Conflict) + )); + first.unregister().await?; + first.unregister().await?; + let second = Shortcut::register(key).await?; + + drop(second); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + + let mut third = loop { + match Shortcut::register(key).await { + Ok(shortcut) => break shortcut, + Err(Error::Conflict) if std::time::Instant::now() < deadline => { + std::thread::yield_now(); + } + Err(error) => return Err(error), + } + }; + + third.unregister().await?; + + Ok::<_, Error>(()) + })?; + println!("global shortcut probe passed: register, conflict, unregister, drop, re-register"); + + Ok(()) +} diff --git a/crates/rake-shortcuts/src/lib.rs b/crates/rake-shortcuts/src/lib.rs new file mode 100644 index 00000000..38fd6134 --- /dev/null +++ b/crates/rake-shortcuts/src/lib.rs @@ -0,0 +1,156 @@ +//! Owned global shortcuts. Native events are queued; callers choose their UI dispatcher. +//! macOS and Windows registration, event pumping and destruction belong on the UI thread. + +use futures::channel::mpsc; +use rake_tray::Accelerator; +use std::marker::PhantomData; +use std::rc::Rc; + +#[cfg(target_os = "linux")] +mod linux; +#[cfg(target_os = "macos")] +mod macos; +#[cfg(target_os = "windows")] +mod windows; + +#[cfg(target_os = "linux")] +use linux as native; +#[cfg(target_os = "macos")] +use macos as native; +#[cfg(target_os = "windows")] +use windows as native; + +/// Registration failed; no alternative shortcut is silently chosen. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// No backend is available in this host/session. + #[error("global shortcuts are unsupported in this host/session")] + Unsupported, + /// Parsing or the native key mapping rejected the accelerator. + #[error("invalid global shortcut: {0}")] + InvalidInput(String), + /// Another registration already owns this shortcut. + #[error("global shortcut is already registered")] + Conflict, + /// Authorization was refused. + #[error("global shortcut permission denied")] + PermissionDenied, + /// An OS failure, including its diagnostic. + #[error("global shortcut failed: {0}")] + Native(String), +} + +/// A thread-bound registration. Drop releases its native resources and stops events. +/// Use `unregister` to observe cleanup errors and await portal session closure. +pub struct Shortcut { + #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))] + native: Option, + events: mpsc::Receiver<()>, + _thread: PhantomData>, +} + +impl Shortcut { + /// Registers a tray-parser accelerator. Poll on the native UI thread. + /// On Wayland the portal may prompt and choose a user-approved binding. + /// + /// # Errors + /// Reports invalid keys, conflicts, denied permission and unavailable backends. + pub async fn register(value: &str) -> Result { + let accelerator = + Accelerator::parse(value).map_err(|error| Error::InvalidInput(error.to_string()))?; + + if accelerator.key.chars().count() != 1 { + return Err(Error::InvalidInput( + "key normalization produced multiple characters".into(), + )); + } + + if !(accelerator.control || accelerator.alt || accelerator.super_key) { + return Err(Error::InvalidInput( + "use Ctrl, Alt or Super with a key".into(), + )); + } + + let (sender, events) = mpsc::channel::<()>(1); + + #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))] + { + let native = native::register(accelerator, sender).await?; + + Ok(Self { + native: Some(native), + events, + _thread: PhantomData, + }) + } + + #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))] + { + let _ = (accelerator, sender, events); + + Err(Error::Unsupported) + } + } + + /// Takes the activation inbox for a separate UI dispatch task. + /// Subsequent calls return a closed inbox. + pub fn take_events(&mut self) -> mpsc::Receiver<()> { + std::mem::replace(&mut self.events, mpsc::channel(1).1) + } + + /// Waits for an activation; a small bounded inbox coalesces repeated presses. + pub async fn next(&mut self) -> Option<()> { + use futures::StreamExt; + + self.events.next().await + } + + /// Releases the registration. Repeated calls are harmless. + /// + /// # Errors + /// Reports native cleanup failures; Drop still attempts resource release. + pub async fn unregister(&mut self) -> Result<(), Error> { + self.events.close(); + + #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))] + if let Some(mut native) = self.native.take() { + native.unregister().await?; + } + + Ok(()) + } +} + +/// Detects backend availability without registering keys or prompting. +pub async fn available() -> bool { + #[cfg(target_os = "linux")] + return linux::available().await; + + #[cfg(not(target_os = "linux"))] + cfg!(any(target_os = "macos", target_os = "windows")) +} + +#[cfg(test)] +mod tests { + //! Covers: parser validation before native registration. + //! Real: accelerator parser. Doubles: none. Requires: no graphical session. + use super::*; + + #[test] + fn invalid_shortcuts_never_register() { + for value in [ + "", + "Ctrl+Ctrl+k", + "Hyper+k", + "Ctrl+Enter", + "Ctrl+İ", + "k", + "Shift+k", + ] { + assert!(matches!( + futures::executor::block_on(Shortcut::register(value)), + Err(Error::InvalidInput(_)) + )); + } + } +} diff --git a/crates/rake-shortcuts/src/linux.rs b/crates/rake-shortcuts/src/linux.rs new file mode 100644 index 00000000..f39fe3ac --- /dev/null +++ b/crates/rake-shortcuts/src/linux.rs @@ -0,0 +1,337 @@ +//! X11 passive grabs and compositor-mediated Wayland portal sessions. +use super::Error; +use futures::{ + FutureExt, StreamExt, + channel::{mpsc, oneshot}, +}; +use rake_tray::Accelerator; +use std::time::Duration; + +pub(super) struct Registration { + stop: Option>, + done: Option>>, +} + +pub(super) async fn available() -> bool { + if wayland() { + ashpd::desktop::global_shortcuts::GlobalShortcuts::new() + .await + .is_ok() + } else { + blocking::unblock(|| x11rb::connect(None).is_ok()).await + } +} + +fn wayland() -> bool { + std::env::var_os("WAYLAND_DISPLAY").is_some() + || std::env::var("XDG_SESSION_TYPE").is_ok_and(|value| value == "wayland") +} + +pub(super) async fn register( + accelerator: Accelerator, + sender: mpsc::Sender<()>, +) -> Result { + let (stop, stopped) = oneshot::channel(); + let (done, finished) = oneshot::channel(); + let (ready, registered) = oneshot::channel(); + let registration = Registration { + stop: Some(stop), + done: Some(finished), + }; + let portal = wayland(); + + std::thread::Builder::new() + .name("rake-shortcut".into()) + .spawn(move || { + let result = async_io::block_on(async move { + if portal { + portal_worker(accelerator, sender, stopped, ready).await + } else { + x11_worker(accelerator, sender, stopped, ready).await + } + }); + let _ = done.send(result); + }) + .map_err(|error| Error::Native(error.to_string()))?; + + registered + .await + .map_err(|_| Error::Native("shortcut worker stopped during registration".into()))??; + + Ok(registration) +} + +impl Registration { + pub(super) async fn unregister(&mut self) -> Result<(), Error> { + self.stop.take(); + + if let Some(done) = self.done.take() { + done.await.map_err(|_| { + Error::Native("shortcut worker stopped without cleanup receipt".into()) + })??; + } + + Ok(()) + } +} + +impl Drop for Registration { + fn drop(&mut self) { + // Closing the sender wakes the worker, which owns and releases all OS resources. + self.stop.take(); + } +} + +async fn portal_worker( + accelerator: Accelerator, + mut sender: mpsc::Sender<()>, + stopped: oneshot::Receiver<()>, + ready: oneshot::Sender>, +) -> Result<(), Error> { + use ashpd::desktop::global_shortcuts::{GlobalShortcuts, NewShortcut}; + + let connection = match ashpd::zbus::Connection::session().await { + Ok(connection) => connection, + Err(_) => { + let _ = ready.send(Err(Error::Unsupported)); + return Ok(()); + } + }; + // A dedicated connection also releases sessions if setup is cancelled midway. + let mut ready = Some(ready); + let result = { + let operation = async { + let portal = GlobalShortcuts::with_connection(connection.clone()) + .await + .map_err(portal_error)?; + let session = portal + .create_session(Default::default()) + .await + .map_err(portal_error)?; + let mut events = portal + .receive_activated() + .await + .map_err(portal_error)? + .boxed(); + let trigger = portal_trigger(&accelerator); + static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + let id = format!( + "rake-{}-{}", + std::process::id(), + NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + ); + let shortcut = NewShortcut::new(&id, "Activate application shortcut") + .preferred_trigger(Some(trigger.as_str())); + let response = portal + .bind_shortcuts(&session, &[shortcut], None, Default::default()) + .await + .map_err(portal_error)? + .response() + .map_err(portal_error)?; + + if !response + .shortcuts() + .iter() + .any(|shortcut| shortcut.id() == id) + { + return Err(Error::PermissionDenied); + } + + let _ = ready.take().expect("registration receipt").send(Ok(())); + + while let Some(event) = events.next().await { + if event.shortcut_id() == id { + let _ = sender.try_send(()); + } + } + + session.close().await.map_err(portal_error) + } + .fuse(); + let stopped = stopped.fuse(); + futures::pin_mut!(operation, stopped); + futures::select! { + result = operation => result, + _ = stopped => Ok(()), + } + }; + // Disconnecting a private D-Bus client closes all its portal sessions, including + // a pending authorization dialog. It cannot affect another Rake registration. + connection + .close() + .await + .map_err(|error| Error::Native(error.to_string()))?; + + if let Some(ready) = ready { + let _ = ready.send(result); + + return Ok(()); + } + + result +} + +fn portal_trigger(accelerator: &Accelerator) -> String { + let mut trigger = String::new(); + + for (enabled, name) in [ + (accelerator.control, "CTRL+"), + (accelerator.alt, "ALT+"), + (accelerator.shift, "SHIFT+"), + (accelerator.super_key, "LOGO+"), + ] { + if enabled { + trigger.push_str(name); + } + } + + trigger.push_str(&accelerator.key); + + trigger +} + +fn portal_error(error: ashpd::Error) -> Error { + match error { + ashpd::Error::PortalNotFound(_) => Error::Unsupported, + ashpd::Error::Response(ashpd::desktop::ResponseError::Cancelled) => Error::PermissionDenied, + error => Error::Native(error.to_string()), + } +} + +async fn x11_worker( + accelerator: Accelerator, + mut sender: mpsc::Sender<()>, + stopped: oneshot::Receiver<()>, + ready: oneshot::Sender>, +) -> Result<(), Error> { + use x11rb::{ + connection::Connection, + protocol::{ + Event, + xproto::{ConnectionExt, GrabMode, ModMask}, + }, + }; + + let setup = || { + let (connection, screen) = x11rb::connect(None).map_err(|_| Error::Unsupported)?; + let root = connection.setup().roots[screen].root; + let key = accelerator + .key + .chars() + .next() + .filter(|key| key.is_ascii()) + .ok_or_else(|| { + Error::InvalidInput("X11 global shortcuts require an ASCII key".into()) + })? as u32; + let first = connection.setup().min_keycode; + let count = connection.setup().max_keycode - first + 1; + let mapping = connection + .get_keyboard_mapping(first, count) + .map_err(x11_error)? + .reply() + .map_err(x11_error)?; + let (keycode, implicit_shift) = mapping + .keysyms + .chunks(usize::from(mapping.keysyms_per_keycode).max(1)) + .enumerate() + .find_map(|(index, symbols)| { + if symbols.first() == Some(&key) { + Some((first + index as u8, false)) + } else if symbols.get(1) == Some(&key) { + Some((first + index as u8, true)) + } else { + None + } + }) + .ok_or_else(|| { + Error::InvalidInput("key is absent from the current X11 layout".into()) + })?; + let modifiers = (u16::from(accelerator.control) * u16::from(ModMask::CONTROL)) + | (u16::from(accelerator.alt) * u16::from(ModMask::M1)) + | (u16::from(accelerator.shift || implicit_shift) * u16::from(ModMask::SHIFT)) + | (u16::from(accelerator.super_key) * u16::from(ModMask::M4)); + let modifier_mapping = connection + .get_modifier_mapping() + .map_err(x11_error)? + .reply() + .map_err(x11_error)?; + let num_lock_code = mapping + .keysyms + .chunks(usize::from(mapping.keysyms_per_keycode).max(1)) + .position(|symbols| symbols.contains(&0xff7f)) + .map(|index| first + index as u8); + let num_lock = modifier_mapping + .keycodes + .chunks(usize::from(modifier_mapping.keycodes_per_modifier()).max(1)) + .position(|keys| num_lock_code.is_some_and(|key| keys.contains(&key))) + .map_or(0, |index| 1_u16 << index); + let mut locks = vec![ + 0, + u16::from(ModMask::LOCK), + num_lock, + num_lock | u16::from(ModMask::LOCK), + ]; + locks.sort_unstable(); + locks.dedup(); + + for lock in &locks { + connection + .grab_key( + false, + root, + (modifiers | lock).into(), + keycode, + GrabMode::ASYNC, + GrabMode::ASYNC, + ) + .map_err(x11_error)? + .check() + .map_err(|error| match error { + x11rb::errors::ReplyError::X11Error(ref native) + if native.error_kind == x11rb::protocol::ErrorKind::Access => + { + Error::Conflict + } + error => x11_error(error), + })?; + } + + Ok::<_, Error>((connection, root, keycode, modifiers, locks)) + }; + let (connection, root, keycode, modifiers, locks) = match setup() { + Ok(state) => state, + Err(error) => { + let _ = ready.send(Err(error)); + return Ok(()); + } + }; + let _ = ready.send(Ok(())); + let stopped = stopped.fuse(); + futures::pin_mut!(stopped); + + loop { + let tick = FutureExt::fuse(async_io::Timer::after(Duration::from_millis(10))); + futures::pin_mut!(tick); + futures::select! { _ = stopped => break, _ = tick => {} } + + while let Some(event) = connection.poll_for_event().map_err(x11_error)? { + if matches!(event, Event::KeyPress(ref event) if event.detail == keycode) { + let _ = sender.try_send(()); + } + } + } + + for lock in locks { + connection + .ungrab_key(keycode, root, (modifiers | lock).into()) + .map_err(x11_error)? + .check() + .map_err(x11_error)?; + } + + connection.flush().map_err(x11_error) +} + +fn x11_error(error: impl std::fmt::Display) -> Error { + Error::Native(error.to_string()) +} diff --git a/crates/rake-shortcuts/src/macos.rs b/crates/rake-shortcuts/src/macos.rs new file mode 100644 index 00000000..89147546 --- /dev/null +++ b/crates/rake-shortcuts/src/macos.rs @@ -0,0 +1,377 @@ +//! Carbon event hotkeys need no Accessibility or Input Monitoring permission. +use super::Error; +use futures::channel::mpsc; +use rake_tray::Accelerator; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, Ordering}; + +#[repr(C)] +#[derive(Clone, Copy)] +struct HotKeyId { + signature: u32, + id: u32, +} + +#[repr(C)] +struct EventType { + class: u32, + kind: u32, +} + +type Ref = *mut c_void; + +#[link(name = "Carbon", kind = "framework")] +unsafe extern "C" { + fn TISCopyCurrentKeyboardLayoutInputSource() -> Ref; + fn TISGetInputSourceProperty(source: Ref, property: Ref) -> Ref; + static kTISPropertyUnicodeKeyLayoutData: Ref; + fn LMGetKbdType() -> u8; + fn UCKeyTranslate( + layout: *const c_void, + key: u16, + action: u16, + modifiers: u32, + keyboard: u32, + options: u32, + dead: *mut u32, + capacity: u32, + length: *mut u32, + output: *mut u16, + ) -> i32; + fn GetApplicationEventTarget() -> Ref; + fn InstallEventHandler( + target: Ref, + callback: unsafe extern "C" fn(Ref, Ref, Ref) -> i32, + count: u32, + types: *const EventType, + data: Ref, + handler: *mut Ref, + ) -> i32; + fn RemoveEventHandler(handler: Ref) -> i32; + fn RegisterEventHotKey( + key: u32, + modifiers: u32, + id: HotKeyId, + target: Ref, + options: u32, + hotkey: *mut Ref, + ) -> i32; + fn UnregisterEventHotKey(hotkey: Ref) -> i32; + fn GetEventParameter( + event: Ref, + name: u32, + kind: u32, + actual_kind: *mut u32, + size: u32, + actual_size: *mut u32, + data: Ref, + ) -> i32; +} + +#[link(name = "CoreFoundation", kind = "framework")] +unsafe extern "C" { + fn CFDataGetBytePtr(data: Ref) -> *const u8; + fn CFRelease(value: Ref); +} + +struct Delivery { + id: HotKeyId, + sender: mpsc::Sender<()>, +} + +pub(super) struct Registration { + hotkey: Ref, + handler: Ref, + _delivery: Box, +} + +unsafe extern "C" fn activated(_: Ref, event: Ref, data: Ref) -> i32 { + let mut id = HotKeyId { + signature: 0, + id: 0, + }; + + // SAFETY: Carbon supplies a live event and the handler's boxed Delivery. Both + // remain valid until RemoveEventHandler on this same main thread. + unsafe { + if GetEventParameter( + event, + u32::from_be_bytes(*b"----"), + u32::from_be_bytes(*b"hkid"), + std::ptr::null_mut(), + std::mem::size_of::() as u32, + std::ptr::null_mut(), + (&mut id as *mut HotKeyId).cast(), + ) != 0 + { + return -9874; + } + + let delivery = &mut *data.cast::(); + + if id.signature != delivery.id.signature || id.id != delivery.id.id { + return -9874; + } + + let _ = delivery.sender.try_send(()); + } + + 0 +} + +pub(super) async fn register( + accelerator: Accelerator, + sender: mpsc::Sender<()>, +) -> Result { + if objc2::MainThreadMarker::new().is_none() { + return Err(Error::Native("register on the main UI thread".into())); + } + + let (key, implicit_shift) = keycode(&accelerator.key)?; + + let modifiers = (u32::from(accelerator.super_key) * (1 << 8)) + | (u32::from(accelerator.shift || implicit_shift) * (1 << 9)) + | (u32::from(accelerator.alt) * (1 << 11)) + | (u32::from(accelerator.control) * (1 << 12)); + + static NEXT: AtomicU32 = AtomicU32::new(1); + let id = NEXT + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1)) + .map_err(|_| Error::Native("shortcut IDs exhausted".into()))?; + + let mut delivery = Box::new(Delivery { + id: HotKeyId { + signature: u32::from_be_bytes(*b"RAKE"), + id, + }, + sender, + }); + + let data = (&mut *delivery as *mut Delivery).cast(); + + let mut registration = Registration { + hotkey: std::ptr::null_mut(), + handler: std::ptr::null_mut(), + _delivery: delivery, + }; + + let event_type = EventType { + class: u32::from_be_bytes(*b"keyb"), + kind: 5, + }; + + // SAFETY: All pointers reference initialized storage. The boxed delivery has + // a stable address and Registration removes the handler before freeing it. + unsafe { + let target = GetApplicationEventTarget(); + + status(InstallEventHandler( + target, + activated, + 1, + &event_type, + data, + &mut registration.handler, + ))?; + let result = RegisterEventHotKey( + key, + modifiers, + registration._delivery.id, + target, + 0, + &mut registration.hotkey, + ); + + if result == -9878 { + return Err(Error::Conflict); + } + + status(result)?; + } + + Ok(registration) +} + +impl Registration { + pub(super) async fn unregister(&mut self) -> Result<(), Error> { + self.release() + } + + fn release(&mut self) -> Result<(), Error> { + // SAFETY: Resources are owned by this registration on the main thread. + unsafe { + if !self.hotkey.is_null() { + status(UnregisterEventHotKey(self.hotkey))?; + self.hotkey = std::ptr::null_mut(); + } + + if !self.handler.is_null() { + status(RemoveEventHandler(self.handler))?; + self.handler = std::ptr::null_mut(); + } + } + + Ok(()) + } +} + +impl Drop for Registration { + fn drop(&mut self) { + let _ = self.release(); + } +} + +fn status(code: i32) -> Result<(), Error> { + if code == 0 { + Ok(()) + } else { + Err(Error::Native(format!("Carbon status {code}"))) + } +} + +fn keycode(key: &str) -> Result<(u32, bool), Error> { + // SAFETY: The copied input source owns its layout data until CFRelease. The + // translator receives initialized output/dead-key storage with matching sizes. + unsafe { + let source = TISCopyCurrentKeyboardLayoutInputSource(); + + if source.is_null() { + return Err(Error::Native( + "current keyboard layout is unavailable".into(), + )); + } + + let data = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData); + let mut found = None; + + if !data.is_null() { + let layout = CFDataGetBytePtr(data).cast(); + let expected: Vec = key.encode_utf16().collect(); + + for shift in [false, true] { + for code in 0..128 { + let mut output = [0_u16; 4]; + let mut length = 0; + let mut dead = 0; + + let status = UCKeyTranslate( + layout, + code, + 0, + if shift { 2 } else { 0 }, + u32::from(LMGetKbdType()), + 1, + &mut dead, + output.len() as u32, + &mut length, + output.as_mut_ptr(), + ); + + if status == 0 && output.get(..length as usize) == Some(expected.as_slice()) { + found = Some((u32::from(code), shift)); + break; + } + } + + if found.is_some() { + break; + } + } + } + + CFRelease(source); + + found.ok_or_else(|| { + Error::InvalidInput("key is absent from the current macOS keyboard layout".into()) + }) + } +} + +#[cfg(test)] +mod tests { + //! Covers: Carbon hotkey event IDs and bounded activation delivery. + //! Real: Carbon event parameters. Doubles: constructed event, no registered keys. + //! Requires: macOS; no permission prompt or keyboard input. + use super::*; + use futures::{FutureExt, StreamExt}; + + #[link(name = "Carbon", kind = "framework")] + unsafe extern "C" { + fn CreateEvent( + allocator: Ref, + class: u32, + kind: u32, + time: f64, + flags: u32, + event: *mut Ref, + ) -> i32; + fn SetEventParameter( + event: Ref, + name: u32, + kind: u32, + size: u32, + data: *const c_void, + ) -> i32; + fn ReleaseEvent(event: Ref); + } + + #[test] + fn carbon_event_routes_only_the_registered_id() { + let (sender, mut events) = mpsc::channel(1); + + let id = HotKeyId { + signature: u32::from_be_bytes(*b"RAKE"), + id: 42, + }; + + let mut delivery = Delivery { id, sender }; + let mut event = std::ptr::null_mut(); + + // SAFETY: Carbon creates a retained event, the parameter points to a + // correctly sized HotKeyId, and Delivery stays live through both calls. + unsafe { + assert_eq!( + CreateEvent( + std::ptr::null_mut(), + u32::from_be_bytes(*b"keyb"), + 5, + 0.0, + 0, + &mut event + ), + 0 + ); + assert_eq!( + SetEventParameter( + event, + u32::from_be_bytes(*b"----"), + u32::from_be_bytes(*b"hkid"), + std::mem::size_of::() as u32, + (&id as *const HotKeyId).cast() + ), + 0 + ); + assert_eq!( + activated( + std::ptr::null_mut(), + event, + (&mut delivery as *mut Delivery).cast() + ), + 0 + ); + delivery.id.id += 1; + assert_eq!( + activated( + std::ptr::null_mut(), + event, + (&mut delivery as *mut Delivery).cast() + ), + -9874 + ); + ReleaseEvent(event); + } + + assert_eq!(events.next().now_or_never(), Some(Some(()))); + assert_eq!(events.next().now_or_never(), None); + } +} diff --git a/crates/rake-shortcuts/src/windows.rs b/crates/rake-shortcuts/src/windows.rs new file mode 100644 index 00000000..ec888c30 --- /dev/null +++ b/crates/rake-shortcuts/src/windows.rs @@ -0,0 +1,233 @@ +//! Message-only windows share the caller's UI message pump. +use super::Error; +use futures::channel::mpsc; +use rake_tray::Accelerator; +use windows_sys::Win32::{ + Foundation::{HWND, LPARAM, LRESULT, WPARAM}, + System::LibraryLoader::GetModuleHandleW, + UI::{ + Input::KeyboardAndMouse::{ + MOD_ALT, MOD_CONTROL, MOD_NOREPEAT, MOD_SHIFT, MOD_WIN, RegisterHotKey, + UnregisterHotKey, VkKeyScanW, + }, + WindowsAndMessaging::*, + }, +}; + +pub(super) struct Registration { + window: HWND, + sender: Box>, + registered: bool, +} + +unsafe extern "system" fn window_proc( + window: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, +) -> LRESULT { + if message == WM_HOTKEY { + // SAFETY: The pointer is installed only after window creation, refers to + // a stable box, and is cleared before that box or the window is destroyed. + unsafe { + let sender = GetWindowLongPtrW(window, GWLP_USERDATA) as *mut mpsc::Sender<()>; + + if let Some(sender) = sender.as_mut() { + let _ = sender.try_send(()); + } + } + + return 0; + } + + // SAFETY: Unhandled messages retain the arguments supplied by the OS. + unsafe { DefWindowProcW(window, message, wparam, lparam) } +} + +pub(super) async fn register( + accelerator: Accelerator, + sender: mpsc::Sender<()>, +) -> Result { + let key = accelerator + .key + .chars() + .next() + .ok_or_else(|| Error::InvalidInput("missing key".into()))?; + + if !key.is_ascii() { + return Err(Error::InvalidInput( + "Windows global shortcuts require an ASCII key".into(), + )); + } + + // SAFETY: VkKeyScanW accepts any UTF-16 code unit and returns -1 if unmappable. + let mapped = unsafe { VkKeyScanW(key as u16) }; + + if mapped == -1 { + return Err(Error::InvalidInput( + "key is absent from the current keyboard layout".into(), + )); + } + + let modifiers = MOD_NOREPEAT + | if accelerator.control || mapped & 0x200 != 0 { + MOD_CONTROL + } else { + 0 + } + | if accelerator.alt || mapped & 0x400 != 0 { + MOD_ALT + } else { + 0 + } + | if accelerator.shift || mapped & 0x100 != 0 { + MOD_SHIFT + } else { + 0 + } + | if accelerator.super_key { MOD_WIN } else { 0 }; + let class: Vec = "RakeGlobalShortcut\0".encode_utf16().collect(); + // SAFETY: The class and window names are NUL-terminated. The window is owned + // by this UI thread; it never stores a pointer to stack data. + unsafe { + let instance = GetModuleHandleW(std::ptr::null()); + let definition = WNDCLASSW { + lpfnWndProc: Some(window_proc), + hInstance: instance, + lpszClassName: class.as_ptr(), + ..Default::default() + }; + + if RegisterClassW(&definition) == 0 + && std::io::Error::last_os_error().raw_os_error() != Some(1410) + { + return Err(last_error()); + } + + let window = CreateWindowExW( + 0, + class.as_ptr(), + class.as_ptr(), + 0, + 0, + 0, + 0, + 0, + HWND_MESSAGE, + std::ptr::null_mut(), + instance, + std::ptr::null(), + ); + + if window.is_null() { + return Err(last_error()); + } + + let mut registration = Registration { + window, + sender: Box::new(sender), + registered: false, + }; + SetWindowLongPtrW( + window, + GWLP_USERDATA, + (&mut *registration.sender as *mut mpsc::Sender<()>) as isize, + ); + + if RegisterHotKey(window, 1, modifiers, (mapped & 0xff) as u32) == 0 { + let error = std::io::Error::last_os_error(); + + return Err(if error.raw_os_error() == Some(1409) { + Error::Conflict + } else { + Error::Native(error.to_string()) + }); + } + + registration.registered = true; + + Ok(registration) + } +} + +impl Registration { + pub(super) async fn unregister(&mut self) -> Result<(), Error> { + self.release() + } + + fn release(&mut self) -> Result<(), Error> { + // SAFETY: The window and hotkey belong to this registration and thread. + unsafe { + if self.registered { + if UnregisterHotKey(self.window, 1) == 0 { + return Err(last_error()); + } + + self.registered = false; + } + + if !self.window.is_null() { + SetWindowLongPtrW(self.window, GWLP_USERDATA, 0); + + if DestroyWindow(self.window) == 0 { + return Err(last_error()); + } + + self.window = std::ptr::null_mut(); + } + } + + Ok(()) + } +} + +impl Drop for Registration { + fn drop(&mut self) { + let _ = self.release(); + } +} + +fn last_error() -> Error { + Error::Native(std::io::Error::last_os_error().to_string()) +} + +#[cfg(test)] +mod tests { + //! Covers: delivery through the real message-only window. + //! Real: RegisterHotKey and the Windows message queue. Doubles: posted WM_HOTKEY. + //! Requires: Windows; no simulated keyboard input. + use super::*; + use futures::{FutureExt, StreamExt}; + + #[test] + fn hotkey_window_delivers_an_activation() { + let (sender, mut events) = mpsc::channel(1); + let mut registration = futures::executor::block_on(register( + Accelerator::parse("Ctrl+Alt+Shift+8").unwrap(), + sender, + )) + .unwrap(); + // SAFETY: The window belongs to this test thread. All message storage is + // initialized and dispatched before the registration is destroyed. + unsafe { + assert_ne!(PostMessageW(registration.window, WM_HOTKEY, 1, 0), 0); + let mut message = MSG::default(); + + assert_ne!( + PeekMessageW( + &mut message, + registration.window, + WM_HOTKEY, + WM_HOTKEY, + PM_REMOVE + ), + 0 + ); + DispatchMessageW(&message); + } + + assert_eq!(events.next().now_or_never(), Some(Some(()))); + futures::executor::block_on(registration.unregister()).unwrap(); + assert_eq!(events.next().now_or_never(), None); + } +} diff --git a/crates/rake/Cargo.toml b/crates/rake/Cargo.toml index db6f7ec5..0de1220f 100644 --- a/crates/rake/Cargo.toml +++ b/crates/rake/Cargo.toml @@ -18,7 +18,8 @@ workspace = true [features] default = ["gpui"] launch-at-login = ["dep:rake-autostart"] -tray = ["gpui", "dep:rake-tray"] +tray = ["gpui", "dep:rake-tray", "global-shortcuts"] +global-shortcuts = ["gpui", "dep:rake-shortcuts"] gpu-surface = ["gpui-fast", "dep:metal", "dep:foreign-types", "dep:objc2", "dep:objc2-foundation", "dep:objc2-quartz-core", "objc2-app-kit?/objc2-quartz-core", "dep:windows"] gpui-fast = ["gpui", "dep:gpui_fast", "dep:gpui_fast_platform", "rake-ui/gpui-fast"] live = ["gpui", "dep:blaze-live", "dep:pathfinder_simd"] @@ -37,6 +38,7 @@ view-test-support = ["gpui", "gpui_pre/test-support", "gpui_fast?/test-support", gpui = ["dep:rake-ui", "rake-macros/view", "dep:gpui_pre", "dep:gpui_platform", "dep:objc2-app-kit", "dep:objc2", "dep:objc2-foundation", "dep:block2", "dep:objc2-user-notifications", "dep:raw-window-handle", "dep:windows-sys", "native-lifecycle"] [dependencies] +rake-shortcuts = { version = "=0.1.0-alpha.4", path = "../rake-shortcuts", optional = true } image = { version = "0.25.10", default-features = false, features = ["png"] } rake-autostart = { version = "=0.1.0-alpha.4", path = "../rake-autostart", optional = true } rake-tray = { version = "=0.1.0-alpha.4", path = "../rake-tray", optional = true } diff --git a/crates/rake/src/platform/browser.rs b/crates/rake/src/platform/browser.rs index d0777e16..29a23f9d 100644 --- a/crates/rake/src/platform/browser.rs +++ b/crates/rake/src/platform/browser.rs @@ -66,6 +66,7 @@ pub(super) fn capabilities() -> Capabilities { }; Capabilities { notifications: super::notifications::capability(), + global_shortcuts: super::GlobalShortcuts::default().capability(), file_import: capability(1, true), file_export: capability(2, true), clipboard_read: capability(4, true), diff --git a/crates/rake/src/platform/mod.rs b/crates/rake/src/platform/mod.rs index c104d57a..d85fb231 100644 --- a/crates/rake/src/platform/mod.rs +++ b/crates/rake/src/platform/mod.rs @@ -6,6 +6,12 @@ //! observation, but cannot undo an OS dialog, clipboard write or browser download. mod notifications; +mod shortcuts; + +#[cfg(feature = "gpui")] +pub use shortcuts::GlobalShortcut; +pub use shortcuts::GlobalShortcuts; + mod preferences; pub use notifications::{Notification, NotificationOutcome}; @@ -36,6 +42,9 @@ pub enum Error { /// No implementation exists in the current host. #[error("{0} is unsupported by this host")] Unsupported(&'static str), + /// Another application or registration owns the requested shortcut. + #[error("global shortcut is already registered")] + ShortcutConflict, /// Host security policy or the user denied the operation. #[error("permission denied for {0}")] PermissionDenied(&'static str), @@ -104,6 +113,8 @@ pub struct Capabilities { pub open_url: Capability, /// Post OS notifications; permission and delivery remain separate. pub notifications: Capability, + /// Register a system-wide shortcut; headless and Web are unsupported. + pub global_shortcuts: Capability, } #[derive(Default)] @@ -116,6 +127,7 @@ struct Activations { #[derive(Clone, Default)] pub struct Platform { activations: Rc, + shortcuts: GlobalShortcuts, #[cfg(any(feature = "gpui", test))] notifications: Rc, } @@ -142,6 +154,7 @@ impl Platform { Capabilities { notifications: notifications::capability(), + global_shortcuts: self.shortcuts.capability(), file_import: ui, file_export: ui, clipboard_read: ui, diff --git a/crates/rake/src/platform/notifications/browser.rs b/crates/rake/src/platform/notifications/browser.rs index 46a5ba74..432edd56 100644 --- a/crates/rake/src/platform/notifications/browser.rs +++ b/crates/rake/src/platform/notifications/browser.rs @@ -81,6 +81,7 @@ impl Drop for Host { pub(super) fn install(platform: &Platform) -> Host { let activations = std::rc::Rc::downgrade(&platform.activations); let notifications = std::rc::Rc::downgrade(&platform.notifications); + let shortcuts = platform.shortcuts.clone(); let activate = Closure::new(move |tag: String| { if let (Some(activations), Some(notifications)) = (activations.upgrade(), notifications.upgrade()) @@ -91,6 +92,7 @@ pub(super) fn install(platform: &Platform) -> Host { let platform = Platform { activations, notifications, + shortcuts: shortcuts.clone(), }; let _ = platform.receive_open_url(payload.as_str()); } diff --git a/crates/rake/src/platform/shortcuts.rs b/crates/rake/src/platform/shortcuts.rs new file mode 100644 index 00000000..4ae06135 --- /dev/null +++ b/crates/rake/src/platform/shortcuts.rs @@ -0,0 +1,316 @@ +//! UI dispatch and application lifetime for native shortcut registrations. +#[cfg(feature = "gpui")] +use super::Error; +use super::{Capability, PermissionState, Platform, Request}; + +/// Global shortcut service. Enable `global-shortcuts` (also enabled by `tray`). +#[derive(Clone, Debug)] +pub struct GlobalShortcuts(std::rc::Rc>); + +impl Default for GlobalShortcuts { + fn default() -> Self { + let supported = cfg!(all( + feature = "global-shortcuts", + any(target_os = "macos", target_os = "windows") + )); + + Self(std::rc::Rc::new(std::cell::Cell::new(supported))) + } +} + +impl Platform { + /// Returns the global shortcut service, including on unsupported hosts. + pub fn global_shortcuts(&self) -> GlobalShortcuts { + self.shortcuts.clone() + } +} + +impl GlobalShortcuts { + pub(super) fn capability(&self) -> Capability { + Capability { + supported: self.0.get(), + permission: if cfg!(target_os = "linux") { + PermissionState::Unknown + } else { + PermissionState::NotRequired + }, + requires_user_gesture: false, + } + } +} + +impl GlobalShortcuts { + /// Queries the current native session, including Wayland portal availability. + /// Does not register keys or request permission. + pub fn available(&self) -> Request { + #[cfg(feature = "global-shortcuts")] + let supported = self.0.clone(); + + Box::pin(async move { + #[cfg(feature = "global-shortcuts")] + { + supported.set(rake_shortcuts::available().await); + + Ok(supported.get()) + } + + #[cfg(not(feature = "global-shortcuts"))] + Ok(false) + }) + } +} + +#[cfg(feature = "gpui")] +pub use ui::GlobalShortcut; + +#[cfg(feature = "gpui")] +mod ui { + use super::*; + + /// An owned shortcut. Drop or `unregister` stops callbacks and releases the key. + pub struct GlobalShortcut { + #[cfg(feature = "global-shortcuts")] + _quit: gpui::Subscription, + #[cfg(feature = "global-shortcuts")] + inner: std::rc::Rc>, + } + + impl GlobalShortcut { + /// Releases the native registration and awaits its cleanup receipt. + /// + /// # Errors + /// Returns a native cleanup failure; repeat calls are harmless. + pub fn unregister(&mut self) -> Request<()> { + #[cfg(feature = "global-shortcuts")] + return stop(&self.inner); + + #[cfg(not(feature = "global-shortcuts"))] + Box::pin(async { Ok(()) }) + } + } + + impl GlobalShortcuts { + /// Registers a keystroke using the tray accelerator grammar. The callback + /// runs on the UI thread, including while another application is focused. + /// Await in owned work; keep the returned handle alive. App quit releases + /// even retained handles. Dropping the request cancels pending registration. + /// + /// # Errors + /// Reports unsupported hosts, invalid keys, conflicts, permission denial + /// and native failures. No fallback keystroke is registered. + pub fn register( + &self, + accelerator: &str, + callback: impl FnMut(&mut gpui::App) + 'static, + cx: &mut gpui::App, + ) -> Request { + #[cfg(feature = "global-shortcuts")] + { + use std::{ + cell::{Cell, RefCell}, + rc::Rc, + }; + + let (cancel, cancellation) = futures::channel::oneshot::channel::<()>(); + let mut cancel = Some(cancel); + let (settle, settled) = futures::channel::oneshot::channel::<()>(); + let mut settled = Some(settled); + let closed = Rc::new(Cell::new(false)); + + let registration = Rc::new(RefCell::new(Registration { + shortcut: None, + task: None, + })); + + let weak = Rc::downgrade(®istration); + let quitting = closed.clone(); + + let quit = cx.on_app_quit(move |_| { + quitting.set(true); + cancel.take(); + let pending = settled.take(); + let cleanup = weak.upgrade().map(|inner| stop(&inner)); + + async move { + if let Some(pending) = pending { + let _ = pending.await; + } + + if let Some(cleanup) = cleanup + && let Err(error) = cleanup.await + { + crate::error!(%error, "global shortcut cleanup failed"); + } + } + }); + + let accelerator = accelerator.to_owned(); + let (send, receive) = futures::channel::oneshot::channel(); + + let task = cx.spawn(async move |cx| { + let result = async { + let mut shortcut = { + use futures::FutureExt; + + let registration = + rake_shortcuts::Shortcut::register(&accelerator).fuse(); + + let cancellation = cancellation.fuse(); + + futures::pin_mut!(registration, cancellation); + futures::select! { + result = registration => result.map_err(error)?, + _ = cancellation => return Err(Error::Unavailable { + operation: "global shortcut", + message: "application has quit".into(), + }), + } + }; + + if closed.get() { + shortcut.unregister().await.map_err(error)?; + + return Err(Error::Unavailable { + operation: "global shortcut", + message: "application has quit".into(), + }); + } + + let events = shortcut.take_events(); + let driver = cx.update(|cx| dispatch(events, callback, cx)); + + *registration.borrow_mut() = Registration { + shortcut: Some(shortcut), + task: Some(driver), + }; + + Ok(GlobalShortcut { + inner: registration, + _quit: quit, + }) + } + .await; + + let _ = send.send(result); + let _ = settle.send(()); + }); + + Box::pin(async move { + let _task = task; + + receive.await.map_err(|_| Error::Unavailable { + operation: "global shortcut", + message: "registration task stopped".into(), + })? + }) + } + + #[cfg(not(feature = "global-shortcuts"))] + { + let _ = (accelerator, callback, cx); + + Box::pin(async { Err(Error::Unsupported("global shortcuts")) }) + } + } + } + + #[cfg(feature = "global-shortcuts")] + struct Registration { + shortcut: Option, + task: Option>, + } + + #[cfg(feature = "global-shortcuts")] + fn dispatch( + mut events: futures::channel::mpsc::Receiver<()>, + mut callback: impl FnMut(&mut gpui::App) + 'static, + cx: &mut gpui::App, + ) -> gpui::Task<()> { + cx.spawn(async move |cx| { + use futures::StreamExt; + + while events.next().await.is_some() { + cx.update(&mut callback); + } + }) + } + + #[cfg(feature = "global-shortcuts")] + fn stop(inner: &std::cell::RefCell) -> Request<()> { + let mut registration = inner.borrow_mut(); + + registration.task.take(); + let shortcut = registration.shortcut.take(); + + Box::pin(async move { + if let Some(mut shortcut) = shortcut { + shortcut.unregister().await.map_err(error)?; + } + + Ok(()) + }) + } + + #[cfg(feature = "global-shortcuts")] + fn error(error: rake_shortcuts::Error) -> Error { + match error { + rake_shortcuts::Error::Unsupported => Error::Unsupported("global shortcuts"), + rake_shortcuts::Error::InvalidInput(message) => Error::InvalidInput(message), + rake_shortcuts::Error::Conflict => Error::ShortcutConflict, + rake_shortcuts::Error::PermissionDenied => Error::PermissionDenied("global shortcuts"), + rake_shortcuts::Error::Native(message) => Error::Unavailable { + operation: "global shortcut", + message, + }, + } + } + + #[cfg(all(test, feature = "global-shortcuts", feature = "view-test-support"))] + mod tests { + //! Covers: UI-thread dispatch and cancellation of queued activations. + //! Real: GPUI foreground scheduler and registration owner. Doubles: native events. + //! Requires: no native shortcut registration or graphical session. + use super::*; + + use std::{ + cell::{Cell, RefCell}, + rc::Rc, + }; + + #[gpui::test] + fn unregister_stops_queued_callbacks(cx: &mut gpui::TestAppContext) { + let (mut sender, events) = futures::channel::mpsc::channel(1); + let calls = Rc::new(Cell::new(0)); + let count = calls.clone(); + let ui_thread = std::thread::current().id(); + + let task = cx.update(|cx| { + dispatch( + events, + move |_| { + assert_eq!(std::thread::current().id(), ui_thread); + count.set(count.get() + 1); + }, + cx, + ) + }); + + let registration = RefCell::new(Registration { + shortcut: None, + task: Some(task), + }); + + sender.try_send(()).unwrap(); + cx.run_until_parked(); + assert_eq!(calls.get(), 1); + + sender.try_send(()).unwrap(); + futures::executor::block_on(stop(®istration)).unwrap(); + cx.run_until_parked(); + + assert_eq!(calls.get(), 1); + assert!(sender.try_send(()).is_err()); + futures::executor::block_on(stop(®istration)).unwrap(); + } + } +} diff --git a/crates/rake/tests/platform.rs b/crates/rake/tests/platform.rs index 704de4f7..0802245c 100644 --- a/crates/rake/tests/platform.rs +++ b/crates/rake/tests/platform.rs @@ -172,3 +172,12 @@ fn headless_notifications_report_unsupported_without_prompting() { Err(Error::Unsupported(_)) )); } + +#[cfg(not(feature = "global-shortcuts"))] +#[test] +fn global_shortcuts_are_explicitly_unavailable_without_the_feature() { + let platform = Platform::default(); + + assert!(!platform.capabilities().global_shortcuts.supported); + assert!(!block_on(platform.global_shortcuts().available()).unwrap()); +} diff --git a/docs/platform-services.md b/docs/platform-services.md index 63d7f493..a72aa6e1 100644 --- a/docs/platform-services.md +++ b/docs/platform-services.md @@ -65,6 +65,8 @@ services. Browser/headless GUI calls are explicit errors. See [tray icons](tray. See [OS notifications](notifications.md) for permission results, URL payloads, packaging requirements and the portable Foundation example. +## File drops + File drops reuse `FileHandle::read(max_bytes)` and its size and regular-file validation. `FileHandle::from_drop(&gpui::ExternalPaths)` accepts exactly one native path without reading on the UI thread. Empty and multi-file drops fail. @@ -77,3 +79,45 @@ handle through `FileHandle`, with the same bounded read as `pick_file`; it never exposes a synthetic path. Empty or multi-file drops report `InvalidInput`. Dropping the subscription removes the DOM listeners. Drag-over outlines the canvas; retain an accessible target label and the import button for keyboard use. + +## Global shortcuts + +Enable `global-shortcuts`, or `tray` which includes it. Call +`platform().global_shortcuts().register("Ctrl+Alt+k", callback, cx)` from the UI +thread and await its request in application-owned work. The callback receives +`&mut gpui::App` on the UI thread and can dispatch an application command or call +`rake::tray::toggle_popup`. The tray example toggles its rich popup this way. +Keep the returned `GlobalShortcut` alive. Drop stops callbacks and unregisters; +`unregister()` returns an awaitable cleanup receipt and can be called repeatedly. +App quit releases registrations even if their handles remain alive. Cancellation +of a pending registration releases any acquired resources. + +Accelerators reuse `rake-tray::Accelerator`: one printable key with unique +`Ctrl`, `Alt`/`Option`, `Shift`, `Super`/`Cmd` modifiers. A global shortcut must +include Ctrl, Alt or Super. Invalid keys, native failures, permission denial and +`platform::Error::ShortcutConflict` are observable errors; no alternative key is +silently registered. Repeated presses may be coalesced while the UI is busy. + +- macOS uses Carbon event hotkeys without Accessibility or Input Monitoring + permission. Printable keys use the current keyboard layout, including implicit + Shift for symbols. Keys absent from the layout and named keys such as Enter are + rejected. Layout changes require re-registration. System-reserved shortcuts can fail. +- Windows uses `RegisterHotKey` on a message-only window in the UI message pump. + ASCII keys are mapped through the current keyboard layout. Held-key repeat is + disabled. OS-reserved combinations and shortcuts owned by other apps can fail. +- Linux X11 uses passive key grabs on a private connection. ASCII keys use the + current layout; Alt and Super mean Mod1 and Mod4. Caps Lock and Num Lock are + handled. Layout/modifier-map changes require unregistering and registering again. +- Wayland uses the GlobalShortcuts desktop portal, never an XWayland grab. The + compositor may prompt, deny access, or let the user change the preferred binding; + the portal owns conflict resolution and user-approved bindings. Closing the + private D-Bus connection ends the session on unregister/drop, including pending + authorization. A missing portal returns Unsupported. Rake never bypasses it. +- Web, headless builds and hosts without the feature return explicit Unsupported. + `capabilities().global_shortcuts` reports support. On Linux it starts false; + await `global_shortcuts().available()` to refresh that shared capability snapshot + without prompting. Availability is no guarantee that a requested key is free. + +Native registration, conflict and cleanup probes run in macOS/Windows CI and +under an isolated X11 display in Linux CI. They do not establish real key presses, +Wayland compositor authorization, or cross-application focus behavior. diff --git a/docs/tray.md b/docs/tray.md index e01df3c5..7bc989a7 100644 --- a/docs/tray.md +++ b/docs/tray.md @@ -144,7 +144,8 @@ command queue. single printable key. AppKit installs native menu equivalents. SNI exports the shortcut for the host to interpret. Windows rejects accelerators: the pinned GPUI message pump provides no supported TranslateAccelerator hook. A displayed label -would not establish execution. These APIs never register global shortcuts. +would not establish execution. Tray menu accelerators remain menu-scoped. For system-wide activation, use the +separate [global shortcut service](platform-services.md#global-shortcuts). ## Reopen the main window diff --git a/examples/tray/src/main.rs b/examples/tray/src/main.rs index a309da30..6bf17c14 100644 --- a/examples/tray/src/main.rs +++ b/examples/tray/src/main.rs @@ -21,6 +21,7 @@ struct Model { mounts: Cell, block_quit: Cell, events: RefCell>, + shortcut: RefCell>, } struct Panel { @@ -38,6 +39,7 @@ impl Render for Panel { gpui::div().size_full().bg(gpui::rgb(0x14202b)).text_color(gpui::rgb(0xf1f5f9)).p_6().flex().flex_col().gap_3() .child("Rake tray workbench") + .child("Ctrl+Alt+K toggles the rich popup from any application") .child(format!("Backend: {capabilities} · Progress: {}%", self.model.progress.get())) .child(gpui::div().id("increment").cursor_pointer().child("Increment progress / update icon").on_click(cx.listener(|this, _, _, cx| { let _ = this.runtime.client().and_then(|client| client.execute(Increment).map_err(|_| rake::router::OperationError::InvalidOptions)); @@ -317,6 +319,38 @@ fn main() -> Result<(), Box> { let outcome = Rc::new(RefCell::new(None)); + let shortcut_model = model.clone(); + + let app = app.background(move |runtime, cx| { + let shortcuts = runtime.services().platform().global_shortcuts(); + let callback_model = shortcut_model.clone(); + + let request = shortcuts.register( + "Ctrl+Alt+k", + move |cx| { + if let Err(error) = toggle_popup("status", cx) { + callback_model.events.borrow_mut().push(error.to_string()); + rake::error!(%error, "global shortcut popup toggle failed"); + } + }, + cx, + ); + + cx.spawn(async move |cx| match request.await { + Ok(shortcut) => *shortcut_model.shortcut.borrow_mut() = Some(shortcut), + Err(error) => { + shortcut_model.events.borrow_mut().push(error.to_string()); + rake::error!(%error, "global shortcut registration failed"); + cx.update(|cx| { + if let Err(error) = rake::show_main_window(cx) { + rake::error!(%error, "shortcut error window could not open"); + } + }); + } + }) + .detach(); + }); + let app = if std::env::args().any(|arg| arg == "--probe") { let outcome = outcome.clone();