Visual Studio Code, rebuilt in Rust
Rust
feat(linux): bind system-wide keybindings through the portal on Wayland
rokarturd3614de5a48d
diff --git a/native/crates/app/Cargo.toml b/native/crates/app/Cargo.tomlindex 9f9ebf12a5b..e3a14277671 100644--- a/native/crates/app/Cargo.toml+++ b/native/crates/app/Cargo.toml@@ -53,7 +53,7 @@ security-framework = "3"[target.'cfg(target_os = "linux")'.dependencies]# The zbus gpui_linux's ashpd and oo7 use.zbus = { version = "5", default-features = false, features = ["async-io", "blocking-api"] }-ashpd = { version = "0.13", default-features = false, features = ["async-io", "file_chooser", "raw_handle", "wayland"] }+ashpd = { version = "0.13", default-features = false, features = ["async-io", "file_chooser", "global_shortcuts", "raw_handle", "wayland"] }async-openssl = "0.2"gdkx11 = "0.18"gtk = "0.18"diff --git a/native/crates/app/src/system_wide_keybindings.rs b/native/crates/app/src/system_wide_keybindings.rsindex 63c011235ec..910b7b446c5 100644--- a/native/crates/app/src/system_wide_keybindings.rs+++ b/native/crates/app/src/system_wide_keybindings.rs@@ -1,7 +1,8 @@//! 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 on macOS and X11 key grabs on Linux, as Electron's globalShortcut does.+//! Carbon's RegisterEventHotKey on macOS and X11 key grabs or the GlobalShortcuts portal 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 78439acb89f..cfd0fb8b491 100644--- a/native/crates/app/src/system_wide_keybindings/linux.rs+++ b/native/crates/app/src/system_wide_keybindings/linux.rs@@ -1,11 +1,15 @@-//! 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.+//! Chromium's global accelerator listeners, which Electron's globalShortcut uses on Linux. In an X11 session+//! (`XGlobalShortcutListener`) each accelerator is a key grab on the root window, with and without Caps Lock and+//! Num Lock; without an X server every registration fails. In a Wayland session (`GlobalAcceleratorListenerLinux`)+//! the accelerators are bound as one set through the xdg-desktop-portal GlobalShortcuts interface.use std::collections::HashMap;use std::sync::{Arc, Mutex};-use futures::channel::mpsc::UnboundedSender;+use ashpd::desktop::Session;+use ashpd::desktop::global_shortcuts::{GlobalShortcuts, NewShortcut};+use futures::StreamExt as _;+use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender};use x11rb::connection::Connection;use x11rb::protocol::Event;use x11rb::protocol::xproto::{ConnectionExt as _, GrabMode, ModMask, Window};@@ -19,17 +23,57 @@ 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];-/// 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 {+/// The registry of the session GPUI runs in; a press of a registered accelerator sends its id to the receiver+/// `HotKeys::new` was given.+pub enum HotKeys {+ X11(KeyGrabs),+ Portal(PortalShortcuts),+}++impl HotKeys {+ pub fn new(presses: UnboundedSender<u32>) -> HotKeys {+ if gpui::guess_compositor() == "Wayland" {+ return HotKeys::Portal(PortalShortcuts::new(zbus::Connection::session(), presses));+ }+ HotKeys::X11(KeyGrabs::new(presses))+ }++ pub fn accelerator(&self, id: u32) -> Option<&str> {+ let accelerators = match self {+ HotKeys::X11(grabs) => grabs.accelerators.iter().find(|(_, (grab_id, _))| *grab_id == id).map(|(accelerator, _)| accelerator),+ HotKeys::Portal(portal) => portal.accelerators.iter().find(|(_, shortcut_id)| **shortcut_id == id).map(|(accelerator, _)| accelerator),+ };+ accelerators.map(String::as_str)+ }+}++impl ShortcutRegistry for HotKeys {+ fn register(&mut self, binding: &Candidate) -> bool {+ match self {+ HotKeys::X11(grabs) => grabs.register(binding),+ HotKeys::Portal(portal) => portal.register(binding),+ }+ }++ fn unregister(&mut self, accelerator: &str) {+ match self {+ HotKeys::X11(grabs) => grabs.unregister(accelerator),+ HotKeys::Portal(portal) => portal.unregister(accelerator),+ }+ }+}++/// The grabs of one X connection.+pub struct KeyGrabs {x11: Option<(Arc<RustConnection>, Window)>,grabs: Arc<Mutex<HashMap<(u8, u16), u32>>>,accelerators: HashMap<String, (u32, (u8, u16))>,next_id: u32,}-impl HotKeys {+impl KeyGrabs {/// 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 {+ fn new(presses: UnboundedSender<u32>) -> KeyGrabs {let grabs = Arc::new(Mutex::new(HashMap::new()));let x11 = RustConnection::connect(None).ok().map(|(connection, screen)| {let root = connection.setup().roots[screen].root;@@ -38,15 +82,9 @@ impl HotKeys {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> {- self.accelerators.iter().find(|(_, (grab_id, _))| *grab_id == id).map(|(accelerator, _)| accelerator.as_str())+ KeyGrabs { x11, grabs, accelerators: HashMap::new(), next_id: 1 }}-}-impl ShortcutRegistry for HotKeys {fn register(&mut self, binding: &Candidate) -> bool {let Some((connection, root)) = &self.x11 else { return false };let chord = &binding.chord;@@ -92,3 +130,123 @@ fn read_presses(connection: &RustConnection, grabs: &Mutex<HashMap<(u8, u16), u3}}}++/// The accelerators bound through the portal. A registration always succeeds, as Chromium's listener handles it+/// externally: the portal, and the user in its dialog, decide which shortcuts fire.+pub struct PortalShortcuts {+ accelerators: HashMap<String, u32>,+ changes: UnboundedSender<HashMap<String, u32>>,+ next_id: u32,+}++impl PortalShortcuts {+ /// Binds each new set of accelerators on a thread that lives as long as the process.+ pub(super) fn new(connection: impl Future<Output = zbus::Result<zbus::Connection>> + Send + 'static, presses: UnboundedSender<u32>) -> PortalShortcuts {+ let (changes, wanted) = futures::channel::mpsc::unbounded();+ std::thread::spawn(move || {+ futures::executor::block_on(async move {+ if let Err(error) = bind_portal_shortcuts(connection, wanted, presses).await {+ eprintln!("[GlobalShortcuts] the GlobalShortcuts portal is not available: {error}");+ }+ })+ });+ PortalShortcuts { accelerators: HashMap::new(), changes, next_id: 1 }+ }++ fn register(&mut self, binding: &Candidate) -> bool {+ self.accelerators.insert(binding.accelerator.clone(), self.next_id);+ self.next_id += 1;+ let _ = self.changes.unbounded_send(self.accelerators.clone());+ true+ }++ fn unregister(&mut self, accelerator: &str) {+ self.accelerators.remove(accelerator);+ let _ = self.changes.unbounded_send(self.accelerators.clone());+ }+}++/// `OnCommandsChanged` and `OnActivatedSignal`: a changed set closes the session and binds the set in a new one,+/// waiting for the previous bind (GNOME answers dialogs only in the order they were opened).+async fn bind_portal_shortcuts(connection: impl Future<Output = zbus::Result<zbus::Connection>>, mut wanted: UnboundedReceiver<HashMap<String, u32>>, presses: UnboundedSender<u32>) -> ashpd::Result<()> {+ let portal = GlobalShortcuts::with_connection(connection.await?).await?;+ // shortcut: activations are not matched to the current session's path (ashpd keeps it private), the ids are.+ let mut activated = std::pin::pin!(portal.receive_activated().await?.fuse());+ let mut session: Option<Session<GlobalShortcuts>> = None;+ let mut bound = HashMap::new();+ loop {+ futures::select! {+ accelerators = wanted.next() => {+ let Some(mut accelerators) = accelerators else { return Ok(()) };+ while let Ok(newer) = wanted.try_recv() {+ accelerators = newer;+ }+ if accelerators.len() == bound.len() && accelerators.keys().all(|accelerator| bound.contains_key(accelerator)) {+ bound = accelerators;+ continue;+ }+ if let Some(old) = session.take() {+ let _ = old.close().await;+ }+ bound.clear();+ if accelerators.is_empty() {+ continue;+ }+ match bind_session(&portal, &accelerators).await {+ Ok(new) => (session, bound) = (Some(new), accelerators),+ Err(error) => eprintln!("[GlobalShortcuts] failed to bind shortcuts: {error}"),+ }+ }+ activation = activated.next() => {+ let Some(activation) = activation else { return Ok(()) };+ if let Some(id) = bound.get(activation.shortcut_id()) {+ let _ = presses.unbounded_send(*id);+ }+ }+ }+ }+}++/// `CreateSession`, `OnListShortcuts` and `BindShortcuts`: the shortcuts the portal already stores are kept, and+/// the set is bound only when one of the accelerators is missing from them.+async fn bind_session(portal: &GlobalShortcuts, accelerators: &HashMap<String, u32>) -> ashpd::Result<Session<GlobalShortcuts>> {+ let session = portal.create_session(Default::default()).await?;+ let listed = portal.list_shortcuts(&session, Default::default()).await?.response()?;+ if accelerators.keys().all(|accelerator| listed.shortcuts().iter().any(|shortcut| shortcut.id() == accelerator)) {+ return Ok(session);+ }+ let mut shortcuts: Vec<NewShortcut> = listed.shortcuts().iter().filter(|shortcut| !accelerators.contains_key(shortcut.id())).map(|shortcut| NewShortcut::new(shortcut.id(), shortcut.description())).collect();+ for accelerator in accelerators.keys() {+ // Electron's command description; Electron 43 turns GlobalShortcutsPortalPreferredTrigger on.+ let description = format!("{} shortcut: {accelerator}", crate::product::name_short());+ shortcuts.push(NewShortcut::new(accelerator, description).preferred_trigger(xdg_trigger(accelerator).as_deref()));+ }+ portal.bind_shortcuts(&session, &shortcuts, None, Default::default()).await?.response()?;+ Ok(session)+}++/// xdg_shortcut.cc `AcceleratorToXdgShortcut`: none for a key the XDG shortcuts spec names differently.+pub(super) fn xdg_trigger(accelerator: &str) -> Option<String> {+ let mut parts: Vec<&str> = accelerator.split('+').collect();+ let key = match parts.pop()? {+ key if key.len() == 1 && key.chars().all(|char| char.is_ascii_alphanumeric()) => key.to_ascii_lowercase(),+ key if key.strip_prefix('F').and_then(|number| number.parse::<u8>().ok()).is_some_and(|number| (1..=12).contains(&number)) => key.into(),+ "," => "comma".into(),+ "." => "period".into(),+ "PageUp" => "Prior".into(),+ "PageDown" => "Next".into(),+ "Space" => "space".into(),+ "MediaStop" => "XF86AudioStop".into(),+ "MediaPlayPause" => "XF86AudioPlay".into(),+ key @ ("Home" | "End" | "Insert" | "Delete" | "Left" | "Up" | "Right" | "Down") => key.into(),+ _ => return None,+ };+ let mut trigger = Vec::new();+ for (modifier, xdg) in [("Ctrl", "CTRL"), ("Alt", "ALT"), ("Shift", "SHIFT"), ("Cmd", "LOGO")] {+ if parts.contains(&modifier) {+ trigger.push(xdg.to_string());+ }+ }+ trigger.push(key);+ Some(trigger.join("+"))+}diff --git a/native/crates/app/src/system_wide_keybindings/tests.rs b/native/crates/app/src/system_wide_keybindings/tests.rsindex e711be5c17a..71f60b08aaa 100644--- a/native/crates/app/src/system_wide_keybindings/tests.rs+++ b/native/crates/app/src/system_wide_keybindings/tests.rs@@ -194,3 +194,111 @@ fn x11_grabs_fail_when_taken_and_report_presses() {let id = futures::executor::block_on(presses.next()).unwrap();assert_eq!(hot_keys.accelerator(id), Some("Ctrl+Alt+K"));}++/// xdg_shortcut.cc `AcceleratorToXdgShortcut`.+#[cfg(target_os = "linux")]+#[test]+fn xdg_triggers_name_the_modifiers_in_chromium_order() {+ use super::linux::xdg_trigger;+ assert_eq!(xdg_trigger("Ctrl+Shift+Alt+Cmd+K").as_deref(), Some("CTRL+ALT+SHIFT+LOGO+k"));+ assert_eq!(xdg_trigger("Ctrl+,").as_deref(), Some("CTRL+comma"));+ assert_eq!(xdg_trigger("Alt+PageDown").as_deref(), Some("ALT+Next"));+ assert_eq!(xdg_trigger("Shift+F12").as_deref(), Some("SHIFT+F12"));+ assert_eq!(xdg_trigger("Ctrl+F13"), None);+ assert_eq!(xdg_trigger("Ctrl+["), None);+}++/// Chromium's portal listener in a Wayland session: a registration binds the set with Electron's description and an+/// XDG trigger, and the portal's Activated signal reaches the receiver. Runs against a fake GlobalShortcuts portal+/// on a private bus; without dbus-daemon it returns early.+#[cfg(target_os = "linux")]+#[test]+fn portal_binds_the_accelerators_and_reports_activations() {+ use futures::StreamExt as _;+ use std::io::BufRead as _;+ use zbus::zvariant::{ObjectPath, Value};++ let Ok(mut daemon) = std::process::Command::new("dbus-daemon").args(["--session", "--nofork", "--print-address=1"]).stdout(std::process::Stdio::piped()).spawn() else { return };+ let mut address = String::new();+ std::io::BufReader::new(daemon.stdout.take().unwrap()).read_line(&mut address).unwrap();+ let address = address.trim().to_string();+ let (bound_sender, bound) = std::sync::mpsc::channel();+ let portal = zbus::blocking::connection::Builder::address(address.as_str()).unwrap().name("org.freedesktop.portal.Desktop").unwrap().serve_at("/org/freedesktop/portal/desktop", fake_portal::Portal { bound: bound_sender }).unwrap().build().unwrap();++ let (sender, mut presses) = futures::channel::mpsc::unbounded();+ let client = zbus::connection::Builder::address(address.as_str()).unwrap().build();+ let mut hot_keys = super::HotKeys::Portal(super::linux::PortalShortcuts::new(client, sender));+ assert!(hot_keys.register(&candidate("Ctrl+Alt+K", "ctrl+alt+k", "cmd", None, false)));++ let (session, shortcuts) = bound.recv_timeout(std::time::Duration::from_secs(10)).unwrap();+ let description = format!("{} shortcut: Ctrl+Alt+K", crate::product::name_short());+ assert_eq!(shortcuts, vec![("Ctrl+Alt+K".to_string(), description, Some("CTRL+ALT+k".to_string()))]);+ let session = ObjectPath::try_from(session.as_str()).unwrap();+ portal.emit_signal(None::<&str>, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.GlobalShortcuts", "Activated", &(session, "Ctrl+Alt+K", 0u64, std::collections::HashMap::<&str, Value>::new())).unwrap();+ let id = futures::executor::block_on(presses.next()).unwrap();+ assert_eq!(hot_keys.accelerator(id), Some("Ctrl+Alt+K"));+ daemon.kill().unwrap();+}++/// The org.freedesktop.portal.GlobalShortcuts calls `PortalShortcuts` makes, answered at once on the Request path.+#[cfg(target_os = "linux")]+mod fake_portal {+ use std::collections::HashMap;++ use zbus::message::Header;+ use zbus::names::UniqueName;+ use zbus::zvariant::{ObjectPath, OwnedObjectPath, OwnedValue, Value};++ pub type Shortcut = (String, String, Option<String>);++ pub struct Portal {+ pub bound: std::sync::mpsc::Sender<(String, Vec<Shortcut>)>,+ }++ struct Session;++ #[zbus::interface(name = "org.freedesktop.portal.Session")]+ impl Session {+ fn close(&self) {}+ }++ #[zbus::interface(name = "org.freedesktop.portal.GlobalShortcuts")]+ impl Portal {+ #[zbus(property)]+ fn version(&self) -> u32 {+ 1+ }++ async fn create_session(&self, options: HashMap<String, OwnedValue>, #[zbus(header)] header: Header<'_>, #[zbus(connection)] connection: &zbus::Connection, #[zbus(object_server)] server: &zbus::ObjectServer) -> OwnedObjectPath {+ let sender = header.sender().unwrap();+ let session = format!("/org/freedesktop/portal/desktop/session/{}/{}", client(sender), token(&options, "session_handle_token"));+ server.at(session.as_str(), Session).await.unwrap();+ respond(connection, sender, &options, HashMap::from([("session_handle", Value::from(ObjectPath::try_from(session).unwrap()))])).await+ }++ async fn list_shortcuts(&self, _session: OwnedObjectPath, options: HashMap<String, OwnedValue>, #[zbus(header)] header: Header<'_>, #[zbus(connection)] connection: &zbus::Connection) -> OwnedObjectPath {+ respond(connection, header.sender().unwrap(), &options, HashMap::new()).await+ }++ async fn bind_shortcuts(&self, session: OwnedObjectPath, shortcuts: Vec<(String, HashMap<String, OwnedValue>)>, _parent_window: String, options: HashMap<String, OwnedValue>, #[zbus(header)] header: Header<'_>, #[zbus(connection)] connection: &zbus::Connection) -> OwnedObjectPath {+ let text = |properties: &HashMap<String, OwnedValue>, key: &str| properties.get(key).map(|value| <&str>::try_from(&**value).unwrap().to_string());+ let shortcuts = shortcuts.iter().map(|(id, properties)| (id.clone(), text(properties, "description").unwrap(), text(properties, "preferred_trigger"))).collect();+ self.bound.send((session.to_string(), shortcuts)).unwrap();+ respond(connection, header.sender().unwrap(), &options, HashMap::new()).await+ }+ }++ fn client(sender: &UniqueName) -> String {+ sender.trim_start_matches(':').replace('.', "_")+ }++ fn token(options: &HashMap<String, OwnedValue>, key: &str) -> String {+ <&str>::try_from(&*options[key]).unwrap().to_string()+ }++ async fn respond(connection: &zbus::Connection, sender: &UniqueName<'_>, options: &HashMap<String, OwnedValue>, results: HashMap<&str, Value<'_>>) -> OwnedObjectPath {+ let request = format!("/org/freedesktop/portal/desktop/request/{}/{}", client(sender), token(options, "handle_token"));+ connection.emit_signal(Some(sender.as_str()), request.as_str(), "org.freedesktop.portal.Request", "Response", &(0u32, results)).await.unwrap();+ OwnedObjectPath::try_from(request).unwrap()+ }+}diff --git a/port/ledger.md b/port/ledger.mdindex 4615673f223..795d9d37b9e 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: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/system_wide_keybindings/linux.rs:171 | done | [linux M] system-wide keybindings through the xdg-desktop-portal GlobalShortcuts in a Wayland session. | `cargo gc test -p app system_wide` on Linux under Xvfb: 13 passed, `x11_grabs_fail_when_taken_and_report_presses` and `portal_binds_the_accelerators_and_reports_activations` (a fake portal on a private bus); GNOME's and KDE's portals not run || 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 |diff --git a/port/notes.md b/port/notes.mdindex f4f8b80fadf..03dbe345749 100644--- a/port/notes.md+++ b/port/notes.md@@ -1001,6 +1001,7 @@ What to do (milestone 21, in order):- Updates follow updateService.linux.ts: a found build waits in AvailableForDownload (no metered deferral, no Squirrel read-only check) and Download opens product.json `downloadUrl`, else the update's url, and goes back to Idle. The running build counts as installed when its executable sits beside `resources/app`.- Accessibility signal sounds run `pw-play`, else `paplay` (both decode mp3 through libsndfile 1.1 or later), one process per sound file, killed when the sound replays.- The `code` shell command on Linux links `~/.local/bin/<applicationName>` to the archive's `bin/<applicationName>` without a privilege prompt (upstream has the command on macOS only; a Linux package puts it on PATH itself). Proxy `<local>` adds the request's host to `--noproxy` when it has no dot, curl has no such rule. Machine info reads `/proc/cpuinfo`, `/proc/meminfo` and the cpufreq `scaling_cur_freq`.+- System-wide keybindings (`system_wide_keybindings/linux.rs`) follow Chromium 150's listeners, Electron 43's: in GPUI's X11 session X11 key grabs (Ctrl+Alt+F<n> stays with XKB's VT switch), in its Wayland session the xdg-desktop-portal GlobalShortcuts session `GlobalAcceleratorListenerLinux` keeps. A registration there always succeeds; each changed set closes the session, lists the stored shortcuts and binds them with the set when one is missing, with Electron's description (`<nameShort> shortcut: <accelerator>`) and the `preferred_trigger` Electron's `GlobalShortcutsPortalPreferredTrigger` turns on. Differences: the shortcut id is the accelerator (Chromium hashes a per-profile UUID into it), no parent window is passed (Electron passes none either), and an Activated signal is matched by id, not by session path (ashpd keeps the path private). Tested against a fake portal on a private bus (`portal_binds_the_accelerators_and_reports_activations`); not run against GNOME's or KDE's portal.## Accepted platform differences