Visual Studio Code, rebuilt in Rust
Rust
//! Ported from platform/keybinding/test/common/keybindingResolver.test.ts and keybindingLabels.test.ts, and
//! base/test/common/keybindings.test.ts. Keybindings are written as user settings strings instead of
//! `KeyMod | KeyCode` numbers; the macOS cases, and the Windows and Linux label cases through the `_in(os)` labels.
use std::collections::HashMap;
use serde_json::{Value, json};
use super::{Item, Os, Resolution, Resolver, label, parse_keybinding, user_settings_label};
use crate::contextkey::Expr;
fn context(values: &[(&str, Value)]) -> HashMap<String, Value> {
values.iter().map(|(key, value)| (key.to_string(), value.clone())).collect()
}
fn kb_item(keybinding: &str, command: &str, args: Option<Value>, when: Option<Expr>, is_default: bool) -> Item {
Item::new(parse_keybinding(keybinding), command, args, when, is_default)
}
fn equals(key: &str, value: &str) -> Option<Expr> {
Some(Expr::key_equals(key, json!(value)))
}
/// What `assert.deepStrictEqual` compares on the items of a removal test.
fn summary(items: &[Item]) -> Vec<(String, String, Option<String>, bool)> {
items.iter().map(|item| (user_settings_label(&item.keybinding), item.command.clone(), item.when.as_ref().map(Expr::serialize), item.is_default)).collect()
}
fn chord(key: &str) -> super::Chord {
parse_keybinding(key)[0]
}
#[test]
fn resolve_key() {
let when = Expr::key_equals("bar", json!("baz"));
let item = kb_item("cmd+shift+z", "yes", None, Some(when.clone()), true);
assert!(when.evaluate(&context(&[("bar", json!("baz"))])));
assert!(!when.evaluate(&context(&[("bar", json!("bz"))])));
let resolver = Resolver::new(vec![item], vec![]);
let found = |bar: &str| resolver.resolve(&context(&[("bar", json!(bar))]), &[], chord("cmd+shift+z"));
assert_eq!(found("baz"), Resolution::KbFound { command: "yes".into(), args: None, bubble: false });
assert_eq!(found("bz"), Resolution::NoMatchingKb);
}
#[test]
fn resolve_key_with_arguments() {
let args = json!({ "text": "no" });
let item = kb_item("cmd+shift+z", "yes", Some(args.clone()), equals("bar", "baz"), true);
let resolver = Resolver::new(vec![item], vec![]);
let result = resolver.resolve(&context(&[("bar", json!("baz"))]), &[], chord("cmd+shift+z"));
assert_eq!(result, Resolution::KbFound { command: "yes".into(), args: Some(args), bubble: false });
}
fn assert_removals(rules: Vec<Item>, expected: Vec<Item>) {
assert_eq!(summary(&Resolver::handle_removals(rules)), summary(&expected));
}
#[test]
fn removals_simple() {
let defaults = || vec![kb_item("a", "yes1", None, equals("1", "a"), true), kb_item("b", "yes2", None, equals("2", "b"), true)];
assert_removals(vec![kb_item("a", "yes1", None, equals("1", "a"), true), kb_item("b", "yes2", None, equals("2", "b"), false)], vec![
kb_item("a", "yes1", None, equals("1", "a"), true),
kb_item("b", "yes2", None, equals("2", "b"), false),
]);
let mut rules = defaults();
rules.push(kb_item("c", "yes3", None, equals("3", "c"), false));
let mut expected = defaults();
expected.push(kb_item("c", "yes3", None, equals("3", "c"), false));
assert_removals(rules, expected);
}
#[test]
fn removals_that_do_not_match() {
let defaults = || vec![kb_item("a", "yes1", None, equals("1", "a"), true), kb_item("b", "yes2", None, equals("2", "b"), true)];
// not matching when
let mut rules = defaults();
rules.push(kb_item("a", "-yes1", None, equals("1", "b"), false));
assert_removals(rules, defaults());
// not matching keybinding
let mut rules = defaults();
rules.push(kb_item("b", "-yes1", None, equals("1", "a"), false));
assert_removals(rules, defaults());
}
#[test]
fn removals_that_match() {
let defaults = || vec![kb_item("a", "yes1", None, equals("1", "a"), true), kb_item("b", "yes2", None, equals("2", "b"), true)];
// matching keybinding and when, unspecified keybinding, unspecified when, both unspecified
for (key, when) in [("a", equals("1", "a")), ("", equals("1", "a")), ("a", None), ("", None)] {
let mut rules = defaults();
rules.push(kb_item(key, "-yes1", None, when, false));
assert_removals(rules, vec![kb_item("b", "yes2", None, equals("2", "b"), true)]);
}
}
#[test]
fn issue_138997_removal_in_default_list() {
let rules = vec![kb_item("a", "yes1", None, None, true), kb_item("b", "yes2", None, None, true), kb_item("", "-yes1", None, None, false)];
assert_removals(rules, vec![kb_item("b", "yes2", None, None, true)]);
}
#[test]
fn issue_612_cannot_remove_keybindings_for_commands_with_caret() {
let rules = vec![kb_item("a", "^yes1", None, equals("1", "a"), true), kb_item("b", "yes2", None, equals("2", "b"), true), kb_item("a", "-yes1", None, None, false)];
assert_removals(rules, vec![kb_item("b", "yes2", None, equals("2", "b"), true)]);
}
#[test]
fn issue_140884_unable_to_reassign_f1() {
let rules = vec![kb_item("a", "command1", None, None, true), kb_item("a", "-command1", None, None, false), kb_item("a", "command1", None, None, false)];
assert_removals(rules, vec![kb_item("a", "command1", None, None, false)]);
}
#[test]
fn issue_141638_change_when_expression_might_remove_keybinding() {
let rules = vec![kb_item("a", "command1", None, None, true), kb_item("a", "command1", None, equals("a", "1"), false), kb_item("a", "-command1", None, None, false)];
assert_removals(rules, vec![kb_item("a", "command1", None, equals("a", "1"), false)]);
}
#[test]
fn issue_157751_auto_quoting_of_context_keys() {
let default_when = Expr::deserialize("editorTextFocus && activeEditor != workbench.editor.notebook && editorLangId in julia.supportedLanguageIds");
let removal_when = Expr::deserialize("editorTextFocus && activeEditor != 'workbench.editor.notebook' && editorLangId in 'julia.supportedLanguageIds'");
assert_removals(vec![kb_item("a", "command1", None, default_when, true), kb_item("a", "-command1", None, removal_when, false)], vec![]);
}
#[test]
fn issue_293802_removal_matches_a_more_specific_default_when() {
let default_when = Expr::and(vec![Some(Expr::has("inChatInput")), Some(Expr::not("withinEditSessionDiff"))]);
assert_removals(vec![kb_item("a", "command1", None, default_when, true), kb_item("a", "-command1", None, Some(Expr::has("inChatInput")), false)], vec![]);
}
#[test]
fn removal_with_more_specific_when_does_not_match_broader_default() {
let removal_when = Expr::and(vec![Some(Expr::has("inChatInput")), Some(Expr::not("withinEditSessionDiff"))]);
let rules = vec![kb_item("a", "command1", None, Some(Expr::has("inChatInput")), true), kb_item("a", "-command1", None, removal_when, false)];
assert_removals(rules, vec![kb_item("a", "command1", None, Some(Expr::has("inChatInput")), true)]);
}
#[test]
fn issue_338834_removing_the_chat_steer_or_queue_enter_keybinding() {
let editing_queue = Expr::key_equals("chatEditingSentRequest", json!("q"));
let editing_steer = Expr::key_equals("chatEditingSentRequest", json!("st"));
let editing_queue_or_steer = Expr::or(vec![Some(editing_queue.clone()), Some(editing_steer.clone())]).unwrap();
let queuing_actions_present = Expr::and(vec![
Some(Expr::not("chatTranscriptProgressActive")),
Expr::or(vec![Some(Expr::has("chatSessionRequestInProgress")), Some(editing_queue_or_steer.clone())]),
Some(Expr::key_not_equals("chatEditingSentRequest", json!("s"))),
]);
let steer_is_default = Expr::key_equals("config.chat.requestQueuing.defaultAction", json!("steer"));
let default_is_queue = Expr::or(vec![Expr::and(vec![Some(steer_is_default.negate()), Some(editing_queue_or_steer.negate())]), Some(editing_queue)]);
let default_is_steer = Expr::or(vec![Expr::and(vec![Some(steer_is_default), Some(editing_queue_or_steer.negate())]), Some(editing_steer)]);
let precondition = Expr::and(vec![Some(Expr::has("chatInputHasText")), Some(Expr::not("chatTranscriptProgressActive")), Some(Expr::not("chatInputBlocked"))]);
let defaults = [("workbench.action.chat.steerWithMessage", default_is_steer), ("workbench.action.chat.queueMessage", default_is_queue)].map(|(command, effective)| {
let when = Expr::and(vec![precondition.clone(), Expr::and(vec![Some(Expr::has("inChatInput")), queuing_actions_present.clone(), effective])]);
kb_item("enter", command, None, when, true)
});
for default in defaults {
let removal = kb_item("enter", &format!("-{}", default.command), None, Expr::deserialize(&default.when.as_ref().unwrap().serialize()), false);
assert_removals(vec![default, removal], vec![]);
}
}
#[test]
fn issue_160604_remove_keybindings_with_when_clause() {
assert_removals(vec![kb_item("a", "command1", None, None, true), kb_item("a", "-command1", None, Some(Expr::True), false)], vec![]);
}
#[test]
fn context_is_entirely_included() {
let expr = |source: Option<&str>| source.and_then(Expr::deserialize);
let included = |a: Option<&str>, b: Option<&str>| Resolver::when_is_entirely_included(expr(a).as_ref(), expr(b).as_ref());
for (a, b) in [
(None, None),
(None, Some("true")),
(Some("true"), None),
(Some("true"), Some("true")),
(Some("key1"), None),
(Some("key1"), Some("")),
(Some("key1"), Some("key1")),
(Some("key1"), Some("true")),
(Some("!key1"), Some("")),
(Some("!key1"), Some("!key1")),
(Some("key2"), Some("")),
(Some("key2"), Some("key2")),
(Some("key1 && key1 && key2 && key2"), Some("key2")),
(Some("key1 && key2"), Some("key2")),
(Some("key1 && key2"), Some("key1")),
(Some("key1 && key2"), Some("")),
(Some("key1"), Some("key1 || key2")),
(Some("key1 || !key1"), Some("key2 || !key2")),
(Some("key1"), Some("key1 || key2 && key3")),
] {
assert!(included(a, b), "{a:?} includes {b:?}");
}
for (a, b) in [
(Some("key1"), Some("!key1")),
(Some("!key1"), Some("key1")),
(Some("key1 && key2"), Some("key3")),
(Some("key1 && key2"), Some("key4")),
(Some("key1"), Some("key2")),
(Some("key1 || key2"), Some("key2")),
(Some(""), Some("key2")),
(None, Some("key2")),
] {
assert!(!included(a, b), "{a:?} does not include {b:?}");
}
}
/// The items of the `resolve command` suite.
fn resolve_command_resolver() -> Resolver {
let item = |key: &str, command: &str, when: Option<Expr>| kb_item(key, command, None, when, true);
Resolver::new(
vec![
// never matches: its `when` is always overwritten by `second`
item("x", "first", Expr::and(vec![Some(Expr::key_equals("key1", json!(true))), Some(Expr::key_not_equals("key2", json!(false)))])),
item("x", "second", Some(Expr::key_equals("key2", json!(true)))),
item("z", "second", None),
item("x", "third", Some(Expr::key_equals("key3", json!(true)))),
item("cmd+y", "fourth", Some(Expr::key_equals("key4", json!(true)))),
item("cmd+y z", "fifth", None),
item("", "sixth", None),
item("cmd+k cmd+u", "seventh", None),
item("cmd+k cmd+k", "seventh", None),
item("cmd+k cmd+u", "uncomment lines", None),
item("cmd+k cmd+c", "comment lines", None),
item("cmd+g cmd+c", "unreachablechord", None),
item("cmd+g", "eleven", None),
item("cmd+k a b", "long multi chord", None),
item("cmd+b cmd+c", "shadowed by long-multi-chord-2", None),
item("cmd+b cmd+c i", "long-multi-chord-2", None),
],
vec![],
)
}
fn assert_lookup(resolver: &Resolver, command: &str, expected: &[&str]) {
let found: Vec<String> = resolver.lookup_keybindings(command).iter().map(|item| mac_settings_label(&item.keybinding)).collect();
assert_eq!(found, expected, "lookup of {command}");
}
fn assert_resolve(resolver: &Resolver, context: &HashMap<String, Value>, keybinding: &str, command: &str) {
let chords = parse_keybinding(keybinding);
for (i, &chord) in chords.iter().enumerate() {
let result = resolver.resolve(context, &chords[..i], chord);
if i == chords.len() - 1 {
assert_eq!(result, Resolution::KbFound { command: command.into(), args: None, bubble: false }, "{command} at chord {i}");
} else {
assert_eq!(result, Resolution::MoreChordsNeeded, "{command} enters or continues multi chord at chord {i}");
}
}
}
#[test]
fn resolve_command() {
let resolver = resolve_command_resolver();
let empty = context(&[]);
assert_lookup(&resolver, "first", &[]);
assert_lookup(&resolver, "second", &["z", "x"]);
assert_resolve(&resolver, &context(&[("key2", json!(true))]), "x", "second");
assert_resolve(&resolver, &empty, "z", "second");
assert_lookup(&resolver, "third", &["x"]);
assert_resolve(&resolver, &context(&[("key3", json!(true))]), "x", "third");
assert_lookup(&resolver, "fourth", &[]);
assert_lookup(&resolver, "fifth", &["cmd+y z"]);
assert_resolve(&resolver, &empty, "cmd+y z", "fifth");
assert_lookup(&resolver, "seventh", &["cmd+k cmd+k"]);
assert_resolve(&resolver, &empty, "cmd+k cmd+k", "seventh");
assert_lookup(&resolver, "uncomment lines", &["cmd+k cmd+u"]);
assert_resolve(&resolver, &empty, "cmd+k cmd+u", "uncomment lines");
assert_lookup(&resolver, "comment lines", &["cmd+k cmd+c"]);
assert_resolve(&resolver, &empty, "cmd+k cmd+c", "comment lines");
assert_lookup(&resolver, "unreachablechord", &[]);
assert_lookup(&resolver, "eleven", &["cmd+g"]);
assert_resolve(&resolver, &empty, "cmd+g", "eleven");
assert_lookup(&resolver, "sixth", &[]);
assert_lookup(&resolver, "long multi chord", &["cmd+k a b"]);
assert_resolve(&resolver, &empty, "cmd+k a b", "long multi chord");
}
#[test]
fn kbs_having_common_prefix_the_one_defined_later_is_returned() {
assert_resolve(&resolve_command_resolver(), &context(&[]), "cmd+b cmd+c i", "long-multi-chord-2");
}
#[test]
fn mac_us_label() {
for (keybinding, expected) in [
("a", "A"),
("cmd+a", "⌘A"),
("shift+a", "⇧A"),
("alt+a", "⌥A"),
("ctrl+a", "⌃A"),
("cmd+shift+a", "⇧⌘A"),
("cmd+alt+a", "⌥⌘A"),
("cmd+ctrl+a", "⌃⌘A"),
("shift+alt+a", "⇧⌥A"),
("shift+ctrl+a", "⌃⇧A"),
("alt+ctrl+a", "⌃⌥A"),
("cmd+shift+alt+a", "⇧⌥⌘A"),
("cmd+shift+ctrl+a", "⌃⇧⌘A"),
("cmd+alt+ctrl+a", "⌃⌥⌘A"),
("shift+alt+ctrl+a", "⌃⇧⌥A"),
("cmd+shift+alt+ctrl+a", "⌃⇧⌥⌘A"),
("cmd+a cmd+b", "⌘A ⌘B"),
("left", "←"),
("up", "↑"),
("right", "→"),
("down", "↓"),
] {
assert_eq!(mac_label(&parse_keybinding(keybinding)), expected, "{keybinding}");
}
}
/// The macOS labels on every OS, as keybindingLabels.test.ts passes `OperatingSystem.Macintosh`.
fn mac_label(chords: &[super::Chord]) -> String {
chords.iter().map(|chord| chord.label_in(Os::Macintosh)).collect::<Vec<_>>().join(" ")
}
fn mac_aria_label(chords: &[super::Chord]) -> String {
chords.iter().map(|chord| chord.aria_label_in(Os::Macintosh)).collect::<Vec<_>>().join(" ")
}
fn mac_settings_label(chords: &[super::Chord]) -> String {
chords.iter().map(|chord| chord.user_settings_label_in(Os::Macintosh)).collect::<Vec<_>>().join(" ")
}
#[test]
fn mac_aria_and_user_settings_labels() {
let all = parse_keybinding("cmd+shift+alt+ctrl+a");
assert_eq!(mac_aria_label(&all), "Control+Shift+Option+Command+A");
assert_eq!(mac_settings_label(&all), "ctrl+shift+alt+cmd+a");
assert_eq!(mac_settings_label(&parse_keybinding("cmd+a cmd+b")), "cmd+a cmd+b");
}
#[test]
fn issue_91235_do_not_end_with_a_plus() {
assert_eq!(mac_aria_label(&parse_keybinding("cmd+alt+alt")), "Option+Command");
}
#[test]
fn issue_173325_equal_scan_code_is_not_v() {
assert_ne!(parse_keybinding("ctrl+v"), parse_keybinding("ctrl+[Equal]"));
}
/// The macOS table; Windows has `windows_default_table_binds_ctrl_keys`.
#[cfg(not(target_os = "windows"))]
#[test]
fn default_table_binds_the_editor_and_palette_keys() {
let resolver = Resolver::new(super::default_keybindings(&[]), vec![]);
let editor = context(&[("textInputFocus", json!(true)), ("editorTextFocus", json!(true))]);
let command = |context: &HashMap<String, Value>, key: &str| match resolver.resolve(context, &[], chord(key)) {
Resolution::KbFound { command, .. } => command,
other => format!("{other:?}"),
};
assert_eq!(command(&editor, "alt+right"), "cursorWordEndRight");
assert_eq!(command(&editor, "cmd+c"), "editor.action.clipboardCopyAction");
assert_eq!(command(&context(&[]), "shift+cmd+p"), "workbench.action.showCommands");
assert_eq!(command(&context(&[("inQuickOpen", json!(true)), ("inFilesPicker", json!(true))]), "cmd+p"), "workbench.action.quickOpenNavigateNextInFilePicker");
assert_eq!(resolver.resolve(&context(&[]), &[], chord("cmd+k")), Resolution::MoreChordsNeeded);
}
#[test]
fn a_shifted_symbol_keystroke_resolves_to_its_us_key_with_shift() {
let keystroke = |key: &str, shift| gpui::Keystroke { modifiers: gpui::Modifiers { platform: true, shift, ..Default::default() }, key: key.into(), key_char: None };
assert_eq!(super::Chord::from_keystroke(&keystroke(">", false)), chord("shift+cmd+."));
assert_eq!(super::Chord::from_keystroke(&keystroke("<", false)), chord("shift+cmd+,"));
assert_eq!(super::Chord::from_keystroke(&keystroke("p", true)), chord("shift+cmd+p"));
assert_eq!(super::Chord::from_keystroke(&keystroke(".", false)), chord("cmd+."));
}
// keybindingIO.test.ts `readUserKeybindingItem` cases. A rule whose command is not a string is dropped where upstream
// keeps it with a null command, which binds nothing.
#[test]
fn read_user_keybinding_item() {
let read = |rule: Value| super::rule_item(&rule, rule["key"].as_str().unwrap_or(""), false);
assert!(read(json!({ "key": "ctrl+k ctrl+f", "command": ["firstcommand", "seccondcommand"] })).is_none(), "issue #10452 - invalid command");
assert!(read(json!({ "key": "ctrl+k ctrl+f", "command": "firstcommand", "when": [] })).unwrap().when.is_none(), "issue #10452 - invalid when");
assert!(read(json!({ "key": [], "command": "firstcommand" })).unwrap().keybinding.is_empty(), "issue #10452 - invalid key");
assert!(read(json!({ "key": "", "command": "firstcommand" })).unwrap().keybinding.is_empty(), "issue #10452 - invalid key 2");
let with_args = read(json!({ "key": "ctrl+k ctrl+f", "command": "firstcommand", "when": [], "args": { "text": "theText" } })).unwrap();
assert_eq!(with_args.args, Some(json!({ "text": "theText" })));
assert!(!read(json!({ "key": "ctrl+cmd+a", "command": "firstcommand" })).unwrap().system_wide);
assert!(!read(json!({ "key": "ctrl+cmd+a", "command": "firstcommand", "systemWide": "yes" })).unwrap().system_wide);
assert!(read(json!({ "key": "ctrl+cmd+a", "command": "firstcommand", "systemWide": true })).unwrap().system_wide);
}
// keybindingLabels.test.ts 'Electron Accelerator label', macOS cases.
#[test]
fn electron_accelerator_label() {
let accelerator = |key: &str| super::electron_accelerator_in(Os::Macintosh, &parse_keybinding(key));
assert_eq!(accelerator("cmd+shift+alt+ctrl+a"), Some("Ctrl+Shift+Alt+Cmd+A".into()));
assert_eq!(accelerator("cmd+a cmd+b"), None);
assert_eq!(accelerator("numpad1"), None);
for (key, expected) in [("left", "Left"), ("up", "Up"), ("right", "Right"), ("down", "Down")] {
assert_eq!(accelerator(key), Some(expected.into()));
}
}
// abstractKeybindingService.test.ts suite 'appendKeybinding'; a missing command id is the empty string here, and the
// `enforceContextCheck` cases are left out: only inline completion and chat callers pass it.
#[test]
fn append_keybinding() {
let resolver = Resolver::new(vec![kb_item("cmd+k", "myCommand", None, None, true)], Vec::new());
let none = context(&[]);
let cmd_k = label(&parse_keybinding("cmd+k"));
assert_eq!(resolver.append_keybinding("My Label", "myCommand", &none), format!("My Label ({cmd_k})"));
assert_eq!(Resolver::new(Vec::new(), Vec::new()).append_keybinding("My Label", "myCommand", &none), "My Label");
assert_eq!(resolver.append_keybinding("My Label", "", &none), "My Label");
assert_eq!(resolver.append_keybinding("", "myCommand", &none), format!(" ({cmd_k})"));
let with_context = Resolver::new(vec![kb_item("cmd+k", "myCommand", None, Some(Expr::has("key1")), true)], Vec::new());
assert_eq!(with_context.append_keybinding("My Label", "myCommand", &context(&[("key1", json!(true))])), format!("My Label ({cmd_k})"));
assert_eq!(with_context.append_keybinding("My Label", "myCommand", &none), format!("My Label ({cmd_k})"));
}
/// keybindingService.ts `_handleKeybinding`: a rejected rule is an error message of the extension, not a keybinding.
#[test]
fn invalid_contributed_keybindings_are_extension_messages() {
let description = json!({ "contributes": { "keybindings": [{ "key": "cmd+k" }, { "command": "a.run", "key": "cmd+a", "when": 1 }, { "command": "b.run", "key": "cmd+b" }] } });
let extension = exthost::scan::ScannedExtension { id: "test.invalid-keybindings".into(), location: "/x".into(), description };
let items = super::default_keybindings(std::slice::from_ref(&extension));
assert!(items.iter().any(|item| item.command == "b.run") && !items.iter().any(|item| item.command == "a.run"));
let messages: Vec<String> = crate::perf::messages(&extension.id).into_iter().map(|(_, message)| message).collect();
assert_eq!(messages, ["Invalid `contributes.keybindings`: property `command` is mandatory and must be of type `string`", "Invalid `contributes.keybindings`: property `when` can be omitted or must be of type `string`"]);
}
/// keybindingLabels.test.ts 'Windows US label' and 'Linux US label' (`KeyMod.CtrlCmd` is ctrl there, `WinCtrl` the Meta key).
#[test]
fn windows_and_linux_us_labels() {
let label_in = |os, keybinding: &str| parse_keybinding(keybinding).iter().map(|chord| chord.label_in(os)).collect::<Vec<_>>().join(" ");
for (os, meta) in [(Os::Windows, "Windows"), (Os::Linux, "Super")] {
for (keybinding, expected) in [
("a", "A".to_string()),
("ctrl+a", "Ctrl+A".into()),
("shift+a", "Shift+A".into()),
("alt+a", "Alt+A".into()),
("win+a", format!("{meta}+A")),
("ctrl+shift+a", "Ctrl+Shift+A".into()),
("ctrl+alt+a", "Ctrl+Alt+A".into()),
("ctrl+win+a", format!("Ctrl+{meta}+A")),
("shift+alt+a", "Shift+Alt+A".into()),
("shift+win+a", format!("Shift+{meta}+A")),
("alt+win+a", format!("Alt+{meta}+A")),
("ctrl+shift+alt+a", "Ctrl+Shift+Alt+A".into()),
("ctrl+shift+win+a", format!("Ctrl+Shift+{meta}+A")),
("ctrl+alt+win+a", format!("Ctrl+Alt+{meta}+A")),
("shift+alt+win+a", format!("Shift+Alt+{meta}+A")),
("ctrl+shift+alt+win+a", format!("Ctrl+Shift+Alt+{meta}+A")),
("ctrl+a ctrl+b", "Ctrl+A Ctrl+B".into()),
("left", "LeftArrow".into()),
] {
assert_eq!(label_in(os, keybinding), expected, "{os:?} {keybinding}");
}
}
assert_eq!(parse_keybinding("ctrl+shift+p")[0].key_caps_in(Os::Windows), ["Ctrl", "Shift", "P"]);
}
/// keybindingLabels.test.ts 'Aria label', 'Electron Accelerator label' and 'User Settings label' on Windows and Linux.
#[test]
fn windows_and_linux_aria_electron_and_user_settings_labels() {
let all = parse_keybinding("ctrl+shift+alt+win+a");
assert_eq!(all[0].aria_label_in(Os::Windows), "Control+Shift+Alt+Windows+A");
assert_eq!(all[0].aria_label_in(Os::Linux), "Control+Shift+Alt+Super+A");
assert_eq!(super::electron_accelerator_in(Os::Windows, &all).as_deref(), Some("Ctrl+Shift+Alt+Super+A"));
assert_eq!(super::electron_accelerator_in(Os::Windows, &parse_keybinding("ctrl+a ctrl+b")), None);
assert_eq!(super::electron_accelerator_in(Os::Windows, &parse_keybinding("numpad1")), None);
assert_eq!(all[0].user_settings_label_in(Os::Windows), "ctrl+shift+alt+win+a");
assert_eq!(all[0].user_settings_label_in(Os::Linux), "ctrl+shift+alt+meta+a");
}
/// The Windows default table (default-win.json, the reference's doc.keybindings.win.json): Ctrl where macOS has Cmd,
/// and Windows' own rules such as Ctrl+Y for redo.
#[test]
fn windows_default_table_binds_ctrl_keys() {
let resolver = Resolver::new(super::default_keybindings_in(Os::Windows, &[]), vec![]);
let editor = context(&[("textInputFocus", json!(true)), ("editorTextFocus", json!(true))]);
let command = |context: &HashMap<String, Value>, key: &str| match resolver.resolve(context, &[], chord(key)) {
Resolution::KbFound { command, .. } => command,
other => format!("{other:?}"),
};
assert_eq!(command(&context(&[]), "ctrl+shift+p"), "workbench.action.showCommands");
assert_eq!(command(&editor, "ctrl+c"), "editor.action.clipboardCopyAction");
assert_eq!(command(&editor, "ctrl+right"), "cursorWordEndRight");
assert_eq!(command(&editor, "ctrl+y"), "redo");
assert_ne!(command(&context(&[]), "shift+win+p"), "workbench.action.showCommands");
assert_eq!(resolver.resolve(&context(&[]), &[], chord("ctrl+k")), Resolution::MoreChordsNeeded);
}
/// keybindingService.ts `bindToCurrentPlatform`: the rule's `win`, `mac` or `linux` key on its platform, else `key`.
#[test]
fn contributed_keybindings_use_the_platform_key() {
let description = json!({ "contributes": { "keybindings": [
{ "command": "a.run", "key": "ctrl+1", "mac": "cmd+1", "win": "alt+1", "linux": "shift+1" },
{ "command": "b.run", "key": "ctrl+2", "win": "" },
] } });
let extension = exthost::scan::ScannedExtension { id: "test.platform-keys".into(), location: "/x".into(), description };
let key = |os| {
let items = super::default_keybindings_in(os, std::slice::from_ref(&extension));
let label = |command: &str| items.iter().find(|item| item.command == command).map(|item| item.keybinding[0].user_settings_label_in(Os::Linux));
(label("a.run"), label("b.run"))
};
assert_eq!(key(Os::Windows), (Some("alt+1".into()), Some("ctrl+2".into())));
assert_eq!(key(Os::Macintosh), (Some("meta+1".into()), Some("ctrl+2".into())));
assert_eq!(key(Os::Linux), (Some("shift+1".into()), Some("ctrl+2".into())));
}