Visual Studio Code, rebuilt in Rust
Rust
//! The modal editor part (modalEditorPart.ts) for text and diff editors, the Settings, Keyboard Shortcuts, Profiles and Workspace Trust editors and Images
//! Preview: preferencesService.ts opens those editors and the settings and keybindings JSON files, and image_carousel.rs its editor, in `MODAL_GROUP` unless `workbench.editor.useModal` is `off`. The group lives outside the grid
//! like the panel's; the part shows its active editor without tabs, breadcrumbs or editor actions (`showTabs: none`,
//! `editorActionsLocation: hidden`) under the header with the editor's label, and closes with its last editor.
use std::path::{Path, PathBuf};
use gpui::{AnyElement, App, Context, Window, div, prelude::*, px};
use serde_json::{Value, json};
use super::Workbench;
use super::keybindings_editor_view::ModalHeader;
use crate::editor::{MODAL_GROUP, OpenEditor, TextDocument};
use crate::theme::ThemeKind;
#[cfg(test)]
mod tests;
/// The resource of the Settings editor (preferencesEditorInput.ts `SettingsEditor2Input`); keybindingsEditorInput.ts
/// has none, so the Keyboard Shortcuts editor's is the port's, in the same scheme, as are the Profiles and Workspace
/// Trust editors'.
pub const PREFERENCES_EDITOR_SCHEME: &str = "vscode-settings";
pub(super) const SETTINGS_EDITOR_PATH: &str = "/settingseditor";
pub(super) const KEYBINDINGS_EDITOR_PATH: &str = "/keybindingseditor";
pub(super) const PROFILES_EDITOR_PATH: &str = "/profileseditor";
pub(super) const WORKSPACE_TRUST_EDITOR_PATH: &str = "/workspacetrusteditor";
const PREFERENCES_EDITOR_PATHS: [&str; 4] = [SETTINGS_EDITOR_PATH, KEYBINDINGS_EDITOR_PATH, PROFILES_EDITOR_PATH, WORKSPACE_TRUST_EDITOR_PATH];
impl Workbench {
/// `getEditorGroupFromOptions`: the modal group unless `workbench.editor.useModal` is `off` or extension tests run.
pub(super) fn open_preferences_file(&mut self, scheme: &str, path: PathBuf, window: &mut Window, cx: &mut Context<Self>) {
if !self.uses_modal_group() {
return self.open_disk_resource(scheme, path, true, window, cx);
}
self.enter_modal_group(window, cx);
self.open_file_in_active_group(scheme, path, true, window, cx);
}
/// The Settings, Keyboard Shortcuts, Profiles or Workspace Trust editor (`path`) in the modal group, else in the
/// active group, pinned, activated where it is already.
pub(super) fn open_preferences_editor(&mut self, path: &str, window: &mut Window, cx: &mut Context<Self>) {
// preferencesService.ts: Settings takes `getEditorGroupFromOptions`, Keyboard Shortcuts `MODAL_GROUP`, Profiles
// and Workspace Trust `RequiresModal`; editorGroupFinder.ts lets `useModal: off` win over the last two.
let modal = match path {
SETTINGS_EDITOR_PATH => self.uses_modal_group(),
_ => self.setting("workbench.editor.useModal") != json!("off"),
};
match modal {
true => self.enter_modal_group(window, cx),
false => self.leave_side_group(),
}
let path = Path::new(path);
match self.editors.editors.iter().position(|editor| editor.document().is(PREFERENCES_EDITOR_SCHEME, path)) {
Some(index) => self.editors.activate(index),
None => {
let document = TextDocument::from_text(PREFERENCES_EDITOR_SCHEME, path, "", "utf8".into(), None, &self.languages, &self.settings.lock().unwrap());
self.editors.open(document, false);
}
}
self.editors_changed(cx);
}
/// editorGroupFinder.ts `doFindGroup`: with `workbench.editor.useModal: all` an editor opened without a group
/// goes to the modal part. Returns whether it does.
pub(super) fn enter_modal_group_for_all(&mut self, window: &Window, cx: &App) -> bool {
if self.setting("workbench.editor.useModal") != json!("all") {
return false;
}
self.enter_modal_group(window, cx);
true
}
fn enter_modal_group(&mut self, window: &Window, cx: &App) {
if !self.modal_group_open() {
self.editor_groups.modal_previous_focus = window.focused(cx);
}
self.editors.ensure_detached_group(MODAL_GROUP);
self.activate_group(MODAL_GROUP);
}
/// After a change of the editors: a closed Settings, Keyboard Shortcuts, Profiles or Workspace Trust editor drops
/// its state (`EditorInput.dispose`), and the focus a closed one had goes to the modal's new active editor, or back
/// to where it was before the modal opened.
pub(super) fn sync_preferences_editors(&mut self, cx: &mut Context<Self>) {
let alive = self.settings_editor.open || self.keybindings_editor.open || self.user_data_profiles.editor.open || self.trust_editor.open;
let Some(main_window) = self.auxiliary_windows.main_window.filter(|_| alive) else { return };
let workbench = cx.entity();
cx.defer(move |cx| {
let _ = main_window.update(cx, |_, window, cx| workbench.update(cx, |workbench, cx| workbench.drop_closed_preferences_editors(window, cx)));
});
}
fn drop_closed_preferences_editors(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let focused = PREFERENCES_EDITOR_PATHS.into_iter().find(|path| self.preferences_editor_focused(path, window));
if self.settings_editor.open && !self.preferences_editor_open(SETTINGS_EDITOR_PATH) {
self.dispose_settings_editor(cx);
}
if self.keybindings_editor.open && !self.preferences_editor_open(KEYBINDINGS_EDITOR_PATH) {
self.dispose_keybindings_editor();
}
if self.user_data_profiles.editor.open && !self.preferences_editor_open(PROFILES_EDITOR_PATH) {
self.dispose_profiles_editor(cx);
}
if self.trust_editor.open && !self.preferences_editor_open(WORKSPACE_TRUST_EDITOR_PATH) {
self.dispose_workspace_trust_editor(cx);
}
let active = self.modal_active_editor().map(|editor| (editor.document().scheme.clone(), editor.document().path.clone()));
let Some((scheme, path)) = active else {
let previous = self.editor_groups.modal_previous_focus.take();
if let Some(focus) = previous.filter(|_| focused.is_some()) {
window.focus(&focus, cx);
}
return cx.notify();
};
let text_focused = self.editor_focus.is_focused(window);
let preferences = PREFERENCES_EDITOR_PATHS.into_iter().find(|preferences| scheme == PREFERENCES_EDITOR_SCHEME && path.to_str() == Some(preferences));
match preferences {
Some(path) if text_focused || focused.is_some_and(|focused| focused != path) => self.focus_preferences_editor(path, window, cx),
Some(_) => {}
None if focused.is_some() => window.focus(&self.editor_focus, cx),
None => {}
}
cx.notify();
}
fn preferences_editor_focused(&self, path: &str, window: &Window) -> bool {
match path {
SETTINGS_EDITOR_PATH => self.settings_editor_focused(window),
KEYBINDINGS_EDITOR_PATH => self.keybindings_editor_focused(window),
PROFILES_EDITOR_PATH => self.profiles_editor_focused(window),
_ => self.workspace_trust_editor_focused(window),
}
}
fn focus_preferences_editor(&mut self, path: &str, window: &mut Window, cx: &mut Context<Self>) {
match path {
SETTINGS_EDITOR_PATH => self.focus_settings_search(false, window, cx),
KEYBINDINGS_EDITOR_PATH => self.focus_keybindings_search(window, cx),
PROFILES_EDITOR_PATH => self.focus_profiles_editor(window, cx),
_ => self.focus_workspace_trust_editor(window, cx),
}
}
fn preferences_editor_open(&self, path: &str) -> bool {
self.editors.all_editors().any(|editor| editor.document().is(PREFERENCES_EDITOR_SCHEME, Path::new(path)))
}
fn modal_active_editor(&self) -> Option<&OpenEditor> {
self.modal_group_open().then(|| self.editors.group_active_tab(MODAL_GROUP)).flatten()
}
pub(super) fn uses_modal_group(&self) -> bool {
self.setting("workbench.editor.useModal") != json!("off") && !self.skip_dialogs
}
pub(super) fn modal_group_open(&self) -> bool {
let (editors, _) = self.editors.group_tabs(MODAL_GROUP);
(self.editors.id == MODAL_GROUP || self.editors.group(MODAL_GROUP).is_some()) && !editors.is_empty()
}
/// Focus in the modal part: its text or webview editor, or the Settings, Keyboard Shortcuts, Profiles or Workspace
/// Trust editor it shows.
pub(super) fn modal_group_focused(&self, window: &Window) -> bool {
if let Some(path) = PREFERENCES_EDITOR_PATHS.into_iter().find(|path| self.modal_shows(path)) {
return self.preferences_editor_focused(path, window);
}
// A webview editor's keys come from its native view, which GPUI's focus does not see.
self.editors.id == MODAL_GROUP && (self.editor_focus.is_focused(window) || self.editors.active().is_some_and(|editor| self.shows_webview(editor)))
}
/// Whether the modal part shows the Settings or Keyboard Shortcuts editor (`path`), which may also be open in a
/// group of the editor area.
pub(super) fn modal_shows(&self, path: &str) -> bool {
self.modal_active_editor().is_some_and(|editor| editor.document().is(PREFERENCES_EDITOR_SCHEME, Path::new(path)))
}
/// `ModalEditorPart.close`: its editors close, asking to save dirty ones; the group goes with the last.
pub(super) fn close_modal_group(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if !self.modal_group_open() {
return;
}
self.activate_group(MODAL_GROUP);
let all = (0..self.editors.editors.len()).collect();
drop(self.close_editors(all, window, cx));
}
/// editorCommands.ts `MoveModalEditorToMainWindowAction` and `ModalEditorPart.close({ mergeAllEditorsToMainPart })`:
/// the modal's editors join the main part's most recent unlocked group (a new one beside the active group when
/// all are locked), its active editor active there, and that group takes the focus. No port editor vetoes a move.
pub(super) fn move_modal_editor_to_main(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if !self.modal_group_open() {
return;
}
let main_groups: Vec<_> = self.editors.group_ids_mru().into_iter().filter(|group| self.part_of_group(*group) == Some(super::editor_groups::MAIN_PART)).collect();
let target = match main_groups.iter().find(|group| !self.editors.locked.contains(group)) {
Some(group) => *group,
None => {
self.activate_group(main_groups[0]);
let direction = self.side_by_side_direction();
self.add_group_beside(direction)
}
};
let moved = self.with_group(MODAL_GROUP, |workbench| {
let active = workbench.editors.active_index().expect("an open modal group has an active editor");
(0..workbench.editors.editors.len()).map(|_| workbench.editors.take_editor(0)).enumerate().map(|(index, editor)| (index == active, editor)).collect::<Vec<_>>()
});
self.remove_group(MODAL_GROUP);
self.editor_groups.modal_previous_focus = None;
self.activate_group(target);
let mut active = self.editors.active_index();
for (was_active, editor) in moved {
self.insert_moved_editor(editor);
if was_active {
active = self.editors.active_index();
}
}
if let Some(active) = active {
self.editors.activate(active);
}
self.focus_group(target, window, cx);
let path = self.editors.active().filter(|editor| editor.document().scheme == PREFERENCES_EDITOR_SCHEME).map(|editor| editor.document().path.clone());
if let Some(path) = path.as_ref().and_then(|path| path.to_str()) {
self.focus_preferences_editor(path, window, cx);
}
}
/// The modal context keys while focus is in the modal part.
pub(super) fn modal_group_context(&self, window: &Window, context: &mut std::collections::HashMap<String, Value>) {
if !self.modal_group_focused(window) {
return;
}
context.insert("editorPartModal".into(), json!(true));
context.insert("editorPartModalVisible".into(), json!(true));
context.insert("editorPartModalMaximized".into(), json!(self.keybindings_editor.maximized));
context.insert("editorPartModalCanMoveToEditorArea".into(), json!(true));
}
/// The modal part around the group's active editor.
pub(super) fn modal_group_widget(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<AnyElement> {
let preferences = {
let active = self.modal_active_editor()?.document();
(active.scheme == PREFERENCES_EDITOR_SCHEME).then(|| active.path.clone())
};
if let Some(path) = preferences {
return match path.to_str() {
Some(SETTINGS_EDITOR_PATH) => Some(self.settings_editor_widget(window, cx)),
Some(PROFILES_EDITOR_PATH) => Some(self.profiles_editor_widget(window, cx)),
Some(WORKSPACE_TRUST_EDITOR_PATH) => Some(self.workspace_trust_editor_widget(window, cx)),
_ => Some(self.keybindings_editor_widget(window, cx)),
};
}
let (resource, (json_title, json_command, json_args), uri) = self.with_group(MODAL_GROUP, |workbench| {
// An inline custom diff has no code editor, so no `active`.
let editor = workbench.editors.active().or(workbench.editors.active_tab()).expect("an open modal group has an active editor");
let document = editor.document();
(workbench.modal_resource_label(editor), workbench.modal_editor_title_action(&document.scheme, &document.path), document.uri())
});
let header = ModalHeader { icon: "", title: "", json_title, json_command, json_args, resource: Some(resource), args: vec![uri] };
let focus = self.editor_focus.clone();
Some(self.modal_editor_part(header, &focus, window, cx, |workbench, _, _, window, cx| {
let body = |workbench: &mut Self, window: &mut Window, cx: &mut Context<Self>| {
if let Some(custom) = workbench.editors.active_diff().and_then(|diff| diff.custom.as_ref()) {
return div().flex_1().min_h_0().flex().flex_col().child(workbench.custom_editor_diff_body(custom.inline, cx));
}
let secondary = workbench.side_by_side_secondary(window, cx);
let editor = workbench.editors.active().expect("an open modal group has an active editor");
// `NoEditorTabsControl` keeps the breadcrumbs (breadcrumbs.enabled) without the tabs.
// An Images Preview (`RequiresModal`) is a webview editor without a resource, so without breadcrumbs.
if workbench.shows_webview(editor) {
return div().flex_1().min_h_0().flex().flex_col().child(workbench.webview_editor_body(editor));
}
if let Some(diff) = workbench.editors.active_diff() {
return div().flex_1().min_h_0().flex().flex_col().child(workbench.diff_editor_body(diff, diff.modified_editor.as_ref().unwrap_or(editor), window, cx));
}
let breadcrumbs = (workbench.setting("breadcrumbs.enabled") != json!(false)).then(|| workbench.breadcrumbs(editor, cx));
let part = div().flex_1().min_h_0().flex().flex_col().children(breadcrumbs);
match secondary {
Some(secondary) => part.child(workbench.side_by_side_body(secondary, editor, window, cx)),
None => part.children(workbench.unicode_banner(editor, cx)).child(workbench.text_area(editor, window, cx)),
}
};
match workbench.editors.id == MODAL_GROUP {
true => body(workbench, window, cx).into_any_element(),
false => workbench.swapped_group_body(MODAL_GROUP, body, window, cx).into_any_element(),
}
}))
}
/// `ModalEditorEditorTitle`: preferences.contribution.ts's Open Settings (UI) on a user, workspace or folder
/// settings file and Open Keyboard Shortcuts on keybindings.json.
fn modal_editor_title_action(&self, scheme: &str, path: &Path) -> (&'static str, &'static str, Vec<Value>) {
if self.keybindings.user_file.as_deref() == Some(path) {
return ("Open Keyboard Shortcuts", "workbench.action.openGlobalKeybindings", Vec::new());
}
if self.is_user_settings_file(path) {
return ("Open Settings (UI)", "workbench.action.openSettings2", Vec::new());
}
match self.open_workspace_settings_ui_action(scheme, path) {
Some((command, args)) => ("Open Settings (UI)", command, args),
None => ("", "", Vec::new()),
}
}
/// `openUserSettingsEditorWhen`: the current or the default profile's settings.json.
pub(super) fn is_user_settings_file(&self, path: &std::path::Path) -> bool {
let settings = self.settings.lock().unwrap();
let files = settings.user_files();
files.settings == path || files.default_settings.as_deref() == Some(path)
}
/// The header's `ResourceLabel`: file icon, name and the folder as the medium description.
fn modal_resource_label(&self, editor: &crate::editor::OpenEditor) -> AnyElement {
let foreground = self.foreground_or("titleBar.activeForeground");
let path = &editor.document().path;
// `EditorInput.getDescription` of an Images Preview is empty; sideBySideEditorInput.ts `getDescription`: none
// for two different sides.
let folder = path
.parent()
.filter(|_| !self.is_image_carousel(path))
.map(|folder| crate::quick_input::path_label(folder, self.workspace()))
.filter(|label| !label.is_empty() && self.editors.side_group().is_none());
// iconlabel.css `.label-description`: 0.9em at 0.7 opacity (0.95 in light themes), 0.5em after the name.
let opacity = if self.theme.kind == ThemeKind::Light { 0.95 } else { 0.7 };
div()
.flex()
.items_center()
.min_w_0()
.whitespace_nowrap()
// modalEditorPart.css `.modal-editor-title`.
.font_weight(gpui::FontWeight::SEMIBOLD)
.children(self.document_icon(editor, 22., foreground).map(|icon| icon.mr(px(6.))))
.child(self.editor_name(editor))
.children(folder.map(|folder| div().ml(px(5.4)).text_size(px(10.8)).opacity(opacity).truncate().child(folder)))
.into_any_element()
}
}