Visual Studio Code, rebuilt in Rust
Rust
//! The editor part's context menus: the text's and the scrollbar's (contextmenu.ts) and the tabs'
//! (multiEditorTabsControl.ts).
use std::cell::Cell;
use std::rc::Rc;
use gpui::{Bounds, Context, Div, Pixels, Point, Rgba, Size, Stateful, Window, canvas, prelude::*, px};
use serde_json::{Value, json};
use super::Workbench;
use super::model_events::Cursor;
use crate::editor::Reveal;
use crate::commands::Outcome;
use crate::editor::minimap::{MinimapSide, MinimapSize};
use crate::editor::{Position, column_at_visible};
use crate::menus::{MenuAction, MenuId};
use crate::workbench::editor_options::CONTEXTMENU;
impl Workbench {
pub(super) fn register_editor_menu_commands(&mut self) {
// editorCommands.ts `TOGGLE_KEEP_EDITORS_COMMAND_ID`: Enable Preview Editors.
self.commands.register("workbench.action.toggleKeepEditors", |workbench, _, _, cx| {
let enabled = workbench.setting("workbench.editor.enablePreview") == json!(true);
workbench.update_setting("workbench.editor.enablePreview", json!(!enabled));
workbench.editors.set_previews_disabled(enabled);
cx.notify();
Outcome::done()
});
// layoutActions.ts `ConfigureEditorAction`: the Settings editor at `workbench.editor`.
self.commands.register("workbench.action.configureEditor", |workbench, _, window, cx| {
workbench.execute_command("workbench.action.openSettings", vec![json!({ "jsonEditor": false, "query": "workbench.editor" })], window, cx)
});
// layoutActions.ts `ConfigureEditorTabsAction`.
self.commands.register("workbench.action.configureEditorTabs", |workbench, _, window, cx| {
workbench.execute_command("workbench.action.openSettings", vec![json!({ "jsonEditor": false, "query": "workbench.editor tab" })], window, cx)
});
// layoutActions.ts `AbstractSetShowTabsAction` and the editor actions position actions: each writes one setting.
let setters = [
("workbench.action.hideEditorTabs", "workbench.editor.showTabs", "none"),
("workbench.action.showMultipleEditorTabs", "workbench.editor.showTabs", "multiple"),
("workbench.action.showEditorTab", "workbench.editor.showTabs", "single"),
("workbench.action.zenHideEditorTabs", "zenMode.showTabs", "none"),
("workbench.action.zenShowMultipleEditorTabs", "zenMode.showTabs", "multiple"),
("workbench.action.zenShowEditorTab", "zenMode.showTabs", "single"),
("workbench.action.editorActionsTitleBar", "workbench.editor.editorActionsLocation", "titleBar"),
("workbench.action.editorActionsDefault", "workbench.editor.editorActionsLocation", "default"),
("workbench.action.hideEditorActions", "workbench.editor.editorActionsLocation", "hidden"),
("workbench.action.showEditorActions", "workbench.editor.editorActionsLocation", "default"),
];
for (id, setting, value) in setters {
self.commands.register(id, move |workbench, _, _, cx| {
workbench.update_setting(setting, json!(value));
cx.notify();
Outcome::done()
});
}
}
/// The editor title's More Actions... (`ToolBar`'s `...`): `MenuId.EditorTitle` but its `navigation` group, a
/// merge editor's layout items first, right aligned below the button (editorTabsControl.ts `AnchorAlignment.RIGHT`).
/// In the title bar (`in_title_bar`) it is the title toolbar's overflow, which adds the layout control's secondary
/// items.
pub(super) fn editor_title_more_button(&self, color: Rgba, in_title_bar: bool, cx: &mut Context<Self>) -> Stateful<Div> {
let bounds = Rc::new(Cell::new(Bounds::default()));
let measured = bounds.clone();
let open = self.context_menu.is_some() && self.editor_groups.title_menu_group == Some(self.editors.id);
self.icon("ellipsis", 22., 16., color)
.id(if in_title_bar { "title-bar-more" } else { "editor-title-more" })
.debug_selector(move || if in_title_bar { "title-bar-more" } else { "editor-title-more" }.into())
.rounded(px(4.))
.when(open, |icon| icon.bg(self.color("toolbar.activeBackground")))
.cursor_pointer()
.hover(|icon| icon.bg(self.color("toolbar.hoverBackground")))
.on_mouse_down(gpui::MouseButton::Left, cx.listener(move |workbench, _: &gpui::MouseDownEvent, window, cx| {
cx.stop_propagation();
workbench.show_editor_title_menu(bounds.get(), in_title_bar, window, cx);
}))
.child(canvas(move |element_bounds, _, _| measured.set(element_bounds), |_, _, _, _| {}).absolute().size_full())
.child(self.hover_target("editor-title-more-hover", super::hover::HoverContent::Text("More Actions...".into()), super::hover::HoverOptions::mouse()))
}
pub(super) fn show_editor_title_menu(&mut self, anchor: Bounds<Pixels>, in_title_bar: bool, window: &mut Window, cx: &mut Context<Self>) {
let mut context = self.key_context(window);
context.insert("isSessionsWindow".into(), json!(false));
let mut actions = Vec::new();
// titlebarPart.ts `createActionToolBarMenus`: the title bar has no editor actions without an active editor.
let editor_actions = !in_title_bar || self.title_bar_has_editor_actions();
if editor_actions && (!in_title_bar || self.editors.active_index().is_some()) {
actions = self.editor_title_secondary_actions(&context);
}
// layoutActions.ts `CustomizeLayoutAction`: in `MenuId.LayoutControlMenu`'s `1_layout` group while the editor
// actions are in the title bar.
if in_title_bar && editor_actions && self.setting("workbench.layoutControl.enabled") != json!(false) {
if !actions.is_empty() {
actions.push(MenuAction::Separator);
}
actions.push(MenuAction::Command { id: "workbench.action.customizeLayout".into(), title: "Customize Layout...".into(), enabled: true, checked: false, alt: None });
}
if in_title_bar {
let global = self.title_bar_global_secondary_actions(&context);
if !actions.is_empty() && !global.is_empty() {
actions.push(MenuAction::Separator);
}
actions.extend(global);
}
let args = self.editors.active().map(document_uri).into_iter().collect();
self.show_dropdown_menu_actions(actions, &context, anchor, args, window, cx);
self.editor_groups.title_menu_group = Some(self.editors.id);
}
/// editorGroupView.ts `createEditorActions`' secondary actions: a merge editor's layout items, `MenuId.EditorTitle`
/// but its `navigation` group, and "Reopen Editor With" last while another editor type can open the resource.
fn editor_title_secondary_actions(&mut self, context: &std::collections::HashMap<String, Value>) -> Vec<MenuAction> {
let mut actions = match self.editors.active_merge() {
Some(_) => self.merge_more_actions(),
None => Vec::new(),
};
let generic = crate::menus::menu_group_actions(&self.menus, MenuId::EditorTitle, context, |group| group != "navigation");
if !actions.is_empty() && !generic.is_empty() {
actions.push(MenuAction::Separator);
}
actions.extend(generic);
if let Some(types) = self.available_editor_types(&[]) {
if !actions.is_empty() {
actions.push(MenuAction::Separator);
}
let reopen_with = self.editor_type_actions(types);
actions.push(MenuAction::Submenu { title: "Reopen Editor With".into(), actions: reopen_with, checked: false });
}
actions
}
/// editorGroupView.ts `onShowContainerContextMenu`: `MenuId.EmptyEditorGroupContext` of an empty group, which
/// becomes the active one first.
pub(super) fn show_empty_group_context_menu(&mut self, group: u32, pointer: Point<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
self.activate_group(group);
self.editors_changed(cx);
let context = self.key_context(window);
self.show_context_menu(MenuId::EmptyEditorGroupContext, &context, point_anchor(pointer), vec![json!({ "groupId": group })], window, cx);
}
/// multiEditorTabsControl.ts: a right press in the tabs container off a tab shows `MenuId.EditorTabsBarContext`
/// with the group as its context; focus goes to the editor, as the tab's menu does.
pub(super) fn show_tabs_bar_context_menu(&mut self, group: u32, pointer: Point<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
let context = self.key_context(window);
window.focus(&self.editor_focus, cx);
self.show_context_menu(MenuId::EditorTabsBarContext, &context, point_anchor(pointer), vec![json!({ "groupId": group })], window, cx);
}
/// `ContextMenuController._onContextMenu`: focus the editor, put the cursor at the pointer unless a selection
/// holds it, then show `MenuId.EditorContext` with the model's uri as argument.
pub(super) fn show_editor_context_menu(&mut self, line: usize, visible: f32, pointer: Point<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
window.focus(&self.editor_focus, cx);
let editor = self.editors.active_mut().expect("text is clickable only with an editor open");
let position = Position::new(line, column_at_visible(&editor.document().lines[line], visible, editor.document().indentation.tab_size));
if !editor.selections.iter().any(|selection| selection.start() <= position && position <= selection.end()) {
editor.move_to(position, false);
self.model_content_changed(None, Cursor { moved: true, source: "mouse", reveal: Reveal::All }, cx);
}
let uri = document_uri(self.editors.active().expect("checked above"));
let context = self.key_context(window);
self.show_context_menu(MenuId::EditorContext, &context, point_anchor(pointer), vec![uri], window, cx);
}
/// `ShowContextMenu` (Shift+F10): `MenuId.EditorContext` below the cursor, which stays where it is; not with
/// `editor.contextmenu` off.
pub(super) fn show_editor_context_menu_at_cursor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(editor) = self.editors.active() else { return };
if !self.editor_option(editor, &CONTEXTMENU) {
return;
}
let Some(anchor) = self.cursor_anchor(window) else { return };
let uri = document_uri(self.editors.active().expect("an anchor needs an editor"));
let context = self.key_context(window);
self.show_context_menu(MenuId::EditorContext, &context, point_anchor(anchor), vec![uri], window, cx);
}
/// editorLineNumberMenu.ts `doShow`: the testing group of the line's test glyph (testingDecorations.ts's
/// gutter actions generator, `1_testing`), then `MenuId.EditorLineNumberContext` with `editorLineNumber` and the
/// `{ lineNumber, uri }` argument. On the line numbers, a line no selection touches is selected first.
pub(super) fn show_line_number_context_menu(&mut self, line: usize, pointer: Point<Pixels>, on_line_numbers: bool, window: &mut Window, cx: &mut Context<Self>) {
let editor = self.editors.active_mut().expect("the gutter is clickable only with an editor open");
let line_end = Position::new(line, editor.document().lines[line].chars().count());
let touched = editor.selections.iter().any(|selection| !selection.is_empty() && selection.start() <= line_end && Position::new(line, 0) <= selection.end());
if on_line_numbers && !touched {
let before = editor.selections.clone();
editor.set_selections(vec![crate::editor::Selection { anchor: Position::new(line, 0), head: line_end }]);
let moved = editor.selections != before;
self.cursor_position_changed(Cursor { moved, source: "api", reveal: Reveal::Nothing }, cx);
}
let editor = self.editors.active().expect("checked above");
let mut context = self.key_context(window);
context.insert("editorLineNumber".into(), json!(line + 1));
let arg = json!({ "lineNumber": line + 1, "uri": document_uri(editor) });
// editorLineNumberMenu.ts `doShow`: the generators' groups sorted by name (`1_testing`, `2_debug`), then the menu.
let groups = [self.test_gutter_actions(line as u32 + 1, window), self.debug_gutter_actions(line as u32 + 1), crate::menus::menu_actions(&self.menus, MenuId::EditorLineNumberContext, &context)];
let mut actions = Vec::new();
for group in groups.into_iter().filter(|group| !group.is_empty()) {
if !actions.is_empty() {
actions.push(MenuAction::Separator);
}
actions.extend(group);
}
self.show_context_menu_actions(actions, &context, point_anchor(pointer), vec![arg], window, cx);
}
/// `onTabContextMenu`: `MenuId.EditorTitleContext` with the context keys of the right-clicked editor, which
/// stays inactive; the commands get its resource and `{ groupId, editorIndex }`. Focus goes back to the group.
/// `anchor` is the pointer, or the tab itself for Shift+F10.
pub(super) fn show_tab_context_menu(&mut self, index: usize, anchor: Bounds<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
let editors = &self.editors.editors;
let mut context = self.key_context(window);
let editor_keys = [
("activeEditorIsNotPreview", json!(!editors[index].preview)),
("activeEditorIsPinned", json!(editors[index].sticky)),
("activeEditorIsDirty", json!(self.tab_shows_dirty(index))),
("splitEditorsVertically", json!(self.setting("workbench.editor.openSideBySideDirection") == "down")),
("activeEditorIsLastInGroup", json!(index == editors.len() - 1)),
("activeEditorCannotClose", json!(false)),
("groupEditorsCount", json!(editors.len())),
("multipleEditorsSelectedInGroup", json!(false)),
("editorTabsVisible", json!(true)),
("config.workbench.editor.enablePreview", self.setting("workbench.editor.enablePreview")),
];
context.extend(editor_keys.map(|(key, value)| (key.to_string(), value)));
let args = vec![document_uri(&editors[index]), json!({ "groupId": 0, "editorIndex": index })];
window.focus(&self.editor_focus, cx);
self.show_context_menu(MenuId::EditorTitleContext, &context, anchor, args, window, cx);
}
/// `_showScrollbarContextMenu`: on the scrollbar or the minimap, the `editor.minimap.*` toggles and choices, each
/// writing its setting; all but Minimap are disabled while the minimap is off. Focus comes back to the editor.
pub(super) fn show_scrollbar_context_menu(&mut self, pointer: Point<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
let settings = self.minimap_settings(self.editors.active().expect("the scrollbar shows only with an editor open"));
// diffEditorEditors.ts `_adjustOptionsForSubEditor` turns the minimap off in both sides.
let enabled = settings.enabled && self.editors.active_diff().is_none();
let render_characters = settings.layout.render_characters;
let size = match settings.layout.size {
MinimapSize::Proportional => "proportional",
MinimapSize::Fill => "fill",
MinimapSize::Fit => "fit",
};
let slider = if settings.slider_always { "always" } else { "mouseover" };
let side = if settings.layout.side == MinimapSide::Left { "left" } else { "right" };
let mut actions = vec![
self.setting_action("Minimap", "editor.minimap.enabled", json!(!enabled), true, enabled),
MenuAction::Separator,
self.setting_action("Render Characters", "editor.minimap.renderCharacters", json!(!render_characters), enabled, render_characters),
];
let choices: [(&str, &'static str, &str, &[(&str, &str)]); 3] = [
("Vertical size", "editor.minimap.size", size, &[("Proportional", "proportional"), ("Fill", "fill"), ("Fit", "fit")]),
("Slider", "editor.minimap.showSlider", slider, &[("Mouse Over", "mouseover"), ("Always", "always")]),
("Side", "editor.minimap.side", side, &[("Right", "right"), ("Left", "left")]),
];
for (label, key, current, options) in choices {
if !enabled {
actions.push(MenuAction::Command { id: String::new(), title: label.into(), enabled: false, checked: false, alt: None });
continue;
}
let choices = options.iter().map(|(title, value)| self.setting_action(title, key, json!(value), true, current == *value)).collect();
actions.push(MenuAction::Submenu { title: label.into(), actions: choices, checked: false });
}
window.focus(&self.editor_focus, cx);
let context = self.key_context(window);
self.show_context_menu_actions(actions, &context, point_anchor(pointer), Vec::new(), window, cx);
}
/// A menu item writing `value` to `key` (`createAction` with `updateValue`), registered under an id of its own.
fn setting_action(&mut self, title: &str, key: &'static str, value: Value, enabled: bool, checked: bool) -> MenuAction {
let id = format!("_editor.scrollbarContextMenu.{key}={value}");
if self.commands.get(&id).is_none() {
self.commands.register(id.clone(), move |workbench, _, _, cx| {
workbench.update_setting(key, value.clone());
cx.notify();
Outcome::done()
});
}
MenuAction::Command { id, title: title.into(), enabled, checked, alt: None }
}
/// `resolveCommandsContext`: the editor a tab context menu passed, else the active one.
pub(super) fn context_editor(&self, args: &[Value]) -> Option<usize> {
match args.iter().find_map(|arg| arg.get("editorIndex")?.as_u64()) {
Some(index) => (index < self.editors.editors.len() as u64).then_some(index as usize),
None => self.editors.active_index(),
}
}
}
fn document_uri(editor: &crate::editor::OpenEditor) -> Value {
editor.document().uri()
}
pub(super) fn point_anchor(pointer: Point<Pixels>) -> Bounds<Pixels> {
Bounds { origin: pointer, size: Size::default() }
}
#[cfg(test)]
mod tests;