Visual Studio Code, rebuilt in Rust
Rust
use std::collections::HashSet;
use std::sync::atomic::{AtomicUsize, Ordering};
use serde_json::json;
use super::{Candidate, GlobalShortcuts, Rejection, Selection, ShortcutRegistry, select};
use crate::keybindings::{Item, parse_keybinding, user_keybindings};
fn user_items(entries: serde_json::Value) -> Vec<Item> {
static FILES: AtomicUsize = AtomicUsize::new(0);
let file = std::env::temp_dir().join(format!("code-gpui-system-wide-{}-{}.json", std::process::id(), FILES.fetch_add(1, Ordering::Relaxed)));
std::fs::write(&file, entries.to_string()).unwrap();
let items = user_keybindings(&file);
std::fs::remove_file(&file).unwrap();
items
}
fn candidate(accelerator: &str, key: &str, command: &str, args: Option<serde_json::Value>, has_when: bool) -> Candidate {
Candidate { accelerator: accelerator.into(), chord: parse_keybinding(key)[0], command: command.into(), args, user_settings_label: key.into(), has_when }
}
fn rejection(command: &str, label: &str) -> Rejection {
Rejection { command: command.into(), user_settings_label: meta(label) }
}
/// The Meta key as this OS names it: Electron's `Cmd` and the label's `cmd` on macOS, `Super` and `win` on Windows.
fn meta(text: &str) -> String {
if cfg!(windows) { text.replace("Cmd", "Super").replace("cmd", "win") } else { text.to_owned() }
}
#[test]
fn selects_only_user_system_wide_single_combo_bindings_and_preserves_args_and_when() {
let mut items = user_items(json!([
{ "key": "ctrl+cmd+a", "command": "workbench.action.openAgentsWindow", "args": { "foo": 1 }, "when": "editorFocus", "systemWide": true },
{ "key": "cmd+b", "command": "noop.notSystemWide" },
{ "key": "cmd+c", "command": "noop.default", "systemWide": true },
{ "key": "cmd+d", "command": "", "systemWide": true },
{ "key": "cmd+e", "command": "noop.stringFlag", "systemWide": "true" },
]));
items[2].is_default = true;
let expected = Selection { candidates: vec![candidate(&meta("Ctrl+Cmd+A"), &meta("ctrl+cmd+a"), "workbench.action.openAgentsWindow", Some(json!({ "foo": 1 })), true)], ..Selection::default() };
assert_eq!(select(&items), expected);
}
#[test]
fn reports_chords_and_single_modifier_bindings_as_unsupported() {
let items = user_items(json!([
{ "key": "cmd+k cmd+c", "command": "noop.chord", "systemWide": true },
{ "key": "shift+shift", "command": "noop.modifier", "systemWide": true },
{ "key": "cmd+numpad0", "command": "noop.numpad", "systemWide": true },
]));
let unsupported = vec![rejection("noop.chord", "cmd+k cmd+c"), rejection("noop.modifier", "shift"), rejection("noop.numpad", "cmd+numpad0")];
assert_eq!(select(&items), Selection { unsupported, ..Selection::default() });
}
#[test]
fn keeps_the_first_binding_on_accelerator_conflicts() {
let items = user_items(json!([
{ "key": "cmd+a", "command": "first.wins", "systemWide": true },
{ "key": "cmd+a", "command": "second.loses", "systemWide": true },
]));
let expected = Selection { candidates: vec![candidate(&meta("Cmd+A"), &meta("cmd+a"), "first.wins", None, false)], duplicates: vec![rejection("second.loses", "cmd+a")], ..Selection::default() };
assert_eq!(select(&items), expected);
}
#[test]
fn accelerators_use_electrons_key_names() {
let accelerator = |key: &str| crate::keybindings::electron_accelerator(&parse_keybinding(key));
assert_eq!(accelerator("ctrl+shift+alt+cmd+up"), Some(meta("Ctrl+Shift+Alt+Cmd+Up")));
assert_eq!(accelerator("alt+delete"), Some("Alt+Delete".into()));
assert_eq!(accelerator("cmd+;"), Some(meta("Cmd+;")));
assert_eq!(accelerator("ctrl+f19"), Some("Ctrl+F19".into()));
}
#[derive(Default)]
struct FakeGlobalShortcut {
registered: Vec<String>,
fail_for: HashSet<String>,
unregister_calls: Vec<String>,
}
impl ShortcutRegistry for FakeGlobalShortcut {
fn register(&mut self, binding: &Candidate) -> bool {
if self.fail_for.contains(&binding.accelerator) {
return false;
}
self.registered.push(binding.accelerator.clone());
true
}
fn unregister(&mut self, accelerator: &str) {
self.unregister_calls.push(accelerator.into());
self.registered.retain(|registered| registered != accelerator);
}
}
fn binding(accelerator: &str, command: &str) -> Candidate {
candidate(accelerator, "ctrl+cmd+a", command, None, false)
}
#[test]
fn registers_desired_accelerators_and_reports_no_failures() {
let mut service = GlobalShortcuts::new(FakeGlobalShortcut::default());
let failed = service.update(vec![binding("Control+Cmd+A", "a"), binding("Control+Cmd+B", "b")]);
assert_eq!(failed, Vec::<String>::new());
assert_eq!(service.registry.registered, ["Control+Cmd+A", "Control+Cmd+B"]);
}
#[test]
fn unregisters_accelerators_removed_on_a_subsequent_update() {
let mut service = GlobalShortcuts::new(FakeGlobalShortcut::default());
service.update(vec![binding("Control+Cmd+A", "a"), binding("Control+Cmd+B", "b")]);
service.update(vec![binding("Control+Cmd+A", "a")]);
assert_eq!(service.registry.registered, ["Control+Cmd+A"]);
assert_eq!(service.registry.unregister_calls, ["Control+Cmd+B"]);
}
#[test]
fn returns_the_labels_that_failed_to_register_and_retries_them_later() {
let mut service = GlobalShortcuts::new(FakeGlobalShortcut::default());
service.registry.fail_for.insert("Control+Cmd+A".into());
assert_eq!(service.update(vec![binding("Control+Cmd+A", "a")]), ["ctrl+cmd+a"]);
service.registry.fail_for.clear();
assert_eq!(service.update(vec![binding("Control+Cmd+A", "a")]), Vec::<String>::new());
assert_eq!(service.registry.registered, ["Control+Cmd+A"]);
}
#[test]
fn deduplicates_accelerators_within_one_payload() {
let mut service = GlobalShortcuts::new(FakeGlobalShortcut::default());
let failed = service.update(vec![binding("Control+Cmd+A", "first"), binding("Control+Cmd+A", "second")]);
assert_eq!(failed, Vec::<String>::new());
assert_eq!(service.registry.registered.len(), 1);
assert_eq!(service.binding("Control+Cmd+A").map(|binding| binding.command.as_str()), Some("first"));
}
#[test]
fn a_trigger_reads_the_current_binding_with_its_args() {
let mut service = GlobalShortcuts::new(FakeGlobalShortcut::default());
service.update(vec![binding("Control+Cmd+A", "old")]);
let with_args = Candidate { args: Some(json!({ "foo": "bar" })), ..binding("Control+Cmd+A", "workbench.action.openAgentsWindow") };
service.update(vec![with_args.clone()]);
assert_eq!(service.registry.registered, ["Control+Cmd+A"], "registered once, with a callback reading the current binding");
assert_eq!(service.binding("Control+Cmd+A"), Some(&with_args));
assert_eq!(service.binding("Control+Cmd+B"), None);
}
/// globalKeybindingsMainService.test.ts 'trigger passes undefined args when the binding has none'.
#[test]
fn a_trigger_of_a_binding_without_args_passes_none() {
let mut service = GlobalShortcuts::new(FakeGlobalShortcut::default());
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"));
}
/// 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()
}
}