Visual Studio Code, rebuilt in Rust
Rust
feat(linux): register system-wide keybindings as X11 key grabs
rokarturedf01b38e7ac
diff --git a/native/crates/app/Cargo.toml b/native/crates/app/Cargo.tomlindex 96cacd2d35f..9f9ebf12a5b 100644--- a/native/crates/app/Cargo.toml+++ b/native/crates/app/Cargo.toml@@ -62,7 +62,7 @@ rcgen = { version = "0.14", default-features = false, features = ["crypto", "pemwebkit2gtk = { version = "2.0", features = ["v2_40"] }x11 = { version = "2", features = ["xlib"] }# The x11rb and xkbcommon gpui_linux's X11 backend uses.-x11rb = { version = "0.13", features = ["allow-unsafe-code", "xkb"] }+x11rb = { version = "0.13", features = ["allow-unsafe-code", "xkb", "xtest"] }xkbcommon = { version = "0.8", features = ["x11"] }[build-dependencies]diff --git a/native/crates/app/src/keybindings.rs b/native/crates/app/src/keybindings.rsindex b6b4456d671..437c1d08cb4 100644--- a/native/crates/app/src/keybindings.rs+++ b/native/crates/app/src/keybindings.rs@@ -271,7 +271,6 @@ const NUMPAD_0: usize = 98;const NUMPAD_DIVIDE: usize = 113;/// The scan code of the key's US position, as `SCAN_CODES` names it (`keya`, `arrowup`).-#[cfg(target_os = "macos")]pub fn us_scan_code(key: usize) -> Option<&'static str> {SCAN_CODES.iter().find(|(_, scan_key)| *scan_key == key).map(|(name, _)| *name)}diff --git a/native/crates/app/src/system_wide_keybindings.rs b/native/crates/app/src/system_wide_keybindings.rsindex f46e32a4b49..63c011235ec 100644--- a/native/crates/app/src/system_wide_keybindings.rs+++ b/native/crates/app/src/system_wide_keybindings.rs@@ -1,7 +1,7 @@//! System-wide keybindings: `"systemWide": true` in keybindings.json registers the key as an OS global shortcut that//! runs its command while another application is active. systemWideKeybindings.ts selects the bindings,//! globalKeybindingsMainService.ts keeps the OS registrations in step with them, and `HotKeys` registers with-//! Carbon's RegisterEventHotKey, as Electron's globalShortcut does on macOS.+//! Carbon's RegisterEventHotKey on macOS and X11 key grabs on Linux, as Electron's globalShortcut does.use std::collections::HashSet;diff --git a/native/crates/app/src/system_wide_keybindings/linux.rs b/native/crates/app/src/system_wide_keybindings/linux.rsindex 63841f836e7..78439acb89f 100644--- a/native/crates/app/src/system_wide_keybindings/linux.rs+++ b/native/crates/app/src/system_wide_keybindings/linux.rs@@ -1,26 +1,94 @@-//! No global shortcuts on Linux yet: every registration fails, so each binding is reported as not registered.-//! Electron's globalShortcut registers X11 key grabs there, and portal GlobalShortcuts on Wayland.+//! Chromium's X11 global accelerator listener (`XGlobalShortcutListener`), which Electron's globalShortcut uses on+//! Linux: a key grab on the root window per accelerator, with and without Caps Lock and Num Lock. Without an X+//! server every registration fails, so each binding is reported as not registered.++use std::collections::HashMap;+use std::sync::{Arc, Mutex};use futures::channel::mpsc::UnboundedSender;+use x11rb::connection::Connection;+use x11rb::protocol::Event;+use x11rb::protocol::xproto::{ConnectionExt as _, GrabMode, ModMask, Window};+use x11rb::rust_connection::RustConnection;use super::{Candidate, ShortcutRegistry};+use crate::keybindings;++const CAPS_LOCK: u16 = 1 << 1;+const NUM_LOCK: u16 = 1 << 4;+/// Caps Lock and Num Lock (Mod2) do not change the accelerator, so each grab is repeated with them.+const LOCK_MASKS: [u16; 4] = [0, CAPS_LOCK, NUM_LOCK, CAPS_LOCK | NUM_LOCK];-pub struct HotKeys;+/// The grabs of one X connection; a press of a grabbed key sends its id to the receiver `HotKeys::new` was given.+pub struct HotKeys {+ x11: Option<(Arc<RustConnection>, Window)>,+ grabs: Arc<Mutex<HashMap<(u8, u16), u32>>>,+ accelerators: HashMap<String, (u32, (u8, u16))>,+ next_id: u32,+}impl HotKeys {- pub fn new(_presses: UnboundedSender<u32>) -> HotKeys {- HotKeys+ /// Connects to the X server and reads its key presses on a thread that lives as long as the process.+ pub fn new(presses: UnboundedSender<u32>) -> HotKeys {+ let grabs = Arc::new(Mutex::new(HashMap::new()));+ let x11 = RustConnection::connect(None).ok().map(|(connection, screen)| {+ let root = connection.setup().roots[screen].root;+ let connection = Arc::new(connection);+ let (events, grabs) = (connection.clone(), grabs.clone());+ std::thread::spawn(move || read_presses(&events, &grabs, &presses));+ (connection, root)+ });+ HotKeys { x11, grabs, accelerators: HashMap::new(), next_id: 1 }}- pub fn accelerator(&self, _id: u32) -> Option<&str> {- None+ pub fn accelerator(&self, id: u32) -> Option<&str> {+ self.accelerators.iter().find(|(_, (grab_id, _))| *grab_id == id).map(|(accelerator, _)| accelerator.as_str())}}impl ShortcutRegistry for HotKeys {- fn register(&mut self, _binding: &Candidate) -> bool {- false+ fn register(&mut self, binding: &Candidate) -> bool {+ let Some((connection, root)) = &self.x11 else { return false };+ let chord = &binding.chord;+ // Electron maps the accelerator's key to the keycode of its US position.+ let Some(key_code) = keybindings::us_scan_code(chord.key).and_then(crate::keyboard_layout::xkb_key_code) else { return false };+ let Ok(key_code) = u8::try_from(key_code) else { return false };+ let modifiers = [(chord.ctrl, ModMask::CONTROL), (chord.shift, ModMask::SHIFT), (chord.alt, ModMask::M1), (chord.meta, ModMask::M4)];+ let modifiers = modifiers.iter().filter(|(pressed, _)| *pressed).fold(0, |all, (_, modifier)| all | u16::from(*modifier));+ for (index, lock) in LOCK_MASKS.iter().enumerate() {+ let grab = connection.grab_key(false, *root, ModMask::from(modifiers | lock), key_code, GrabMode::ASYNC, GrabMode::ASYNC);+ // Another client holding the key answers BadAccess.+ if grab.map_err(|_| ()).and_then(|cookie| cookie.check().map_err(|_| ())).is_err() {+ for granted in &LOCK_MASKS[..index] {+ let _ = connection.ungrab_key(key_code, *root, ModMask::from(modifiers | granted));+ }+ let _ = connection.flush();+ return false;+ }+ }+ let id = self.next_id;+ self.next_id += 1;+ self.grabs.lock().unwrap().insert((key_code, modifiers), id);+ self.accelerators.insert(binding.accelerator.clone(), (id, (key_code, modifiers)));+ true}- fn unregister(&mut self, _accelerator: &str) {}+ fn unregister(&mut self, accelerator: &str) {+ let (Some((connection, root)), Some((_, (key_code, modifiers)))) = (&self.x11, self.accelerators.remove(accelerator)) else { return };+ self.grabs.lock().unwrap().remove(&(key_code, modifiers));+ for lock in LOCK_MASKS {+ let _ = connection.ungrab_key(key_code, *root, ModMask::from(modifiers | lock));+ }+ let _ = connection.flush();+ }+}++fn read_presses(connection: &RustConnection, grabs: &Mutex<HashMap<(u8, u16), u32>>, presses: &UnboundedSender<u32>) {+ while let Ok(event) = connection.wait_for_event() {+ let Event::KeyPress(press) = event else { continue };+ let modifiers = u16::from(press.state) & !(CAPS_LOCK | NUM_LOCK);+ if let Some(id) = grabs.lock().unwrap().get(&(press.detail, modifiers)) {+ let _ = presses.unbounded_send(*id);+ }+ }}diff --git a/native/crates/app/src/system_wide_keybindings/tests.rs b/native/crates/app/src/system_wide_keybindings/tests.rsindex 91780825aaf..e711be5c17a 100644--- a/native/crates/app/src/system_wide_keybindings/tests.rs+++ b/native/crates/app/src/system_wide_keybindings/tests.rs@@ -155,3 +155,42 @@ fn a_trigger_of_a_binding_without_args_passes_none() {service.update(vec![binding("Control+Cmd+A", "cmd")]);assert_eq!(service.binding("Control+Cmd+A").map(|binding| (binding.command.as_str(), binding.args.clone())), Some(("cmd", None)));}++/// Chromium's X11 listener: a grab another client holds fails, a press of a grabbed key (with Num Lock on too)+/// reaches the receiver. Runs under Xvfb; without an X display every registration fails.+#[cfg(target_os = "linux")]+#[test]+fn x11_grabs_fail_when_taken_and_report_presses() {+ use futures::StreamExt as _;+ use x11rb::connection::Connection as _;+ use x11rb::protocol::xproto::{ConnectionExt as _, GrabMode, ModMask};+ use x11rb::protocol::xtest::ConnectionExt as _;+ use x11rb::wrapper::ConnectionExt as _;++ let (sender, mut presses) = futures::channel::mpsc::unbounded();+ let mut hot_keys = super::HotKeys::new(sender);+ // Not Ctrl+Alt+F<n>: XKB's XF86Switch_VT actions keep those presses from every client.+ let k = candidate("Ctrl+Alt+K", "ctrl+alt+k", "cmd", None, false);+ if std::env::var_os("DISPLAY").is_none() {+ assert!(!hot_keys.register(&k));+ return;+ }+ let (other, screen) = x11rb::connect(None).unwrap();+ let root = other.setup().roots[screen].root;+ let j = candidate("Ctrl+Alt+J", "ctrl+alt+j", "cmd", None, false);+ let j_key = crate::keyboard_layout::xkb_key_code("KeyJ").unwrap() as u8;+ other.grab_key(false, root, ModMask::CONTROL | ModMask::M1, j_key, GrabMode::ASYNC, GrabMode::ASYNC).unwrap().check().unwrap();+ assert!(!hot_keys.register(&j));++ assert!(hot_keys.register(&k));+ let keys = ["ControlLeft", "AltLeft", "NumLock", "KeyK"].map(|code| crate::keyboard_layout::xkb_key_code(code).unwrap() as u8);+ for key in keys {+ other.xtest_fake_input(x11rb::protocol::xproto::KEY_PRESS_EVENT, key, 0, root, 0, 0, 0).unwrap();+ }+ for key in keys.into_iter().rev() {+ other.xtest_fake_input(x11rb::protocol::xproto::KEY_RELEASE_EVENT, key, 0, root, 0, 0, 0).unwrap();+ }+ other.sync().unwrap();+ let id = futures::executor::block_on(presses.next()).unwrap();+ assert_eq!(hot_keys.accelerator(id), Some("Ctrl+Alt+K"));+}diff --git a/native/crates/app/src/workbench/keyboard.rs b/native/crates/app/src/workbench/keyboard.rsindex 20e637f823e..3d1168e6059 100644--- a/native/crates/app/src/workbench/keyboard.rs+++ b/native/crates/app/src/workbench/keyboard.rs@@ -167,7 +167,7 @@ impl Workbench {}}- /// Registers the system-wide keybindings with macOS and runs the command of each press, as the+ /// Registers the system-wide keybindings with the OS and runs the command of each press, as the/// `vscode:runAction` request of globalKeybindingsMainService.ts.pub fn start_system_wide_keybindings(&mut self, window: &mut Window, cx: &mut Context<Self>) {let (sender, mut presses) = futures::channel::mpsc::unbounded();diff --git a/port/ledger.md b/port/ledger.mdindex 7bb5a1cf1e6..24078fff3ef 100644--- a/port/ledger.md+++ b/port/ledger.md@@ -47,7 +47,7 @@ Status: `open`, `in progress`, `waiting on Artur`, `later` (postponed), `done`,| M23 Linux | app/src/clipboard.rs:97 | open | [linux M] clipboard file lists, HTML and other custom formats, the find text. Linux shows now: text only; the other formats read empty. | || M23 Linux | app/src/workbench/themes.rs:47 | done | [linux S] host color scheme and high contrast from the xdg-desktop-portal Settings. | GPUI's `window_appearance()`, which gpui_linux reads from the portal's `color-scheme`; high contrast stays off, as Chromium on Linux || M23 Linux | app/src/dialog.rs:63 | open | [linux M] native message box (GTK). Linux shows now: the custom workbench dialog. | |-| M23 Linux | app/src/system_wide_keybindings/linux.rs:20 | open | [linux M] system-wide keybindings (xdg-desktop-portal GlobalShortcuts, X11 grabs). Linux shows now: registration fails. | |+| M23 Linux | app/src/system_wide_keybindings/linux.rs:31 | open | [linux M] system-wide keybindings through the xdg-desktop-portal GlobalShortcuts in a Wayland session. Linux shows now: X11 key grabs (`x11_grabs_fail_when_taken_and_report_presses` under Xvfb), which under Wayland see only the keys XWayland windows get. | || M23 Linux | app/src/power/linux.rs:8 | done | [linux M] powerMonitor: idle time, lock state, battery, sleep and resume events, power save blockers (logind). | `cargo test -p app power::` on Linux; the D-Bus calls (logind, UPower, ScreenSaver, Mutter) not run on a desktop || M23 Linux | app/src/accessibility_signals.rs:119 | done | [linux S] accessibility signal sounds. | `pw-play`, else `paplay`; not run with audio in the container || M23 Linux | app/src/metered_connection.rs:57 | done | [linux S] metered connection (NetworkManager). | NetworkManager `Metered` over D-Bus; not run on a desktop |