Skip to content

Visual Studio Code, rebuilt in Rust

Rust
43.2 KB
Raw Blame
//! Keybinding dispatch (platform/keybinding/common/abstractKeybindingService.ts `_doDispatch`): every key
//! down of the window resolves against the keybindings in the context of the focused part, before the
//! focused element sees it. Multi-chord mode, its status messages and the context keys live here too.

use std::collections::HashMap;
use std::path::PathBuf;
use std::time::{Duration, Instant};

use files::watcher::{Change, Watcher};
use futures::StreamExt;
use futures::channel::mpsc;
use gpui::{Context, KeyDownEvent, Keystroke, Subscription, Task, Window};
use serde_json::{Value, json};

use super::Workbench;
use super::search_view::SideBarView;
use crate::command_palette::MenuItem;
use crate::commands::Outcome;
use crate::editor::TextDocument;
use crate::keybindings::{self, Chord, Item, Resolution, Resolver};
use crate::system_wide_keybindings::{HotKeys, SystemWide};
use crate::workbench::editor_options::{COLUMN_SELECTION, FOLDING, MULTI_CURSOR_MODIFIER};

/// The keybindings and the dispatch state of `AbstractKeybindingService`.
pub struct Keybindings {
    pub(super) defaults: Vec<Item>,
    /// The rules of keybindings.json, kept to rebuild the resolver when the keyboard layout changes.
    overrides: Vec<Item>,
    /// `<user data>/User/keybindings.json`.
    pub(super) user_file: Option<PathBuf>,
    watcher: Option<Watcher>,
    reload: Option<Task<()>>,
    pub resolver: Resolver,
    /// Counts the resolver's rebuilds, so the Keyboard Shortcuts editor knows its rows are stale.
    pub(super) generation: u64,
    /// Chords pressed so far in multi-chord mode, with their labels.
    chords: Vec<(Chord, String)>,
    chord_checker: Option<Task<()>>,
    system_wide: SystemWide,
    /// `_logging`, toggled by Toggle Keyboard Shortcuts Troubleshooting.
    pub(super) logging: bool,
    /// `_currentlyDispatchingCommandId`: the command a keybinding runs, while it runs.
    dispatching: Option<String>,
    hold_mode: Option<HoldMode>,
}

/// keybindingService.ts `_keybindingHoldMode`: what to run when the held key goes up or the window loses focus.
struct HoldMode {
    release: fn(&mut Workbench),
    _blur: Subscription,
}

impl Default for Keybindings {
    fn default() -> Self {
        Keybindings { defaults: Vec::new(), overrides: Vec::new(), user_file: None, watcher: None, reload: None, resolver: Resolver::new(Vec::new(), Vec::new()), generation: 0, chords: Vec::new(), chord_checker: None, system_wide: SystemWide::default(), logging: false, dispatching: None, hold_mode: None }
    }
}

impl Workbench {
    /// Sets the default and user keybindings.
    pub fn load_keybindings(&mut self, defaults: Vec<Item>, user_file: PathBuf) {
        self.keybindings.user_file = Some(user_file.clone());
        self.set_default_keybindings(defaults);
        let menu = std::mem::take(&mut self.quick_access.menu);
        self.set_command_palette_menu(menu);
        self.set_user_keybindings(keybindings::user_keybindings(&user_file));
    }

    /// Reloads the user's keybindings.json when it changes on disk. Apart from `load_keybindings`: the watcher's
    /// thread wakes the window from outside the test scheduler.
    pub fn start_keybindings_watcher(&mut self, cx: &mut Context<Self>) {
        let (sender, mut receiver) = mpsc::unbounded::<Vec<Change>>();
        let watcher = match Watcher::new(move |changes| drop(sender.unbounded_send(changes))) {
            Ok(watcher) => watcher,
            Err(error) => return eprintln!("[Keybindings] {error}"),
        };
        self.keybindings.watcher = Some(watcher);
        self.watch_user_keybindings();
        cx.spawn(async move |workbench, cx| {
            while let Some(changes) = receiver.next().await {
                if workbench.update(cx, |workbench, cx| workbench.user_keybindings_changed(&changes, cx)).is_err() {
                    return;
                }
            }
        })
        .detach();
    }

    /// keybindingService.ts `UserKeybindings.watch`: the folder of the profile's keybindings.json, which may not exist
    /// yet; a profile switch watches the new one.
    pub(super) fn watch_user_keybindings(&mut self) {
        let (Some(watcher), Some(user_file)) = (self.keybindings.watcher.as_mut(), &self.keybindings.user_file) else { return };
        watcher.unwatch(0);
        let folder = user_file.parent().expect("keybindings.json has a folder");
        if let Err(error) = watcher.watch(0, folder, false, &[]) {
            eprintln!("[Keybindings] {}: {error}", folder.display());
        }
    }

    /// `reloadConfigurationScheduler`: a change of the file reads it again 50 ms after the last one.
    fn user_keybindings_changed(&mut self, changes: &[Change], cx: &mut Context<Self>) {
        let Some(user_file) = self.keybindings.user_file.clone() else { return };
        if !changes.iter().any(|change| change.path == user_file) {
            return;
        }
        self.keybindings.reload = Some(cx.spawn(async move |workbench, cx| {
            cx.background_executor().timer(Duration::from_millis(50)).await;
            let overrides = keybindings::user_keybindings(&user_file);
            let _ = workbench.update(cx, |workbench, cx| {
                workbench.set_user_keybindings(overrides);
                cx.notify();
            });
        }));
    }

