Visual Studio Code, rebuilt in Rust
Rust
//! 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 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};
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];
/// 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 KeyGrabs {
/// Connects to the X server and reads its key presses on a thread that lives as long as the process.
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;
let connection = Arc::new(connection);
let (events, grabs) = (connection.clone(), grabs.clone());
std::thread::spawn(move || read_presses(&events, &grabs, &presses));
(connection, root)
});
KeyGrabs { x11, grabs, accelerators: HashMap::new(), next_id: 1 }
}
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) {
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);
}
}
}
/// 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("+"))
}