Skip to content

Visual Studio Code, rebuilt in Rust

Rust

fix(keybindings): label keys by the build's OS in the keyboard mapper

rokartura1dddb7178f2
diff --git a/native/crates/app/src/keybindings.rs b/native/crates/app/src/keybindings.rs
index d44dcfd0880..d1189b48435 100644
--- a/native/crates/app/src/keybindings.rs
+++ b/native/crates/app/src/keybindings.rs
@@ -25,14 +25,18 @@ use crate::keyboard_mapper::{self, KeyboardMapper, ScanCodeChord};
pub enum Os {
Macintosh,
Windows,
- // Only the tests build it until M23 makes it Linux's `OS`.
- #[allow(dead_code)]
Linux,
}
/// This build's `OS`. Linux keeps the macOS table and labels until M23 ports its table (`default_table`).
pub const OS: Os = if cfg!(target_os = "windows") { Os::Windows } else { Os::Macintosh };
+/// GPUI parses `secondary` as ctrl on Linux, where `OS` keeps the macOS table until M23 ports Linux's.
+#[cfg(test)]
+pub fn primary_keys(keys: &str) -> String {
+ keys.replace("secondary-", if OS == Os::Windows { "ctrl-" } else { "cmd-" })
+}
+
/// One key press with its modifiers: a `KeyCodeChord` (`key` indexes `KEY_CODES`, 0 is `KeyCode.Unknown`), or a
/// `ScanCodeChord` when `scan_code` (an index of `SCAN_CODE_INFO`) is set, where `key` is the US key code it stands
/// for without a keyboard mapper. The labels come from the current layout's keyboard mapper when there is one.
@@ -153,12 +157,7 @@ impl Chord {
return label;
}
let key = if self.is_duplicate_modifier_case() { "" } else { KEY_CODES[self.key].0 };
- let labels = match os {
- Os::Macintosh => ["Control", "Shift", "Option", "Command"],
- Os::Windows => ["Control", "Shift", "Alt", "Windows"],
- Os::Linux => ["Control", "Shift", "Alt", "Super"],
- };
- self.with_modifiers(labels, "+", key)
+ self.with_modifiers(aria_modifier_labels(os), "+", key)
}
/// `keyAriaLabel` of a `ResolvedChord`.
@@ -180,12 +179,7 @@ impl Chord {
return label;
}
let key = if self.is_duplicate_modifier_case() { String::new() } else { KEY_CODES[self.key].1.to_lowercase() };
- let meta = match os {
- Os::Macintosh => "cmd",
- Os::Windows => "win",
- Os::Linux => "meta",
- };
- self.with_modifiers(["ctrl", "shift", "alt", meta], "+", &key)
+ self.with_modifiers(user_settings_modifier_labels(os), "+", &key)
}
/// The source `gpui::KeyBinding` parses, `shift-cmd-s`; `None` where Electron has no accelerator either.
@@ -214,7 +208,7 @@ impl Chord {
}
/// `UILabelProvider`'s modifier labels (Ctrl, Shift, Alt, Meta) and separator on `os`.
-fn ui_modifier_labels(os: Os) -> ([&'static str; 4], &'static str) {
+pub fn ui_modifier_labels(os: Os) -> ([&'static str; 4], &'static str) {
match os {
Os::Macintosh => (["\u{2303}", "⇧", "⌥", "⌘"], ""),
Os::Windows => (["Ctrl", "Shift", "Alt", "Windows"], "+"),
@@ -222,6 +216,23 @@ fn ui_modifier_labels(os: Os) -> ([&'static str; 4], &'static str) {
}
}
+pub fn aria_modifier_labels(os: Os) -> [&'static str; 4] {
+ match os {
+ Os::Macintosh => ["Control", "Shift", "Option", "Command"],
+ Os::Windows => ["Control", "Shift", "Alt", "Windows"],
+ Os::Linux => ["Control", "Shift", "Alt", "Super"],
+ }
+}
+
+/// `UserSettingsLabelProvider`: the Meta key is `cmd`, `win` or `meta`.
+pub fn user_settings_modifier_labels(os: Os) -> [&'static str; 4] {
+ match os {
+ Os::Macintosh => ["ctrl", "shift", "alt", "cmd"],
+ Os::Windows => ["ctrl", "shift", "alt", "win"],
+ Os::Linux => ["ctrl", "shift", "alt", "meta"],
+ }
+}
+
/// `_simpleAsString`: the pressed modifiers' labels in Ctrl, Shift, Alt, Meta order, then the key.
pub fn with_modifiers(pressed: [bool; 4], labels: [&str; 4], separator: &str, key: &str) -> String {
let mut parts: Vec<&str> = labels.iter().zip(pressed).filter(|(_, pressed)| *pressed).map(|(label, _)| *label).collect();
diff --git a/native/crates/app/src/keyboard_mapper.rs b/native/crates/app/src/keyboard_mapper.rs
index 5780bd2ac5c..df98498a0d5 100644
--- a/native/crates/app/src/keyboard_mapper.rs
+++ b/native/crates/app/src/keyboard_mapper.rs
@@ -13,7 +13,7 @@ use serde_json::Value;
use crate::keybindings::key_codes::KEY_CODES;
use crate::keybindings::scan_codes::SCAN_CODE_INFO;
-use crate::keybindings::{Chord, electron_key, with_modifiers};
+use crate::keybindings::{Chord, OS, Os, aria_modifier_labels, electron_key, ui_modifier_labels, user_settings_modifier_labels, with_modifiers};
use crate::keyboard_layout::KeyEvent;
/// `ScanCodeChord`: `scan_code` indexes `SCAN_CODE_INFO`.
@@ -153,8 +153,10 @@ pub fn event_chord(keystroke: &gpui::Keystroke) -> Chord {
}
pub struct KeyboardMapper {
- /// The mapper's `_OS` is Linux.
+ /// The mapper's `_OS` is Linux, for Electron's OEM key accelerators.
linux: bool,
+ /// The `_OS` its labels are in: this build's `OS`, so Linux keeps the macOS labels of its macOS table until M23.
+ os: Os,
is_us_standard: bool,
map_alt_gr_to_ctrl_alt: bool,
/// The layout's characters per scan code, for `dump_debug_info`.
@@ -171,6 +173,7 @@ impl KeyboardMapper {
let count = SCAN_CODE_INFO.len();
let mut mapper = KeyboardMapper {
linux: cfg!(target_os = "linux"),
+ os: OS,
is_us_standard,
map_alt_gr_to_ctrl_alt,
code_info: HashMap::new(),
@@ -412,6 +415,9 @@ impl KeyboardMapper {
/// `getUILabelForScanCodeChord`: arrows as arrows on macOS.
fn ui_key_label(&self, chord: &ScanCodeChord) -> Option<String> {
+ if self.os != Os::Macintosh {
+ return self.key_label(chord);
+ }
let arrow = match SCAN_CODE_INFO[chord.scan_code].0 {
"ArrowLeft" => "←",
"ArrowUp" => "↑",
@@ -483,15 +489,16 @@ impl KeyboardMapper {
}
pub fn label(&self, chords: &[ScanCodeChord]) -> Option<String> {
- to_label(chords, ["\u{2303}", "⇧", "⌥", "⌘"], "", |chord| self.ui_key_label(chord))
+ let (modifiers, separator) = ui_modifier_labels(self.os);
+ to_label(chords, modifiers, separator, |chord| self.ui_key_label(chord))
}
pub fn aria_label(&self, chords: &[ScanCodeChord]) -> Option<String> {
- to_label(chords, ["Control", "Shift", "Option", "Command"], "+", |chord| self.key_label(chord))
+ to_label(chords, aria_modifier_labels(self.os), "+", |chord| self.key_label(chord))
}
pub fn user_settings_label(&self, chords: &[ScanCodeChord]) -> Option<String> {
- to_label(chords, ["ctrl", "shift", "alt", "cmd"], "+", |chord| self.user_settings_key_label(chord))
+ to_label(chords, user_settings_modifier_labels(self.os), "+", |chord| self.user_settings_key_label(chord))
}
/// `getElectronAccelerator`: none for chords and a lone modifier.
@@ -500,7 +507,8 @@ impl KeyboardMapper {
if chord.is_duplicate_modifier_case() {
return None;
}
- to_label(chords, ["Ctrl", "Shift", "Alt", "Cmd"], "+", |chord| self.electron_key_label(chord))
+ let meta = if self.os == Os::Macintosh { "Cmd" } else { "Super" };
+ to_label(chords, ["Ctrl", "Shift", "Alt", meta], "+", |chord| self.electron_key_label(chord))
}
pub fn is_wysiwyg_keybinding(&self, chords: &[ScanCodeChord]) -> bool {
@@ -509,7 +517,7 @@ impl KeyboardMapper {
/// The key caps `KeybindingLabel` draws for one chord: each modifier, then the UI key label.
pub fn key_caps(&self, chord: &ScanCodeChord) -> Vec<String> {
- let mut caps: Vec<String> = ["\u{2303}", "⇧", "⌥", "⌘"].into_iter().zip(chord.modifiers()).filter(|(_, pressed)| *pressed).map(|(symbol, _)| symbol.to_string()).collect();
+ let mut caps: Vec<String> = ui_modifier_labels(self.os).0.into_iter().zip(chord.modifiers()).filter(|(_, pressed)| *pressed).map(|(symbol, _)| symbol.to_string()).collect();
if let Some(key) = self.ui_key_label(chord).filter(|key| !key.is_empty()) {
caps.push(key);
}
diff --git a/native/crates/app/src/keyboard_mapper/tests.rs b/native/crates/app/src/keyboard_mapper/tests.rs
index 099f3969a30..6dd8451fd9d 100644
--- a/native/crates/app/src/keyboard_mapper/tests.rs
+++ b/native/crates/app/src/keyboard_mapper/tests.rs
@@ -1,4 +1,4 @@
-//! macLinuxKeyboardMapper.test.ts, the macOS suites, over the upstream layout fixtures.
+//! macLinuxKeyboardMapper.test.ts, the macOS suites and Linux en_us cases, over the upstream layout fixtures.
use std::path::Path;
@@ -37,7 +37,7 @@ pub(crate) fn raw_mapping(name: &str) -> Value {
/// A mapper of the macOS fixtures, created with `OperatingSystem.Macintosh` as macLinuxKeyboardMapper.test.ts does.
fn mapper(name: &str, is_us_standard: bool) -> KeyboardMapper {
- KeyboardMapper { linux: false, ..KeyboardMapper::new(is_us_standard, &raw_mapping(name), false) }
+ KeyboardMapper { linux: false, os: Os::Macintosh, ..KeyboardMapper::new(is_us_standard, &raw_mapping(name), false) }
}
/// `IResolvedKeybinding`: label, aria label, electron accelerator, user settings label, WYSIWYG, dispatch parts,
@@ -156,11 +156,28 @@ fn mac_en_us_resolve() {
#[test]
fn mac_en_us_alt_gr_maps_to_ctrl_alt() {
- let mapper = KeyboardMapper::new(true, &raw_mapping("mac_en_us"), true);
+ let mapper = KeyboardMapper { linux: false, os: Os::Macintosh, ..KeyboardMapper::new(true, &raw_mapping("mac_en_us"), true) };
let chord = mapper.resolve_keyboard_event(KeyEvent { code: "KeyZ", ctrl: false, shift: false, alt: false, meta: false }, None, true);
assert_eq!(resolved_of(&mapper, &[chord]), resolved("⌃⌥Z", "Control+Option+Z", Some("Ctrl+Alt+Z"), "ctrl+alt+z", true, &[Some("ctrl+alt+[KeyZ]")]));
}
+/// 'keyboardMapper - LINUX en_us': Linux labels name the modifiers, join them with `+` and keep arrow names.
+#[test]
+fn linux_en_us_resolve() {
+ let mapper = KeyboardMapper { linux: true, os: Os::Linux, ..KeyboardMapper::new(true, &raw_mapping("linux_en_us"), false) };
+ let one = |keybinding| resolve_keybinding(&mapper, keybinding);
+ assert_eq!(one("ctrl+a"), [resolved("Ctrl+A", "Control+A", Some("Ctrl+A"), "ctrl+a", true, &[Some("ctrl+[KeyA]")])]);
+ assert_eq!(one("shift+]"), [resolved("Shift+]", "Shift+]", Some("Shift+]"), "shift+]", true, &[Some("shift+[BracketRight]")])]);
+ assert_eq!(one("ctrl+k ctrl+\\"), [resolved("Ctrl+K Ctrl+\\", "Control+K Control+\\", None, "ctrl+k ctrl+\\", true, &[Some("ctrl+[KeyK]"), Some("ctrl+[Backslash]")])]);
+ assert_eq!(one("ctrl+down"), [resolved("Ctrl+DownArrow", "Control+DownArrow", Some("Ctrl+Down"), "ctrl+down", true, &[Some("ctrl+[ArrowDown]")])]);
+ for code in ["MetaLeft", "MetaRight"] {
+ let expected = (Some("Super".into()), Some("Super".into()), None, Some("meta".into()), true, vec![None], vec![Some("meta")]);
+ assert_eq!(resolve_event(&mapper, true, code), expected, "{code}");
+ }
+ let chord = ScanCodeChord { ctrl: true, shift: true, alt: false, meta: false, scan_code: scan_code("KeyR") };
+ assert_eq!(mapper.key_caps(&chord), ["Ctrl", "Shift", "R"]);
+}
+
/// 'issue #28237 resolveKeybinding Cmd+C'.
#[test]
fn mac_zh_hant_cmd_c() {
diff --git a/native/crates/app/src/workbench/extension_features.rs b/native/crates/app/src/workbench/extension_features.rs
index 31f76ca59d9..6ac101b7036 100644
--- a/native/crates/app/src/workbench/extension_features.rs
+++ b/native/crates/app/src/workbench/extension_features.rs
@@ -277,7 +277,11 @@ fn commands_table(contributes: &Value) -> FeatureData {
for rule in keybindings {
// menusExtensionPoint.ts `resolveKeybinding`: `resolveUserBinding(win, linux or mac ?? key)[0]`; a key that
// does not parse resolves to nothing.
- let platform_key = if cfg!(target_os = "macos") { "mac" } else if cfg!(windows) { "win" } else { "linux" };
+ let platform_key = match crate::keybindings::OS {
+ crate::keybindings::Os::Macintosh => "mac",
+ crate::keybindings::Os::Windows => "win",
+ crate::keybindings::Os::Linux => "linux",
+ };
let key = rule.get(platform_key).and_then(Value::as_str).or_else(|| rule["key"].as_str()).unwrap_or_default();
let chords = crate::keybindings::parse_keybinding(key);
if chords.is_empty() {
diff --git a/port/ledger.md b/port/ledger.md
index b9beac5936b..a3c15dc118e 100644
--- a/port/ledger.md
+++ b/port/ledger.md
@@ -64,7 +64,7 @@ Status: `open`, `in progress`, `waiting on Artur`, `later` (postponed), `done`,
| M23 Linux | app/src/main.rs:174 | open | [linux M] the arm64 build sometimes dies at quit with SIGSEGV (exit 139) after its work is done: `v1.148.0-insider` (dea4dbe55a1) 2 of 21 smoke runs, `v1.147.0-insider` 1 of 17, so it predates 1.148.0; x64 not seen. Found while publishing v1.148.0-insider; root cause not looked for. | `port/tools/linux/smoke` on arm64 repeated 20 times: no exit 139 |
| M23 Linux | app/src/update/install.rs:51 | done | [linux M] updates as a download link (no in-place install). | `cargo test -p app update::` on Linux: `an_update_found_on_linux_waits_and_download_opens_its_link` |
| M23 Linux | app/src/diagnostics.rs:308 | done | [linux S] machine info from `/proc` (CPU model, memory, release). | `cargo test -p app diagnostics` on Linux: `linux_machine_reads_proc` |
-| M23 Linux | app/src/keybindings.rs:86 | open | [linux L] Linux keybindings: the Linux default table (keybindings.rs `DEFAULT_KEYBINDINGS` is `default-macos.json`), the `linux` key of extension and user rules (`extension_keybindings` reads `mac`), and labels in Linux's form (keybindingLabels.ts `UILabelProvider`, `AriaLabelProvider`, `UserSettingsLabelProvider` for `OperatingSystem.Linux`): `Ctrl+Shift+P`, `Super` and `meta`. Labels alone would show the macOS table as `Super+P`, so they wait for the table. Linux shows now: the macOS table with Cmd on GPUI's platform modifier (Super), the macOS symbols (`⌃⇧⌥⌘`), `Option` and `Command` aria labels and `cmd` in user settings. | |
+| M23 Linux | app/src/keybindings.rs:86 | open | [linux L] Linux keybindings: the Linux default table (keybindings.rs `DEFAULT_KEYBINDINGS` is `default-macos.json`), the `linux` key of extension and user rules (`extension_keybindings` reads `mac`), and labels in Linux's form (keybindingLabels.ts `UILabelProvider`, `AriaLabelProvider`, `UserSettingsLabelProvider` for `OperatingSystem.Linux`): `Ctrl+Shift+P`, `Super` and `meta`. Labels alone would show the macOS table as `Super+P`, so they wait for the table. Linux shows now: the macOS table with Cmd on GPUI's platform modifier (Super), the macOS symbols (`⌃⇧⌥⌘`), `Option` and `Command` aria labels and `cmd` in user settings. | Ready for the switch: keyboard_mapper.rs labels in its `os` field, this build's `OS` (`cargo test -p app keyboard_mapper`: `linux_en_us_resolve` checks `Ctrl+A`, `Super`, `meta` and key caps with `Os::Linux`); `extension_keybindings(os)` reads the `linux` key once `OS` is Linux. |
| M23 Linux | app/src/workbench/menubar.rs:173 | open | [linux M] menu bar in the custom title bar. Linux shows now: no menu bar; gpui_linux `set_menus` keeps the menus and draws none. | |
| M23 Linux | .github/workflows/linux.yml:1 | done | [linux S] move actions/checkout, actions/setup-node and actions/upload-artifact from v4 to their Node 24 majors (pinned by SHA). | checkout v7.0.1, setup-node v7.1.0, upload-artifact v7.0.2 by SHA; the workflow not run yet |
| M23 Linux | port/tools/package-linux:1 | done | [linux M] Linux builds of the host's native modules (@vscode/spdlog, kerberos): package-linux rebuilds them with node-gyp; a dev run in the Studio container still loads the reference's macOS builds (its pnpm install ran on macOS), a Linux install of upstream builds them for Linux. | the extracted `VSRustium-1.147.0-linux-arm64.tar.gz` writes `logs/<session>/window1/exthost/exthost.log` (spdlog) and passes `port/tools/linux/smoke` |