    /// The keybindings the core and extensions contribute; `set_user_keybindings` puts them in the resolver.
    pub fn set_default_keybindings(&mut self, defaults: Vec<Item>) {
        self.keybindings.defaults = self.with_user_keybindings_resource(defaults);
    }

    /// The default rules with the reference profile's `resource ==` clauses naming the port's keybindings.json.
    pub(super) fn with_user_keybindings_resource(&self, defaults: Vec<Item>) -> Vec<Item> {
        let resource = self.keybindings.user_file.as_ref().map(|file| crate::editor::uri_string(files::user_data::SCHEME, file)).unwrap_or_default();
        defaults
            .into_iter()
            .map(|item| {
                let when = keybindings::with_keybindings_resource(item.when.clone(), &resource);
                let when_text = if when == item.when { item.when_text } else { None };
                Item { when, when_text, ..item }
            })
            .collect()
    }

    /// The Command Palette's items, whose `resource ==` clauses of the reference's profile name the port's
    /// keybindings.json once it is known (`with_keybindings_resource`).
    pub fn set_command_palette_menu(&mut self, menu: Vec<MenuItem>) {
        let Some(file) = &self.keybindings.user_file else {
            self.quick_access.menu = menu;
            return;
        };
        let resource = crate::editor::uri_string(files::user_data::SCHEME, file);
        let map = |when| keybindings::with_keybindings_resource(when, &resource);
        self.quick_access.menu = menu.into_iter().map(|item| MenuItem { when: map(item.when), precondition: map(item.precondition), ..item }).collect();
    }

    /// Rebuilds the resolver over the defaults and the user's keybindings, and syncs the system-wide ones.
    pub(super) fn set_user_keybindings(&mut self, overrides: Vec<Item>) {
        for warning in self.keybindings.system_wide.set_keybindings(&overrides) {
            self.notify_warning(warning);
        }
        self.keybindings.overrides = overrides;
        self.rebuild_resolver();
    }

    fn rebuild_resolver(&mut self) {
        self.keybindings.resolver = Resolver::new(self.keybindings.defaults.clone(), self.keybindings.overrides.clone());
        self.keybindings.generation += 1;
    }

    /// nativeKeyboardLayout.ts: a new keyboard mapper when the input source or `keyboard.dispatch` and
    /// `keyboard.mapAltGrToCtrlAlt` change, and the keybindings resolved again on it.
    pub fn refresh_keyboard_mapper(&mut self) {
        let setting = |key| self.settings.lock().unwrap().get_value(Some(key), &Default::default());
        let dispatch_key_code = setting("keyboard.dispatch") == Some(json!("keyCode"));
        let map_alt_gr_to_ctrl_alt = setting("keyboard.mapAltGrToCtrlAlt") == Some(json!(true));
        if crate::keyboard_mapper::refresh(dispatch_key_code, map_alt_gr_to_ctrl_alt) {
            self.rebuild_resolver();
        }
    }

    /// Registers the system-wide keybindings with the OS and runs the command of each press, as the
    /// `vscode:runAction` request of globalKeybindingsMainService.ts.
    pub fn start_system_wide_keybindings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let (sender, mut presses) = futures::channel::mpsc::unbounded();
        if let Some(warning) = self.keybindings.system_wide.start(HotKeys::new(sender)) {
            self.notify_warning(warning);
        }
        cx.spawn_in(window, async move |workbench, cx| {
            while let Some(id) = presses.next().await {
                let ran = workbench.update_in(cx, |workbench, window, cx| {
                    let Some(binding) = workbench.keybindings.system_wide.pressed(id) else { return };
                    let (command, args) = (binding.command.clone(), binding.args.clone().into_iter().collect());
                    let outcome = workbench.execute_command(&command, args, window, cx);
                    report_failure(outcome, cx);
                });
                if ran.is_err() {
                    return;
                }
            }
        })
        .detach();
    }

    /// `_doDispatch`: runs the command bound to the key and keeps the key from the focused element.
    pub(super) fn dispatch_key(&mut self, keystroke: &Keystroke, window: &mut Window, cx: &mut Context<Self>) {
        if self.keybindings.hold_mode.is_some() {
            return;
        }
        let native_event = crate::keyboard_layout::current_key_event();
        if native_event.is_some() {
            self.refresh_keyboard_mapper();
        }
        let chord = crate::keyboard_mapper::event_chord(keystroke);
        if self.keybindings.logging {
            let m = &keystroke.modifiers;
            let modifiers: Vec<&str> = [(m.control, "ctrl"), (m.shift, "shift"), (m.alt, "alt"), (m.platform, "meta")].into_iter().filter(|(on, _)| *on).map(|(_, name)| name).collect();
            let code = native_event.map_or("", |event| event.code);
            let key_code = crate::keybindings::key_codes::EVENT_KEY_CODES[chord.key];
            self.log_keybinding(&format!("/ Received  keydown event - modifiers: [{}], code: {code}, keyCode: {key_code}, key: {}", modifiers.join(","), keystroke.key));
            self.log_keybinding(&format!("| Converted keydown event - modifiers: [{}], code: {code}, keyCode: {} ('{}')", modifiers.join(","), chord.key, crate::keybindings::key_codes::KEY_CODES[chord.key].0));
        }
        // isKeyInComposition: the IME owns the keys while it composes.
        if self.marked_text.is_some() || self.input_composing() {
            self.log_keybinding("+ Ignoring keybinding dispatch because an IME composition is in progress.");
            return;
        }
        // The menu's own key handlers run before the window's keybindings.
        if self.context_menu_key(keystroke, window, cx) || self.custom_dialog_key(keystroke, window, cx) || self.accessible_view_key(keystroke, window, cx) || self.icon_select_box_key(keystroke, window, cx) || self.update_tooltip_key(keystroke, window, cx) || self.breadcrumbs_picker_key(keystroke, window, cx) {
            cx.stop_propagation();
            return;
        }
        self.find_input_key_down(keystroke, window, cx);
        if self.find_input_keeps_arrow(keystroke, window) {
            return;
        }
        if chord.is_modifier_key() {
            self.log_keybinding("\\ Keyboard event cannot be dispatched in keydown phase.");
            return;
        }
        let current: Vec<Chord> = self.keybindings.chords.iter().map(|(chord, _)| *chord).collect();
        let in_chord_mode = !current.is_empty();
        let mut log = Vec::new();
        let resolution = self.keybindings.resolver.resolve_logged(&self.key_context(window), &current, chord, &mut log);
        for line in &log {
            self.log_keybinding(line);
        }
        if !in_chord_mode && self.keybindings_editor_record_key(chord, &resolution, window, cx) {
            cx.stop_propagation();
            return;
        }
        if self.modal_blocks_command(&resolution, window) {
            cx.stop_propagation();
            return;
        }
        if !in_chord_mode && self.terminal_key(keystroke, &resolution, window, cx) {
            cx.stop_propagation();
            return;
        }
        // The list's own keydown listener runs before the window's keybindings.
        if !in_chord_mode && self.list_type_navigation(keystroke, resolution == Resolution::NoMatchingKb, window, cx) {
            cx.stop_propagation();
            return;
        }
        if self.editor_focus.is_focused(window) {
            self.content_hover_key_down(&resolution, cx);
            self.debug_hover_key_down(window, cx);
        }
        if keystroke.key == "escape" && self.debug_hover_focus.contains_focused(window, cx) {
            self.debug_hover_escape(window, cx);
            cx.stop_propagation();
            return;
        }
        // contentHoverWidgetWrapper.ts: the widget's own keydown listener hides it on Escape.
        if keystroke.key == "escape" && self.content_hover_focused(window) {
            self.hide_content_hover(cx);
        }
        if self.content_hover_stop_key_down(keystroke, window, cx) || self.workbench_hover_key_down(keystroke, window, cx) {
            cx.stop_propagation();
            return;
        }
        match resolution {
            Resolution::MoreChordsNeeded => {
                cx.stop_propagation();
                self.expect_another_chord(chord, window, cx);
                self.log_keybinding(if current.is_empty() { "+ Entering multi-chord mode..." } else { "+ Continuing multi-chord mode..." });
            }
            Resolution::KbFound { command, args, bubble } if !command.is_empty() => {
                if in_chord_mode {
                    self.leave_chord_mode(cx);
                }
                if !bubble {
                    cx.stop_propagation();
                }
                self.log_keybinding(&format!("+ Invoking command {command}."));
                self.keybindings.dispatching = Some(command.clone());
                let outcome = self.execute_command(&command, args.into_iter().collect(), window, cx);
                self.keybindings.dispatching = None;
                report_failure(outcome, cx);
            }
            // Nothing bound, or bound to no command: only a chord sequence in progress ends with a message.
            _ if in_chord_mode => {
                let mode = if resolution == Resolution::NoMatchingKb { "multi-chord mode" } else { "chord mode" };
                self.log_keybinding(&format!("+ Leaving {mode}: Nothing bound to \"{}, {}\".", self.chord_labels(), chord.label()));
                let message = format!("The key combination ({}, {}) is not a command.", self.chord_labels(), chord.label());
                self.show_status(message, Duration::from_secs(10), window, cx);
                self.leave_chord_mode(cx);
                cx.stop_propagation();
            }
            // hoverService.ts `_keyDown` with hideOnKeyDown, which every workbench hover delegate sets; a sticky hover
            // registers no key listener; QuickInputHoverDelegate turns hideOnKeyDown off.
            _ if self.hovers.stays_on_key_down() => {}
            _ => self.hide_hover_on_key_down(window, cx),
        }
    }

    /// The browser's default action for Tab, after every element's keydown listener let it through.
    pub(super) fn tab_key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
        let keystroke = &event.keystroke;
        if keystroke.key != "tab" || keystroke.modifiers.control || keystroke.modifiers.platform || keystroke.modifiers.alt {
            return;
        }
        if self.move_tab_focus(keystroke.modifiers.shift, window, cx) {
            cx.stop_propagation();
            if !self.hovers.is_sticky() {
                self.dismiss_hover(cx);
                self.hover_focused_action_item(window, cx);
            }
        }
    }

    /// keybindingService.ts `enableKeybindingHoldMode`: while the key that runs `command` stays down, key downs are
    /// ignored; its key up or the window losing focus runs `release`. False when no keybinding runs `command`.
    pub(super) fn enable_keybinding_hold_mode(&mut self, command: &str, release: fn(&mut Workbench), window: &mut Window, cx: &mut Context<Self>) -> bool {
        // shortcut: the key up reaches the workbench only through a focused element, so without one there is no hold mode;
        // a window-level key up listener would lift that.
        if self.keybindings.dispatching.as_deref() != Some(command) || window.focused(cx).is_none() {
            return false;
        }
        let blur = cx.observe_window_activation(window, |workbench, window, cx| {
            if !window.is_window_active() {
                workbench.reset_keybinding_hold_mode(cx);
            }
        });
        self.keybindings.hold_mode = Some(HoldMode { release, _blur: blur });
        self.log_keybinding(&format!("+ Enabled hold-mode for {command}."));
        true
    }

    /// `_resetKeybindingHoldMode`, on every key up.
    pub(super) fn reset_keybinding_hold_mode(&mut self, cx: &mut Context<Self>) {
        if let Some(hold_mode) = self.keybindings.hold_mode.take() {
            (hold_mode.release)(self);
            cx.notify();
        }
    }

    /// abstractKeybindingService.ts `_log`: an Info line of the Window log while troubleshooting.
    fn log_keybinding(&self, line: &str) {
        if self.keybindings.logging {
            self.output.log_window(3, &format!("[KeybindingService]: {line}"));
        }
    }

    fn chord_labels(&self) -> String {
        self.keybindings.chords.iter().map(|(_, label)| label.as_str()).collect::<Vec<_>>().join(", ")
    }

    /// The status bar message of multi-chord mode, shown while it lasts.
    pub(super) fn chord_status(&self) -> Option<String> {
        match self.keybindings.chords.len() {
            0 => None,
            1 => Some(format!("({}) was pressed. Waiting for second key of chord...", self.chord_labels())),
            _ => Some(format!("({}) was pressed. Waiting for next key of chord...", self.chord_labels())),
        }
    }

    fn expect_another_chord(&mut self, chord: Chord, window: &mut Window, cx: &mut Context<Self>) {
        self.keybindings.chords.push((chord, chord.label()));
        cx.notify();
        // _scheduleLeaveChordMode: leave when the window loses focus or 5s after the last chord.
        let entered = Instant::now();
        self.keybindings.chord_checker = Some(cx.spawn_in(window, async move |workbench, cx| {
            loop {
                cx.background_executor().timer(Duration::from_millis(500)).await;
                let left = workbench.update_in(cx, |workbench, window, cx| {
                    let leave = !window.is_window_active() || entered.elapsed() > Duration::from_secs(5);
                    if leave {
                        workbench.leave_chord_mode(cx);
                    }
                    leave
                });
                if left.unwrap_or(true) {
                    return;
                }
            }
        }));
    }

    fn leave_chord_mode(&mut self, cx: &mut Context<Self>) {
        self.keybindings.chords.clear();
        // Dropping the task cancels it; it may be the task running this call, which ends right after.
        self.keybindings.chord_checker.take();
        cx.notify();
    }

    /// `INotificationService.status` with `hideAfter`: a message at the far right of the status bar's left side.
    pub(super) fn show_status(&mut self, message: String, hide_after: Duration, window: &mut Window, cx: &mut Context<Self>) {
        let hide = cx.spawn_in(window, async move |workbench, cx| {
            cx.background_executor().timer(hide_after).await;
            let _ = workbench.update(cx, |workbench, cx| {
                workbench.status_message = None;
                cx.notify();
            });
        });
        self.status_message = Some((message, hide));
        cx.notify();
    }

    /// The context keys the keybindings' `when` clauses see: the keys extensions set, then the focused part's.
    pub fn key_context(&self, window: &Window) -> HashMap<String, Value> {
        let mut context = self.settings.lock().unwrap().configuration.context_keys();
        context.extend(self.context_keys.clone());
        // update.ts CONTEXT_UPDATE_STATE.
        context.insert("updateState".into(), json!(self.update_state.type_name()));
        // update.ts MAJOR_MINOR_UPDATE_AVAILABLE, set while an update is ready.
        if let crate::update::State::Ready { update, .. } = &self.update_state {
            let current = crate::product::display_version();
            context.insert("majorMinorUpdateAvailable".into(), json!(super::update::is_major_minor_update(&current, &update.product_version)));
        }
        // contextkeys.ts ProductQualityContext.
        context.insert("productQualityType".into(), json!(crate::product::quality().unwrap_or_default()));
        // list.contribution.ts `ListContext`; listSupportsKeyboardNavigation is the deprecated name.
        for key in ["listSupportsTypeNavigation", "listSupportsKeyboardNavigation"] {
            context.entry(key.into()).or_insert(json!(true));
        }
        let editor_focused = self.editor_focus.is_focused(window);
        // The sticky lines, the hover, the find widget and the code action widget are part of the editor's DOM, so their focus is the editor's but not its text's.
        let (find_focused, replace_focused) = (self.find.find_focus.is_focused(window), self.find.replace_focus.is_focused(window));
        let button_focused = self.find.button_focus.values().any(|focus| focus.is_focused(window));
        context.insert("editorFocus".into(), json!(editor_focused || self.sticky_scroll.is_focused(window) || self.content_hover_focused(window) || self.standalone_color_picker_focus.is_focused(window) || find_focused || replace_focused || button_focused || self.rename_input_focused(window) || self.action_widget_in_editor_focused(window)));
        context.insert("editorTextFocus".into(), json!(editor_focused));
        context.insert("textInputFocus".into(), json!(editor_focused));
        // simpleCommentEditor.ts `ctxCommentEditorFocused`.
        let comment_editor = self.editors.active().is_some_and(|editor| editor.document().scheme == super::comments::INPUT_SCHEME);
        context.insert("commentEditorFocused".into(), json!(editor_focused && comment_editor));
        // commentThreadWidget.ts `CommentContextKeys.commentFocused`: the focus is in a thread's comments.
        context.insert("commentFocused".into(), json!(self.comments.thread_focus.is_focused(window)));
        // walkThroughPart.ts WALK_THROUGH_FOCUS: the page's content element, not one of its editors, has the focus.
        if self.playground_focused(window) {
            context.insert("interactivePlaygroundFocus".into(), json!(true));
        }
        if editor_focused {
            // contextkeys.ts `InputFocusedContext`: the editor's textarea is an editable element.
            context.insert("inputFocus".into(), json!(true));
        }
        self.notifications_context(window, &mut context);
        self.banner_context(window, &mut context);
        self.host_context(window, &mut context);
        self.layout_context(&mut context);
        if let Some(alignment) = self.quick_input_alignment(window) {
            context.insert("quickInputAlignment".into(), json!(alignment));
        }
        // views.ts `FocusedViewContext` is '' while no view has focus, so `focusedView != ''` is false then.
        context.insert("focusedView".into(), json!(self.focused_movable_view(window).unwrap_or_default()));
        context.insert("statusBarFocused".into(), json!(self.status_bar_focus.is_focused(window)));
        self.editor_groups_context(&mut context);
        self.auxiliary_window_context(window, &mut context);
        self.history_context(&mut context);
        self.list_scroll_context(window, &mut context);
        context.insert("editorIsOpen".into(), json!(self.editors.active().is_some()));
        // editorPart.ts: `editorTabsVisible` is `showTabs === 'multiple'`.
        context.insert("editorTabsVisible".into(), json!(self.editor_show_tabs() == "multiple"));
        // viewDescriptorService.ts `<view id>.active`: the Changes view has no `when`, so it is always active.
        context.insert("workbench.scm.active".into(), json!(true));
        context.insert("scm.providerCount".into(), json!(self.scm.model.providers.len()));
        context.insert("dirtyWorkingCopies".into(), json!(self.editors.all_editors().any(|editor| editor.is_dirty())));
        // toggleMultiCursorModifier.ts `MultiCursorModifierContextKeyController`.
        context.insert("multiCursorModifier".into(), json!(if self.global_editor_option(&MULTI_CURSOR_MODIFIER) == "ctrlCmd" { "ctrlCmd" } else { "altKey" }));
        self.word_wrap_context(&mut context);
        self.action_widget_context(&mut context);
        self.problems_context(window, &mut context);
        self.comments_filter_context(window, &mut context);
        self.testing_filter_context(window, &mut context);
        self.view_containers_context(&mut context);
        self.refactor_preview_context(&mut context);
        self.modal_group_context(window, &mut context);
        // contextkeys.ts WorkbenchContextKeysHandler: the desktop build supports every workspace kind.
        let workbench_state = match self.workspace() {
            None => "empty",
            Some(workspace) if workspace.file.is_some() => "workspace",
            Some(_) => "folder",
        };
        context.insert("workbenchState".into(), json!(workbench_state));
        context.insert("workspaceFolderCount".into(), json!(self.workspace().map_or(0, |workspace| workspace.folders.len())));
        context.insert("resourceSelectedForCompare".into(), json!(self.resource_to_compare.is_some()));
        // RemoteNameContext of a local window.
        context.insert("remoteName".into(), json!(""));
        // workspace.contribution.ts WorkspaceTrustContextKeys.
        context.insert("isWorkspaceTrustEnabled".into(), json!(self.workspace_trust.enabled));
        context.insert("isWorkspaceTrusted".into(), json!(self.workspace_trust.is_trusted()));
        for key in ["openFolderWorkspaceSupport", "enterMultiRootWorkspaceSupport", "emptyWorkspaceSupport"] {
            context.insert(key.into(), json!(true));
        }
        // viewDescriptorService.ts: the Explorer, Search and Extensions containers always hold their views.
        context.insert("viewContainer.workbench.view.extensions.enabled".into(), json!(true));
        for (container, view) in [("workbench.view.explorer", "workbench.explorer.fileView"), ("workbench.view.search", "workbench.view.search")] {
            context.insert(format!("viewContainer.{container}.enabled"), json!(true));
            context.insert(format!("{view}.active"), json!(true));
        }
        if let Some(index) = self.editors.active_index() {
            context.insert("activeEditorIsLastInGroup".into(), json!(index == self.editors.editors.len() - 1));
            context.insert("activeEditorIsPinned".into(), json!(self.editors.editors[index].sticky));
        }
        if let Some(editor) = self.editors.active() {
            let breadcrumbs_possible = self.breadcrumbs_possible(editor);
            context.insert("breadcrumbsPossible".into(), json!(breadcrumbs_possible));
            context.insert("breadcrumbsVisible".into(), json!(self.breadcrumbs_visible(editor)));
            context.insert("breadcrumbsActive".into(), json!(self.breadcrumbs_active(window)));
            context.insert("breadcrumbsHasSymbols".into(), json!(breadcrumbs_possible && !self.breadcrumb_symbols(editor).is_empty()));
            let pane = match editor.document().scheme.as_str() {
                _ if self.playground_active() => "workbench.editor.walkThroughPart",
                super::welcome_page::WALKTHROUGH_SCHEME => "gettingStartedPage",
                super::disassembly_view::DISASSEMBLY_SCHEME => "workbench.debug.disassemblyView",
                _ if self.active_notebook_editor().is_some() => "workbench.editor.notebook",
                // editor.contribution.ts: `TextResourceEditor` shows `UntitledTextEditorInput`.
                "untitled" => "workbench.editors.textResourceEditor",
                // textfiles.ts `TEXT_FILE_EDITOR_ID`.
                _ => "workbench.editors.files.textFileEditor",
            };
            context.insert("activeEditor".into(), json!(pane));
            // contextkeys.ts `applyAvailableEditorIds`; every use reads it as a boolean, so the showing editor's id stands in for the list.
            if let Some((_, editor_id)) = self.active_editor_type() {
                context.insert("activeEditorAvailableEditorIds".into(), json!(editor_id));
            }
            self.webview_editor_context(&mut context);
            self.insert_diff_editor_context(&mut context);
            self.insert_multi_diff_editor_context(&mut context, window);
            self.insert_merge_editor_context(&mut context, window);
            // The port opens only files, never untitled editors (editorGroupView.ts).
            context.insert("activeEditorCanRevert".into(), json!(true));
            let readonly = self.active_editor_readonly().is_some();
            context.insert("editorReadonly".into(), json!(readonly));
            context.insert("activeEditorIsReadonly".into(), json!(readonly));
            context.insert("activeEditorCanToggleReadonly".into(), json!(editor.document().scheme != "untitled"));
            context.insert("messageVisible".into(), json!(self.editor_message_visible()));
            context.insert("markersNavigationVisible".into(), json!(self.markers_navigation_visible()));
            context.insert("dirtyDiffVisible".into(), json!(self.quick_diff_visible()));
            context.insert("quickDiffDecorationCount".into(), json!(self.quick_diff_decoration_count()));
            self.goto_symbol_context(&mut context);
            self.references_peek_context(window, &mut context);
            self.hierarchy_peek_context(editor, window, &mut context);
            self.testing_peek_context(editor, &mut context);
            self.debug_hover_context(window, &mut context);
            context.insert("editorHoverVisible".into(), json!(self.content_hover_visible()));
            context.insert("editorHoverFocused".into(), json!(self.content_hover_focused(window)));
            self.suggest_context(&mut context);
            self.snippet_context(&mut context);
            self.tab_completion_context(&mut context);
            self.parameter_hints_context(&mut context);
            self.code_actions_context(&mut context);
            self.paste_edits_context(&mut context);
            self.commenting_context(&mut context);
            self.code_lens_context(&mut context);
            self.standalone_color_picker_context(&mut context, window);
            self.inline_completions_context(&mut context);
            self.inlay_hints_accessibility_context(&mut context);
            self.rename_context(&mut context);
            self.format_context(&mut context);
            self.linked_editing_context(&mut context);
            context.insert("editorHasSelection".into(), json!(editor.selections.iter().any(|selection| !selection.is_empty())));
            context.insert("editorHasMultipleSelections".into(), json!(editor.selections.len() > 1));
            context.insert("selectionAnchorSet".into(), json!(editor.selection_anchor.is_some()));
            context.insert("emptyEditorHintActionsVisible".into(), json!(self.empty_editor_hint_actions_visible()));
            context.insert("editorTabMovesFocus".into(), json!(self.tab_focus_mode()));
            context.insert("editorColumnSelection".into(), json!(self.editor_option(editor, &COLUMN_SELECTION)));
            context.insert("foldingEnabled".into(), json!(self.editor_option(editor, &FOLDING)));
            // A custom editor diff has no code editor.
            if self.editors.active_diff().is_none_or(|diff| diff.custom.is_none()) {
                context.insert("editorLangId".into(), json!(editor.document().language_id));
            }
            // ResourceContextKey follows the editor input, not a focused comment editor in it.
            let resource = self.editors.pane_editor().expect("an active editor is in a pane").document();
            context.insert("resourceLangId".into(), json!(resource.language_id));
            self.sticky_scroll_context(window, &mut context);
            self.cancellable_operation_context(&mut context);
            // findModel.ts CONTEXT_FIND_WIDGET_VISIBLE, CONTEXT_FIND_INPUT_FOCUSED, CONTEXT_REPLACE_INPUT_FOCUSED.
            context.insert("findWidgetVisible".into(), json!(self.find.controller.state.is_revealed));
            context.insert("findInputFocussed".into(), json!(find_focused));
            context.insert("replaceInputFocussed".into(), json!(replace_focused));
            if find_focused || replace_focused {
                context.insert("inputFocus".into(), json!(true));
                // contextScopedHistoryWidget.ts: the inputs are history widgets, navigable both ways.
                context.insert("historyNavigationWidgetFocus".into(), json!(true));
                context.insert("historyNavigationForwardsEnabled".into(), json!(true));
                context.insert("historyNavigationBackwardsEnabled".into(), json!(true));
            }
            context.insert("isFileSystemResource".into(), json!(crate::editor::on_disk(&resource.scheme)));
            let path = &resource.path;
            context.insert("resource".into(), json!(crate::editor::uri_string(&resource.scheme, path)));
            context.insert("resourceScheme".into(), json!(resource.scheme));
            context.insert("resourceFilename".into(), json!(path.file_name().map(|name| name.to_string_lossy()).unwrap_or_default()));
            context.insert("resourceExtname".into(), json!(path.extension().map(|ext| format!(".{}", ext.to_string_lossy())).unwrap_or_default()));
            // A notebook editor's resource keys are its notebook's (ResourceContextKey of the editor input), not a cell's.
            if let Some((scheme, path)) = self.active_notebook_resource() {
                context.insert("isFileSystemResource".into(), json!(crate::editor::on_disk(&scheme)));
                context.insert("resource".into(), json!(crate::editor::uri_string(&scheme, &path)));
                context.insert("resourceScheme".into(), json!(scheme));
                context.insert("resourceFilename".into(), json!(path.file_name().map(|name| name.to_string_lossy()).unwrap_or_default()));
                context.insert("resourceExtname".into(), json!(path.extension().map(|ext| format!(".{}", ext.to_string_lossy())).unwrap_or_default()));
                context.insert("resourceLangId".into(), json!(self.languages.guess_language(&path, "")));
                self.notebook_context(editor, editor_focused, window, &mut context);
            }
        }
        // notebookEditorServiceImpl.ts: `mostRecentReplEditor` and `interactiveWindowOpen` are global.
        if let Some(repl) = &self.host.notebooks.most_recent_repl {
            context.insert("mostRecentReplEditor".into(), json!(repl));
        }
        context.insert("interactiveWindowOpen".into(), json!(self.host.notebooks.interactive_window_open));
        self.quick_input_context(window, &mut context);
        match self.side_bar_view {
            SideBarView::Explorer => self.explorer_context(window, &mut context),
            SideBarView::Search => self.search_context(window, &mut context),
            SideBarView::Scm => {}
            SideBarView::Extensions => self.extensions_context(true, window, &mut context),
            SideBarView::Debug | SideBarView::Testing | SideBarView::Contributed(_) | SideBarView::Generated(_) => {}
        }
        if self.container_location(super::extensions_view::VIEWLET_ID) != super::layout::Part::SideBar {
            self.extensions_context(false, window, &mut context);
        }
        self.open_editors_context(window, &mut context);
        self.outline_context(window, &mut context);
        // After the side bar's keys, whose list is not focused: the notebook's cell list (notebookCellList.ts) and the breadcrumbs picker are lists.
        if self.notebook_views.list_focus.is_focused(window) || self.breadcrumbs.picker.as_ref().is_some_and(|picker| picker.focus.is_focused(window)) {
            context.insert("listFocus".into(), json!(true));
        }
        self.scm_key_context(window, &mut context);
        self.debug_context(window, &mut context);
        self.testing_service_context(&mut context);
        self.testing_results_list_context(window, &mut context);
        self.testing_continuous_context(&mut context);
        self.keybindings_editor_context(window, &mut context);
        self.settings_editor_context(window, &mut context);
        self.search_editor_context(window, &mut context);
        self.output_context(window, &mut context);
        self.terminal_context(window, &mut context);
        self.task_context(&mut context);
        self.timeline_context(window, &mut context);
        self.accessibility_context(&mut context);
        context
    }

    /// `openGlobalKeybindingSettings(textual: true)`: opens keybindings.json, created with upstream's header first;
    /// with `workbench.settings.openDefaultKeybindings` the default keybindings stay in the active group and
    /// keybindings.json opens in a group added to its right.
    pub(super) fn open_keybindings_file(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        let Some(file) = self.keybindings.user_file.clone() else { return Outcome::error("no keybindings.json") };
        if !file.exists() {
            let created = file.parent().map_or(Ok(()), std::fs::create_dir_all);
            if let Err(error) = created.and_then(|_| std::fs::write(&file, "// Place your key bindings in this file to override the defaults\n[\n]")) {
                return Outcome::error(format!("writing {}: {error}", file.display()));
            }
        }
        if self.setting("workbench.settings.openDefaultKeybindings") == json!(true) {
            let source = self.editors.group_ids_mru().into_iter().find(|group| *group != crate::editor::MODAL_GROUP).expect("the part has a group");
            self.activate_group(source);
            let side = self.add_group_beside(crate::editor_grid::Direction::Right);
            self.open_default_keybindings(window, cx);
            self.activate_group(side);
            self.open_file_in_active_group(files::user_data::SCHEME, file, true, window, cx);
            return Outcome::done();
        }
        self.open_preferences_file(files::user_data::SCHEME, file, window, cx);
        Outcome::done()
    }

    /// `editorService.openEditor({ resource: undefined, contents, options: { pinned: true } })` of inspectKeybindings.ts.
    pub(super) fn open_untitled_with_contents(&mut self, contents: &str, window: &mut Window, cx: &mut Context<Self>) {
        let path = (1..).map(|n| PathBuf::from(format!("Untitled-{n}"))).find(|path| self.editors.model("untitled", path).is_none()).expect("a free name");
        let document = TextDocument::untitled(&path, contents, None, &self.languages, &self.settings.lock().unwrap());
        self.leave_locked_group("untitled", &path);
        self.editors.open(document, false);
        window.focus(&self.editor_focus, cx);
        self.editors_changed(cx);
    }

    /// The `_setContext` command (extensions call it as `setContext`): `createKey(String(key), value)`.
    pub(super) fn register_context_commands(&mut self) {
        self.commands.register("workbench.action.openGlobalKeybindingsFile", |workbench, _, window, cx| workbench.open_keybindings_file(window, cx));
        self.commands.register("workbench.action.inspectKeyMappings", |workbench, _, window, cx| {
            let resolved = keybindings::dump_resolve_keybinding_debug_info(&workbench.keybindings.defaults, &workbench.keybindings.overrides);
            workbench.open_untitled_with_contents(&crate::keyboard_layout::dump_debug_info(crate::keyboard_mapper::current().as_deref(), &resolved), window, cx);
            Outcome::done()
        });
        self.commands.register("workbench.action.inspectKeyMappingsJSON", |workbench, _, window, cx| {
            workbench.open_untitled_with_contents(&crate::keyboard_layout::dump_debug_info_json(), window, cx);
            Outcome::done()
        });
        self.commands.register("_setContext", |workbench, args, _, cx| {
            let mut args = args.into_iter();
            let key = match args.next() {
                Some(Value::String(key)) => key,
                Some(key) => key.to_string(),
                None => return Outcome::error("setContext needs a key"),
            };
            let value = stringify_uris(args.next().unwrap_or(Value::Null));
            // contextKeyService.ts `setValue` fires `onDidChangeContext` only for a value not `equals` the old one: menus and views with `when` clauses update.
            if workbench.context_keys.insert(key, value.clone()).as_ref() != Some(&value) {
                cx.notify();
            }
            Outcome::done()
        });
        // contextKeyService.ts `getContextKeyInfo`: the reference's RawContextKey.all() (port/tools/ref-commands).
        self.commands.register("getContextKeyInfo", |_, _, _, _| Outcome::Ready(Ok(serde_json::from_str(include_str!("../contextkey/reference-context-keys.json")).expect("valid JSON"))));
        // mainThreadLogService.ts: `loggerService.setLogLevel(parseLogLevel(level))` and `logService.getLevel()`.
        self.commands.register("_extensionTests.setLogLevel", |workbench, args, _, _| {
            if let Some(level) = args.first().and_then(Value::as_str).and_then(crate::output::log_levels::parse_log_level) {
                workbench.set_log_level(level);
            }
            Outcome::done()
        });
        self.commands.register("_extensionTests.getLogLevel", |workbench, _, _, _| Outcome::Ready(Ok(Value::from(crate::output::log_level_name(workbench.output.log_level)))));
    }
}

/// contextKeyService.ts `stringifyURIs`: a context value's URIs become their `toString()`, which `in` compares.
fn stringify_uris(value: Value) -> Value {
    match value {
        Value::Object(uri) if uri.get("$mid") == Some(&json!(1)) => Value::String(crate::debug::uri_string(&Value::Object(uri))),
        Value::Object(map) => Value::Object(map.into_iter().map(|(key, value)| (key, stringify_uris(value))).collect()),
        Value::Array(items) => Value::Array(items.into_iter().map(stringify_uris).collect()),
        other => other,
    }
}

/// `notificationService.warn(err)` of a failed keybinding command; the caller holds the workbench, so the warning waits a tick.
pub(super) fn report_failure(outcome: Outcome, cx: &mut Context<Workbench>) {
    cx.spawn(async move |workbench, cx| {
        let result = match outcome {
            Outcome::Ready(result) => result,
            Outcome::Pending(pending) => pending.await.unwrap_or(Ok(Value::Null)),
        };
        if let Err(error) = result {
            let _ = workbench.update(cx, |workbench, cx| {
                workbench.notify_warning(error["message"].as_str().unwrap_or_default());
                cx.notify();
            });
        }
    })
    .detach();
}

#[cfg(test)]
mod tests;