Visual Studio Code, rebuilt in Rust
Rust
//! mainThreadCustomEditors.ts with contrib/customEditor: the custom editors extensions contribute, picked by
//! editorResolverService.ts and drawn as webview editors. A custom text editor's tab is its resource's text model, so
//! saving, undo, dirty state and moves are the model's; a custom document's tab is a webview panel's.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use exthost::main_thread::serialized_error;
use files::glob::{self, Options};
use futures::channel::oneshot;
use gpui::{Context, IntoElement, Window};
use serde_json::{Value, json};
use super::Workbench;
use super::host_requests::uri_parts;
use super::media_preview::{media_kind, media_preview_contributions};
use super::webview_panels::{WEBVIEW_PANEL_SCHEME, WebviewPanel};
use crate::commands::Outcome;
use crate::diff_editor::{CustomDiff, DIFF_EDITOR_SCHEME, Side};
use crate::editor::{ContentChanged, OpenEditor, TextDocument, uri_value};
use crate::main_thread_quick_open::Owner;
use crate::quick_input::{Entry, Event, Item, Kind, QuickInput};
/// `DEFAULT_EDITOR_ASSOCIATION.id`: the text editor.
pub(super) const TEXT_EDITOR_ID: &str = "default";
const CONFIGURE_DEFAULT_ID: &str = "promptOpenWith.configureDefault";
const ASSOCIATIONS_SETTING: &str = "workbench.editorAssociations";
const DIFF_ASSOCIATIONS_SETTING: &str = "workbench.diffEditorAssociations";
/// editorResolverService.ts `priorityToRank`; the text editor ranks 2.
/// `hasExclusiveMatch`.
pub(super) const RANK_EXCLUSIVE: u8 = 5;
const RANK_DEFAULT: u8 = 4;
pub(super) const RANK_BUILTIN: u8 = 3;
const RANK_TEXT_EDITOR: u8 = 2;
/// `RegisteredEditorPriority.option`.
const RANK_OPTION: u8 = 1;
const RESOLVER_CACHE_KEY: &str = "editorOverrideService.cache";
/// editorResolverService.ts `conflictingDefaultsStorageID`.
const CONFLICTING_DEFAULTS_KEY: &str = "editorOverrideService.conflictingDefaults";
const CUSTOM_EDITORS_MEMENTO_KEY: &str = "memento/customEditors";
/// NotebookProviderInfoStore's `CUSTOM_EDITORS_STORAGE_ID`.
const NOTEBOOK_EDITORS_MEMENTO_KEY: &str = "memento/notebookEditors";
#[derive(Default)]
pub struct CustomEditors {
/// `$registerTextEditorProvider` and `$registerCustomEditorProvider`, by view type.
providers: HashMap<String, Provider>,
/// Opens waiting for their view type's provider, which `onCustomEditor:<viewType>` registers.
pending: Vec<PendingOpen>,
/// Opens answered once their editor's `$resolveCustomEditor` settles (WebviewEditor.setInput awaits `resolveWebview`),
/// with the options `applyOptions` reveals then.
pub(super) opening: HashMap<String, Vec<(oneshot::Sender<Result<Value, Value>>, Value)>>,
next_handle: u64,
/// The custom documents the host created, by resource and view type (custom_documents.rs).
pub(super) documents: Vec<super::custom_documents::CustomDocument>,
}
struct Provider {
extension: Value,
/// `IWebviewPanelOptions`.
options: Value,
text: bool,
supports_move: bool,
supports_navigation: bool,
/// `supportsMultipleEditorsPerDocument`: else an editor of the resource is a singleton the open moves.
supports_multiple_editors: bool,
/// The proposed `customEditorDiffs` capabilities (extHostCustomEditors.ts).
supports_inline_diff: bool,
supports_side_by_side_diff: bool,
}
struct PendingOpen {
view_type: String,
resource: Value,
options: Value,
reply: oneshot::Sender<Result<Value, Value>>,
/// A diff's original side and label: the resource is its modified side.
diff: Option<(Side, Option<String>)>,
}
/// The open with picker's resource, the active editor's id, and the editor id of each item handle. `reopen`: the
/// pick replaces the active editor (Reopen Editor With...), else it opens the resource (Explorer's Open With...).
#[derive(Clone)]
pub struct OpenWithPicker {
resource: Value,
current: String,
ids: Vec<String>,
configure_default: bool,
reopen: bool,
/// Opened from the empty editor hint, which offers the picked editor first next time.
pub(super) remember_untitled_editor: bool,
}
/// The custom editor a webview panel shows.
pub(super) struct CustomEditor {
pub(super) resource: Value,
/// `$resolveCustomEditor` was sent for the panel's handle.
pub(super) resolved: bool,
/// The backup a restored editor creates its document from.
pub(super) backup_id: Option<String>,
pub(super) navigation: Navigation,
/// The part of a diff the panel shows over the diff editor's tab.
pub(super) diff: Option<DiffPart>,
}
/// customEditorDiffInput.ts: a `CustomEditorDiffInput` (`Inline`), a side of a `DiffEditorInput` of
/// `CustomEditorSideBySideDiffInput`s, or of `CustomEditorInput`s when the provider has no diff capability.
pub(super) struct DiffPart {
pub(super) side: DiffSide,
pub(super) original: Value,
pub(super) modified: Value,
/// The provider resolves the diff (`supportsInlineDiff` or `supportsSideBySideDiff`): its webviews hold both
/// sides' documents. Else each side is a plain custom editor of its own resource.
pub(super) joint: bool,
/// The diff tab's model id: a diff reopened in place has the same path but is another editor.
pub(super) tab: u32,
}
impl CustomEditor {
/// The resources whose custom documents the editor holds: a diff's webviews hold both sides'
/// (mainThreadCustomEditors.ts `additionalModelRefs`).
pub(super) fn resources(&self) -> Vec<&Value> {
match &self.diff {
Some(part) if part.joint => vec![&part.original, &part.modified],
_ => vec![&self.resource],
}
}
}
#[derive(Clone, Copy, PartialEq)]
pub(super) enum DiffSide {
Inline,
Original,
Modified,
}
/// mainThreadCustomEditors.ts `resolveCustomTextEditorNavigation`: the selection of a custom text editor whose
/// provider resolved its navigation, which the outline and breadcrumbs follow.
pub(super) enum Navigation {
None,
/// `_pendingNavigation`: the selection the host changed to before it answered.
Resolving(Option<Value>),
/// The `ISelection`, or null.
Ready(Value),
}
/// The selection of a custom text editor whose navigation resolved.
pub(super) fn custom_navigation(panel: &WebviewPanel) -> Option<&Value> {
match &panel.custom.as_ref()?.navigation {
Navigation::Ready(selection) => Some(selection),
_ => None,
}
}
impl Workbench {
pub(crate) fn handle_custom_editors_request(&mut self, method: &str, args: &[Value], window: &mut Window, cx: &mut Context<Self>) -> Outcome {
let arg = |index: usize| args.get(index).cloned().unwrap_or(Value::Null);
let view_type = arg(1).as_str().unwrap_or_default().to_owned();
match method {
"$registerTextEditorProvider" | "$registerCustomEditorProvider" => {
if self.webview_panels.custom_editors.providers.contains_key(&view_type) {
return Outcome::Ready(Err(serialized_error(&format!("Provider for {view_type} already registered"))));
}
let capabilities = arg(3);
let provider = Provider { extension: arg(0), options: arg(2), text: method == "$registerTextEditorProvider", supports_move: capabilities["supportsMove"] == true, supports_navigation: capabilities["supportsNavigation"] == true,
supports_multiple_editors: method == "$registerTextEditorProvider" || arg(4) == true,
supports_inline_diff: capabilities["supportsInlineDiff"] == true,
supports_side_by_side_diff: capabilities["supportsSideBySideDiff"] == true,
};
self.webview_panels.custom_editors.providers.insert(view_type, provider);
self.open_pending_custom_editors(window, cx);
}
"$unregisterEditorProvider" => {
let view_type = arg(0).as_str().unwrap_or_default().to_owned();
self.webview_panels.custom_editors.providers.remove(&view_type);
self.dispose_custom_text_editor_navigations(&view_type, cx);
}
"$onDidChangeCustomTextEditorSelection" => {
let Some(custom) = self.webview_panel_mut(arg(0).as_str().unwrap_or_default()).and_then(|panel| panel.custom.as_mut()) else { return Outcome::done() };
match &mut custom.navigation {
Navigation::Resolving(changed) => *changed = Some(arg(1)),
Navigation::Ready(selection) => *selection = arg(1),
Navigation::None => {}
}
cx.notify();
}
"$onDidEdit" => self.push_custom_document_edit(&arg(0), &view_type, arg(2).as_i64().unwrap_or_default(), arg(3).as_str(), cx),
"$onContentChange" => self.change_custom_document_content(&arg(0), &view_type, cx),
_ => {}
}
Outcome::done()
}
/// `_workbench.open` and `_workbench.openWith` through editorResolverService.ts: without an override the custom
/// editor that ranks above the text editor opens the resource; `default` is the text editor.
pub(super) fn open_with_resolver(&mut self, resource: &Value, override_id: Option<&str>, options: Value, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
let view_type = match (override_id, uri_parts(resource)) {
(Some("default"), _) | (None, Err(_)) => None,
(Some(view_type), _) => Some(view_type.to_owned()),
(None, Ok((scheme, path))) => {
let view_type = self.custom_editor_for(scheme, &path);
if let Some(view_type) = &view_type
&& self.conflicting_default(scheme, &path)
{
self.prompt_conflicting_defaults(resource, view_type, window, cx);
}
view_type
}
};
match view_type {
Some(view_type) if self.is_notebook_type(&view_type) => {
self.detach_custom_editors(resource);
self.open_notebook(resource.clone(), view_type, options, window, cx)
}
Some(view_type) => match media_kind(&view_type) {
Some(kind) => {
self.detach_custom_editors(resource);
self.open_media_preview(kind, &view_type, resource, &options, window, cx)
}
None => self.open_custom_editor(view_type, resource.clone(), None, options, window, cx),
},
None => {
self.detach_custom_editors(resource);
self.api_open_editor_resolving(vec![resource.clone(), json!([null, options])], window, cx)
}
}
}
/// editorResolverService.ts `getDefaultEditorSelection` for a resource: the view type of the custom editor that
/// opens it, None for the text editor.
pub(super) fn custom_editor_for(&self, scheme: &str, path: &Path) -> Option<String> {
let (view_type, _) = self.default_editor(scheme, path, true, false);
(view_type != TEXT_EDITOR_ID).then_some(view_type)
}
/// editorResolverService.ts `resolveEditor` of a diff: the custom editor its modified side opens in by the diff
/// editor's associations and priorities, None for the text diff editor.
pub(super) fn custom_diff_editor_for(&self, modified: &Side) -> Option<String> {
let (view_type, _) = self.default_editor(&modified.scheme, &modified.path, true, true);
(view_type != TEXT_EDITOR_ID && media_kind(&view_type).is_none() && !self.is_notebook_type(&view_type)).then_some(view_type)
}
/// `getDefaultEditorSelection` `conflictingDefault`: without a user association for the resource, more than one
/// editor that is not exclusive opens it at builtin priority or above.
fn conflicting_default(&self, scheme: &str, path: &Path) -> bool {
let path = &self.pattern_resource(scheme, path);
let Some(matches) = resource_matcher(scheme, path) else { return false };
if !self.matching_associations(&matches, false).is_empty() {
return false;
}
let defaults = self.editor_contributions().into_iter().filter(|contribution| (RANK_BUILTIN..RANK_EXCLUSIVE).contains(&contribution.rank) && contribution.patterns.iter().any(|pattern| matches(pattern)));
defaults.count() > 1
}
/// editorResolverService.ts `doHandleConflictingDefaults`: a warning offers to configure the default or keep
/// `view_type`; once it closes, the editors matching the resource are remembered for its extension's glob and it
/// does not ask again while `view_type` is among them.
fn prompt_conflicting_defaults(&mut self, resource: &Value, view_type: &str, window: &mut Window, cx: &mut Context<Self>) {
let Ok((scheme, path)) = uri_parts(resource) else { return };
let glob = format!("*{}", path.extension().map(|extension| format!(".{}", extension.to_string_lossy())).unwrap_or_default());
let stored = self.profile_storage.lock().unwrap().get(CONFLICTING_DEFAULTS_KEY).and_then(|raw| serde_json::from_str::<Value>(raw).ok()).unwrap_or_default();
if stored[&glob].as_array().is_some_and(|ids| ids.iter().any(|id| id == view_type)) {
return;
}
let editors = self.resource_editors(scheme, &path, false);
let label = editors.iter().find(|(id, ..)| id == view_type).map(|(_, label, ..)| label.clone()).unwrap_or_default();
let ids: Vec<String> = editors.into_iter().map(|(id, ..)| id).collect();
let keep = format!("Keep {label}");
let answer = self.prompt_notification(crate::notifications::Severity::Warning, "There are multiple default editors available for the resource.", &["Configure Default", &keep]);
let (resource, current) = (resource.clone(), view_type.to_owned());
cx.spawn_in(window, async move |workbench, cx| {
let Ok(answer) = answer.await else { return };
let _ = workbench.update_in(cx, |workbench, window, cx| {
// `CONFIGURE_DEFAULT_EDITOR_COMMAND_ID`: the picker sets the new default and replaces the editor.
if answer == Ok(json!(0)) {
workbench.show_open_with_picker(resource, current, true, true, window, cx);
}
let mut storage = workbench.profile_storage.lock().unwrap();
let mut stored = storage.get(CONFLICTING_DEFAULTS_KEY).and_then(|raw| serde_json::from_str::<Value>(raw).ok()).filter(Value::is_object).unwrap_or_else(|| json!({}));
stored[&glob] = json!(ids);
storage.set(CONFLICTING_DEFAULTS_KEY, stored.to_string());
});
})
.detach();
}
/// editorResolverService.ts `cacheEditors` on `onWillSaveState`: the globs of every editor but the optional ones,
/// and of the user's associations, whose resources the next start opens only after the extensions registered.
pub(super) fn store_editor_resolver_cache(&self) {
let mut patterns: Vec<String> = Vec::new();
for contribution in self.editor_contributions().into_iter().filter(|contribution| contribution.rank != RANK_OPTION) {
patterns.extend(contribution.patterns);
}
patterns.extend(self.editor_associations().into_iter().map(|(pattern, _)| pattern));
patterns.sort();
patterns.dedup();
self.profile_storage.lock().unwrap().set(RESOLVER_CACHE_KEY, Value::from(patterns).to_string());
}
/// contributedCustomEditors.ts `update` once the extensions registered: the custom editors go to the profile
/// memento, which the next start's resolver reads before the extensions register again.
pub fn store_custom_editors_memento(&mut self) {
self.memento_custom_editors = None;
let mut editors = Vec::new();
for extension in &self.extensions {
let is_builtin = extension.description["isBuiltin"] == true;
let provider = match is_builtin {
true => "Built-in".to_owned(),
false => extension.description["displayName"].as_str().map_or(extension.id.clone(), str::to_owned),
};
for contribution in extension.description["contributes"]["customEditors"].as_array().into_iter().flatten() {
let priority = &contribution["priority"];
let editor = stored_priority(priority.as_str().or(priority["textEditor"].as_str()), is_builtin).unwrap_or("default");
let diff = priority["diffEditor"].as_str().and_then(|diff| stored_priority(Some(diff), is_builtin)).unwrap_or("explicit");
editors.push(json!({
"id": contribution["viewType"],
"displayName": contribution["displayName"],
"providerDisplayName": provider,
"selector": contribution.get("selector").cloned().unwrap_or_else(|| json!([])),
"priority": { "editor": editor, "diff": diff },
}));
}
}
let notebooks: Vec<Value> = notebook_contributions(&self.extensions)
.into_iter()
.map(|notebook| {
let priority = if notebook.rank == RANK_DEFAULT { "default" } else { "option" };
let selectors: Vec<Value> = notebook.patterns.iter().map(|pattern| json!({ "filenamePattern": pattern })).collect();
json!({ "id": notebook.view_type, "displayName": notebook.display_name, "providerDisplayName": notebook.provider, "selectors": selectors, "priority": priority })
})
.collect();
let mut storage = self.profile_storage.lock().unwrap();
storage.set(CUSTOM_EDITORS_MEMENTO_KEY, json!({ "editors": editors }).to_string());
storage.set(NOTEBOOK_EDITORS_MEMENTO_KEY, json!({ "editors": notebooks }).to_string());
}
/// ContributedCustomEditors' and NotebookProviderInfoStore's constructors: the previous session's mementos register
/// their editors before the extensions do, so a restored editor's control lists them from the start. Whether they
/// held any.
pub fn restore_custom_editors_memento(&mut self) -> bool {
let storage = self.profile_storage.lock().unwrap();
let memento = |key| storage.get(key).and_then(|raw| serde_json::from_str::<Value>(raw).ok()).unwrap_or_default();
let mut editors = memento_contributions(&memento(CUSTOM_EDITORS_MEMENTO_KEY));
for notebook in memento(NOTEBOOK_EDITORS_MEMENTO_KEY)["editors"].as_array().into_iter().flatten() {
let provider = notebook["providerDisplayName"].as_str().unwrap_or_default();
editors.extend(notebook_contribution(notebook["id"].as_str(), notebook, ¬ebook["selectors"], provider));
}
drop(storage);
let known = !editors.is_empty();
self.memento_custom_editors = Some(editors);
known
}
/// The previous session's `editorOverrideService.cache`, read and removed on startup as the resolver does.
pub fn take_editor_resolver_cache(&mut self) -> Vec<String> {
let mut storage = self.profile_storage.lock().unwrap();
let cache = storage.get(RESOLVER_CACHE_KEY).and_then(|raw| serde_json::from_str(raw).ok()).unwrap_or_default();
storage.delete(RESOLVER_CACHE_KEY);
cache
}
/// The command line's file on startup. editorResolverService.ts `resolveEditor` runs before the extensions
/// registered their editors and waits for them only when the cache or a user association names the file's glob,
/// so on a first start a `.ipynb` opens as JSON in the text editor. The media previews are registered by then.
pub fn open_startup_file(&mut self, path: PathBuf, resolver_cache: &[String], editors_known: bool, window: &mut Window, cx: &mut Context<Self>) {
let waits_for_extensions = resource_matcher("file", &path).is_some_and(|matches| {
resolver_cache.iter().any(|pattern| matches(pattern))
|| self.editor_associations().iter().any(|(pattern, view_type)| view_type != TEXT_EDITOR_ID && matches(pattern))
|| media_preview_contributions().iter().flat_map(|contribution| &contribution.patterns).any(|pattern| matches(pattern))
});
match waits_for_extensions {
true => self.open_file(path, true, window, cx),
false => {
self.open_text_file("file", path, true, window, cx);
if !editors_known {
self.set_editor_type_control_before_registration();
}
}
}
}
/// The contributed custom editors, then the built-in media previews.
fn editor_contributions(&self) -> Vec<Contribution> {
let mut contributions = match &self.memento_custom_editors {
Some(memento) => memento.clone(),
None => custom_editor_contributions(&self.extensions),
};
contributions.extend(media_preview_contributions());
contributions
}
/// `getEditorMatches(resource).defaultRule`: the id of the editor that opens the resource, `default` for the text
/// editor, and the glob a new default would be written for. Without `associations` it is the natural default;
/// with `diff`, the diff editor's (`EditorAssociationType.DiffEditor`).
pub(super) fn default_editor(&self, scheme: &str, path: &Path, associations: bool, diff: bool) -> (String, String) {
let path = &self.pattern_resource(scheme, path);
let extension_pattern = format!("*{}", path.extension().map(|extension| format!(".{}", extension.to_string_lossy())).unwrap_or_default());
let text_editor = (TEXT_EDITOR_ID.to_owned(), extension_pattern.clone());
let Some(matches) = resource_matcher(scheme, path) else { return text_editor };
if associations && let Some((pattern, view_type)) = self.matching_associations(&matches, diff).into_iter().next() {
return (view_type, pattern);
}
let mut best: Option<(u8, &str, String)> = None;
let contributions = self.editor_contributions();
for contribution in &contributions {
let Some(pattern) = contribution.patterns.iter().filter(|pattern| matches(pattern)).max_by_key(|pattern| pattern.len()) else { continue };
let rank = contribution.rank_for(diff);
let better = best.as_ref().is_none_or(|(best_rank, best_pattern, _)| (rank, pattern.len()) > (*best_rank, best_pattern.len()));
if rank > RANK_TEXT_EDITOR && better {
best = Some((rank, pattern, contribution.view_type.clone()));
}
}
best.map_or(text_editor, |(_, pattern, view_type)| (view_type, pattern.to_owned()))
}
/// customEditors.ts `UndoCommand` and `RedoCommand` implementations: a custom text editor's are its model's, a
/// custom document's are its edits (`undoRedoService.undo(resource)`).
pub(super) fn custom_text_editor_undo(&mut self, id: &str, command: fn(&mut OpenEditor) -> Option<ContentChanged>, window: &mut Window, cx: &mut Context<Self>) -> Option<Outcome> {
let direction = match id {
"undo" => crate::undo_redo::Direction::Undo,
"redo" => crate::undo_redo::Direction::Redo,
_ => return None,
};
let editor = self.editors.active()?;
if editor.document().scheme == WEBVIEW_PANEL_SCHEME {
let path = editor.document().path.clone();
return Some(self.undo_custom_document(&path, direction, window, cx));
}
let custom_text = self.custom_editor_over(editor).is_some();
custom_text.then(|| self.run_on_active_editor(command, cx))
}
/// editorCommands.ts `reopenEditorWith` on the active editor: `override_id` is an editor id, None asks with the
/// open with picker.
pub(super) fn reopen_active_editor_with(&mut self, override_id: Option<String>, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
let Some((resource, current)) = self.active_editor_type() else { return Outcome::done() };
match override_id {
Some(editor_id) => self.reopen_with(&resource, ¤t, &editor_id, false, window, cx),
None => {
self.show_open_with_picker(resource, current, false, true, window, cx);
Outcome::done()
}
}
}
/// The active editor's resource and the id of the editor showing it (`activeEditor.editorId`): a notebook's type,
/// a custom editor's view type or the text editor; a webview panel has no resource to reopen.
pub(super) fn active_editor_type(&self) -> Option<(Value, String)> {
if let Some(model) = self.active_notebook_editor().and_then(|editor| self.host.notebooks.model(&editor.notebook)) {
return Some((model.uri.clone(), model.view_type.clone()));
}
if let Some(diff) = self.editors.active_diff() {
let editor_id = diff.custom.as_ref().map_or(TEXT_EDITOR_ID, |custom| custom.view_type.as_str());
return Some((uri_value(&diff.modified.scheme, &diff.modified.path), editor_id.to_owned()));
}
let editor = self.editors.pane_editor()?;
// terminalMainContribution.ts registers the terminal editor `exclusive`: `getEditors` lists none for it.
if editor.document().scheme == super::terminal_editor::TERMINAL_EDITOR_SCHEME {
return None;
}
match self.webview_panels.panels.iter().find(|panel| panel.shows(editor)) {
Some(panel) => panel.custom.as_ref().map(|custom| (custom.resource.clone(), panel.view_type.clone())),
None => Some((editor.document().uri(), TEXT_EDITOR_ID.to_owned())),
}
}
/// `group.replaceEditors`: a text model's editor stays and gains or loses a custom text editor's webview; a custom
/// document's, a saved notebook's or a clean text editor reopened in a tab of its own closes first and the replacement takes its place, pinned (editorGroupView.ts
/// `replaceEditors`).
pub(super) fn reopen_with(&mut self, resource: &Value, current: &str, editor_id: &str, preserve_focus: bool, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
// binaryFileEditor.ts `openInternal`: the text editor picked for a binary file opens it as text.
if editor_id == TEXT_EDITOR_ID
&& let Some(editor) = self.editors.active().filter(|editor| matches!(editor.document().open_error, Some(crate::editor::OpenError::Binary(_))))
{
let (scheme, path) = (editor.document().scheme.clone(), editor.document().path.clone());
self.reopen_file_editor(&scheme, &path, false, true, cx);
return Outcome::done();
}
if current == editor_id {
return Outcome::done();
}
let notebook_dirty = self.active_notebook_editor().and_then(|editor| self.host.notebooks.model(&editor.notebook)).is_some_and(|model| model.dirty);
let own_tab = media_kind(editor_id).is_some() || self.is_notebook_type(editor_id) || self.webview_panels.custom_editors.providers.get(editor_id).is_some_and(|provider| !provider.text);
let replaced = |editor: &OpenEditor| match editor.document().scheme.as_str() {
WEBVIEW_PANEL_SCHEME => true,
crate::notebook::NOTEBOOK_EDITOR_SCHEME => !notebook_dirty,
_ => own_tab && !editor.is_dirty(),
};
// editorCommands.ts `reopenEditorWith` of a diff resolves both sides with the editor: a diff again.
let diff = self.editors.active_diff().filter(|diff| uri_value(&diff.modified.scheme, &diff.modified.path) == *resource).map(|diff| (diff.original.clone(), diff.label.clone()));
let diff = diff.filter(|_| media_kind(editor_id).is_none() && !self.is_notebook_type(editor_id));
let group = self.editors.id;
let replaced_at = self.editors.active_index().filter(|&index| diff.is_some() || replaced(&self.editors.editors[index]));
if let Some(index) = replaced_at {
self.editors.close(index);
// A diff reopens at once (both editors below sync): the host never sees the group without it.
if diff.is_none() {
self.editors_changed(cx);
}
}
let options = json!({ "preserveFocus": preserve_focus });
let outcome = match diff {
Some((original, label)) if editor_id == TEXT_EDITOR_ID => {
let (scheme, path) = uri_parts(resource).expect("a diff side's resource");
self.show_diff_editor(original, Side { scheme: scheme.to_owned(), path }, label, None, &options, window, cx);
Outcome::done()
}
Some(diff) => self.open_custom_editor(editor_id.to_owned(), resource.clone(), Some(diff), options, window, cx),
None => self.open_with_resolver(resource, Some(editor_id), options, window, cx),
};
if let Some(index) = replaced_at
&& self.editors.id == group
&& let Some(opened) = self.editors.active_index()
{
self.editors.move_editor(opened, index);
self.editors.pin(index.min(self.editors.editors.len() - 1));
self.editors_changed(cx);
}
outcome
}
/// editorResolverService.ts `getEditorMatches` (in a diff editor with `diff`): the editors that open the resource
/// (by glob or a user association) by priority, then the longer glob, the text editor registering `*` as builtin;
/// as id, label, provider, rank and whether it is an unconfigured `*` option editor
/// (`isUnconfiguredUniversalOptionalEditorMatch`).
pub(super) fn resource_editors(&self, scheme: &str, path: &Path, diff: bool) -> Vec<(String, String, String, u8, bool)> {
let path = &self.pattern_resource(scheme, path);
let mut editors = vec![(RANK_BUILTIN, 1, (TEXT_EDITOR_ID.to_owned(), "Text Editor".to_owned(), "Built-in".to_owned(), RANK_BUILTIN, false))];
if let Some(matches) = resource_matcher(scheme, path) {
let associated: Vec<String> = self.matching_associations(&matches, diff).into_iter().map(|(_, view_type)| view_type).collect();
for contribution in self.editor_contributions() {
let is_associated = associated.contains(&contribution.view_type);
let pattern = contribution.patterns.iter().filter(|pattern| matches(pattern)).max_by_key(|pattern| pattern.len());
if !is_associated && pattern.is_none() {
continue;
}
let rank = contribution.rank_for(diff);
let universal_option = !is_associated && rank == RANK_OPTION && pattern.is_some_and(|pattern| pattern == "*");
let glob_length = pattern.map_or(0, String::len);
editors.push((rank, glob_length, (contribution.view_type, contribution.display_name, contribution.provider, rank, universal_option)));
}
}
editors.sort_by_key(|(rank, glob_length, _)| std::cmp::Reverse((*rank, *glob_length)));
editors.into_iter().map(|(_, _, editor)| editor).collect()
}
/// editorResolverService.ts `getResourceForPatternMatching`: an untitled resource without an extension or an
/// associated file matches editor globs by the first extension of its model's language, e.g. `Untitled-1.txt`.
fn pattern_resource(&self, scheme: &str, path: &Path) -> std::path::PathBuf {
let Some(model) = self.editors.model(scheme, path).filter(|model| scheme == "untitled" && path.extension().is_none() && !model.text_model().associated_file) else {
return path.to_path_buf();
};
match self.languages.extensions(&model.document().language_id).first() {
Some(extension) => format!("{}{extension}", path.display()).into(),
None => path.to_path_buf(),
}
}
/// `getAssociationsForResourceByType`: a diff takes `workbench.diffEditorAssociations`, else the editor
/// associations whose editor is not `explicit` for diffs; the longest glob first.
fn matching_associations(&self, matches: &impl Fn(&str) -> bool, diff: bool) -> Vec<(String, String)> {
let matching = |setting| self.associations(setting).into_iter().filter(|(pattern, _)| matches(pattern)).collect::<Vec<_>>();
if !diff {
return matching(ASSOCIATIONS_SETTING);
}
let diff_associations = matching(DIFF_ASSOCIATIONS_SETTING);
if !diff_associations.is_empty() {
return diff_associations;
}
let contributions = self.editor_contributions();
let explicit = |view_type: &str| contributions.iter().any(|contribution| contribution.view_type == view_type && contribution.diff_rank == 0);
matching(ASSOCIATIONS_SETTING).into_iter().filter(|(_, view_type)| !explicit(view_type)).collect()
}
/// openWithEditorPicker.ts `doPick`: the text editor, then the resource's editors by rank, and the entry that
/// picks a new default; `configure_default` is the picker that entry opens.
/// fileCommands.ts `OPEN_WITH_EXPLORER_COMMAND_ID`: the picker marks the editor the resource shows in as active
/// in the active group (openWithEditorPicker.ts `activeGroup.findEditors(resource).at(0)`), and the pick opens
/// the resource with that editor.
pub(super) fn show_open_with_picker_for(&mut self, resource: &crate::diff_editor::Side, window: &mut Window, cx: &mut Context<Self>) {
let uri = crate::editor::uri_value(&resource.scheme, &resource.path);
let custom = self.webview_panels.panels.iter().find(|panel| panel.custom.as_ref().is_some_and(|custom| uri_parts(&custom.resource).is_ok_and(|(scheme, path)| scheme == resource.scheme && path == resource.path))).map(|panel| panel.view_type.clone());
let text = self.editors.editors.iter().any(|editor| editor.document().is(&resource.scheme, &resource.path)).then(|| TEXT_EDITOR_ID.to_owned());
let current = custom.or(text).unwrap_or_default();
self.show_open_with_picker(uri, current, false, false, window, cx);
}
pub(super) fn show_open_with_picker(&mut self, resource: Value, current: String, configure_default: bool, reopen: bool, window: &mut Window, cx: &mut Context<Self>) {
let Ok((scheme, path)) = uri_parts(&resource) else { return };
let (default_id, pattern) = self.default_editor(scheme, &path, true, false);
let mut entries = Vec::new();
let mut ids = Vec::new();
let mut editors = self.resource_editors(scheme, &path, false);
editors.sort_by_key(|(id, ..)| id != TEXT_EDITOR_ID);
for (id, label, detail, _, _) in editors {
let description = match (id == current, id == default_id) {
(true, true) => Some("Active and Default".to_owned()),
(true, false) => Some("Active".to_owned()),
(false, true) => Some("Default".to_owned()),
(false, false) => None,
};
entries.push(Entry::Item(Item { handle: ids.len() as i64, label, description, detail: Some(detail), pickable: true, ..Item::default() }));
ids.push(id);
}
if !configure_default && path.extension().is_some() {
entries.push(Entry::Separator(None));
let label = format!("Configure default editor for '{pattern}'...");
entries.push(Entry::Item(Item { handle: ids.len() as i64, label, pickable: true, ..Item::default() }));
ids.push(CONFIGURE_DEFAULT_ID.to_owned());
}
let basename = path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
let mut input = QuickInput::new(0, Kind::QuickPick);
input.placeholder = Some(match configure_default {
true => format!("Select new default editor for '{pattern}'"),
false => format!("Select editor for '{basename}'"),
});
input.can_accept_in_background = true;
input.set_items(entries);
let id = self.quick_inputs.add(input, Owner::OpenWith(OpenWithPicker { resource, current, ids, configure_default, reopen, remember_untitled_editor: false }));
self.show_quick_input(id, window, cx);
self.flush_quick_input_events(window, cx);
}
pub fn open_with_picker_event(&mut self, id: i64, event: Event, window: &mut Window, cx: &mut Context<Self>) {
match event {
Event::Accept(in_background) => {
let Some(input) = self.quick_inputs.get(id) else { return };
let Some(&handle) = input.selected_handles().first() else { return };
let Some(Owner::OpenWith(picker)) = self.quick_inputs.owner(id) else { return };
let picker = picker.clone();
self.hide_quick_input_by_id(id, window, cx);
let editor_id = &picker.ids[handle as usize];
if editor_id == CONFIGURE_DEFAULT_ID {
return self.show_open_with_picker(picker.resource, picker.current, true, picker.reopen, window, cx);
}
if picker.configure_default {
self.set_default_editor(&picker.resource, editor_id, false);
}
match picker.reopen {
true => {
drop(self.reopen_with(&picker.resource, &picker.current, editor_id, in_background, window, cx));
if picker.remember_untitled_editor {
self.remember_untitled_editor(&picker.resource);
}
}
false => drop(self.open_with_resolver(&picker.resource, Some(editor_id), json!({ "preserveFocus": in_background }), window, cx)),
}
}
Event::Hide => self.quick_inputs.remove(id),
_ => {}
}
}
/// editorResolverService.ts `setDefaultEditor`: the association for the default rule's glob, removed when the
/// editor is the one the resource opens with without it; a diff's goes to `workbench.diffEditorAssociations`.
pub(super) fn set_default_editor(&mut self, resource: &Value, editor_id: &str, diff: bool) {
let Ok((scheme, path)) = uri_parts(resource) else { return };
let setting = if diff { DIFF_ASSOCIATIONS_SETTING } else { ASSOCIATIONS_SETTING };
let (default_id, pattern) = self.default_editor(scheme, &path, true, diff);
let (natural_id, _) = self.default_editor(scheme, &path, false, diff);
let mut associations = match self.setting(setting) {
Value::Object(associations) => associations,
_ => serde_json::Map::new(),
};
if editor_id == natural_id {
if associations.remove(&pattern).is_some() {
return self.update_setting(setting, Value::Object(associations));
}
if default_id == editor_id {
return;
}
}
associations.insert(pattern, json!(editor_id));
self.update_setting(setting, Value::Object(associations));
}
/// `workbench.editorAssociations` as glob and editor id, the longest glob first.
fn editor_associations(&self) -> Vec<(String, String)> {
self.associations(ASSOCIATIONS_SETTING)
}
/// editorResolverService.ts `getAllUserAssociationsForSetting`: the workspace's globs, then the default's and
/// the user's for the globs the workspace leaves out; the longest glob first, equal lengths in that order.
fn associations(&self, setting: &str) -> Vec<(String, String)> {
let inspected = self.settings.lock().unwrap().configuration.inspect(setting, &config::configuration::Overrides::default());
let object = |value: Option<Value>| match value {
Some(Value::Object(object)) => object,
_ => serde_json::Map::new(),
};
let mut raw = object(inspected.workspace.value);
let mut default_and_user = object(inspected.default_value);
default_and_user.extend(object(inspected.user_local.value));
for (pattern, view_type) in default_and_user {
raw.entry(pattern).or_insert(view_type);
}
let mut associations: Vec<(String, String)> = raw.into_iter().filter_map(|(pattern, view_type)| Some((pattern, view_type.as_str()?.to_owned()))).collect();
associations.sort_by_key(|(pattern, _)| std::cmp::Reverse(pattern.len()));
associations
}
/// Opens `resource` in the custom editor of `view_type` once its provider is registered, activating
/// `onCustomEditor:<viewType>` for it (customEditors.ts).
pub(super) fn open_custom_editor(&mut self, view_type: String, resource: Value, diff: Option<(Side, Option<String>)>, options: Value, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
drop(self.host.activate_by_event(&format!("onCustomEditor:{view_type}")));
let (reply, receiver) = oneshot::channel();
self.webview_panels.custom_editors.pending.push(PendingOpen { view_type, resource, options, reply, diff });
self.open_pending_custom_editors(window, cx);
Outcome::Pending(receiver)
}
fn open_pending_custom_editors(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let custom_editors = &mut self.webview_panels.custom_editors;
let (ready, waiting): (Vec<PendingOpen>, Vec<PendingOpen>) =
std::mem::take(&mut custom_editors.pending).into_iter().partition(|open| custom_editors.providers.contains_key(&open.view_type));
custom_editors.pending = waiting;
for open in ready {
let shown = match open.diff {
Some((original, label)) => self.show_custom_editor_diff(&open.view_type, original, &open.resource, label, &open.options, window, cx),
None => self.show_custom_editor(&open.view_type, &open.resource, &open.options, window, cx),
};
match shown {
Ok(handle) if self.webview_panel_mut(&handle).is_some_and(|panel| panel.custom.as_ref().is_some_and(|custom| !custom.resolved)) => {
self.webview_panels.custom_editors.opening.entry(handle).or_default().push((open.reply, open.options));
}
Ok(handle) => {
self.apply_custom_editor_options(&handle, &open.options);
_ = open.reply.send(Ok(Value::Null));
}
Err(error) => _ = open.reply.send(Err(error)),
}
}
self.resolve_custom_editors(cx);
}
/// A custom text editor attaches a webview to the resource's text editor, opened or shown as `$tryShowTextDocument`
/// does; a custom document gets a webview panel's editor of its own, one per resource and view type.
fn show_custom_editor(&mut self, view_type: &str, resource: &Value, options: &Value, window: &mut Window, cx: &mut Context<Self>) -> Result<String, Value> {
let (_, path) = uri_parts(resource)?;
let provider = &self.webview_panels.custom_editors.providers[view_type];
let (text, extension, retain) = (provider.text, provider.extension.clone(), provider.options["retainContextWhenHidden"] == true);
let find_enabled = provider.options["enableFindWidget"] == true;
let multiple = provider.supports_multiple_editors;
let title = path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
let backup_id = options["backupId"].as_str().map(str::to_owned);
let custom = CustomEditor { resource: resource.clone(), resolved: false, backup_id, navigation: Navigation::None, diff: None };
let handle = if text {
// The selection goes to the panel (`$revealCustomTextEditorRange`), not to the text model under it.
let mut options = options.clone();
options["selection"] = Value::Null;
self.try_show_text_document(resource, &options, window, cx)?;
let tab = self.editors.active_tab().expect("just shown").model_id;
let handle = self.attach_custom_text_editor(tab, view_type, custom)?;
self.editors_changed(cx);
handle
} else {
let shows = |panel: &WebviewPanel| panel.view_type == view_type && panel.custom.as_ref().is_some_and(|custom| custom.resource == *resource);
let in_active_group = |panel: &WebviewPanel| self.editors.editors.iter().any(|editor| panel.shows(editor));
// A custom document with several editors gets one more in the active group.
let handle = match self.webview_panels.panels.iter().find(|panel| shows(panel) && (!multiple || in_active_group(panel))) {
Some(panel) => panel.handle.clone(),
None => self.add_custom_document_editor(view_type, title, &extension, retain, Some(custom), options["pinned"] != true),
};
if let Some(panel) = self.webview_panel_mut(&handle) {
panel.find_enabled = find_enabled;
}
handle
};
if !text {
// editorResolverService.ts `moveExistingEditorForResource`: a singleton editor in another group moves here.
let (group, index) = self.webview_editor_group(&handle).expect("the panel's editor is open");
if group != self.editors.id {
let editor = self.with_group(group, |workbench| workbench.editors.take_editor(index));
self.insert_moved_editor(editor);
self.close_group_if_empty(group);
}
let (_, index) = self.webview_editor_group(&handle).expect("the panel's editor is open");
self.editors.activate(index);
if options["pinned"] == true {
self.editors.pin(index);
}
self.editors_changed(cx);
}
if options["preserveFocus"] != true {
self.focus_webview_panel(&handle, window, cx);
}
Ok(handle)
}
/// customEditors.ts `createDiffEditorInput`: one webview for the inline layout (`CustomEditorDiffInput`), else
/// one per side (`CustomEditorSideBySideDiffInput`, or `CustomEditorInput` when the provider has no diff
/// capability) over the diff editor's tab. The handle answered is the one whose resolve the open waits for.
fn show_custom_editor_diff(&mut self, view_type: &str, original: Side, modified: &Value, label: Option<String>, options: &Value, window: &mut Window, cx: &mut Context<Self>) -> Result<String, Value> {
let (scheme, path) = uri_parts(modified)?;
let modified_side = Side { scheme: scheme.to_owned(), path };
let provider = &self.webview_panels.custom_editors.providers[view_type];
// customEditors.ts `getDiffEditorLayout`.
let inline = match (provider.supports_inline_diff, provider.supports_side_by_side_diff) {
(true, true) => self.setting("diffEditor.renderSideBySide") == json!(false),
(inline, _) => inline,
};
let joint = provider.supports_inline_diff || provider.supports_side_by_side_diff;
let (extension, retain, find_enabled) = (provider.extension.clone(), provider.options["retainContextWhenHidden"] == true, provider.options["enableFindWidget"] == true);
let original_resource = uri_value(&original.scheme, &original.path);
let mut diff_options = options.clone();
diff_options["preserveFocus"] = json!(true);
let custom = CustomDiff { view_type: view_type.to_owned(), inline };
self.show_diff_editor(original.clone(), modified_side.clone(), label, Some(custom), &diff_options, window, cx);
let tab = self.editors.active_tab().expect("just shown");
let (tab_id, tab_path) = (tab.model_id, tab.document().path.clone());
let name = self.editors.diffs[&tab.model_id].name();
let sides = match inline {
true => vec![(DiffSide::Inline, modified.clone(), name)],
false => vec![(DiffSide::Original, original_resource.clone(), original.name()), (DiffSide::Modified, modified.clone(), modified_side.name())],
};
let mut handle = String::new();
for (side, resource, title) in sides {
let shown = self.webview_panels.panels.iter().find(|panel| panel.scheme == DIFF_EDITOR_SCHEME && panel.path == tab_path && panel.custom.as_ref().and_then(|custom| custom.diff.as_ref()).is_some_and(|part| part.side == side && part.tab == tab_id));
handle = match shown {
Some(panel) => panel.handle.clone(),
None => {
let diff = DiffPart { side, original: original_resource.clone(), modified: modified.clone(), joint, tab: tab_id };
let custom = CustomEditor { resource, resolved: false, backup_id: None, navigation: Navigation::None, diff: Some(diff) };
let handle = self.next_custom_editor_handle();
let mut panel = WebviewPanel::new(handle.clone(), DIFF_EDITOR_SCHEME.into(), tab_path.clone(), view_type, title, &extension, Value::Null, retain, Some(custom));
panel.find_enabled = find_enabled;
self.webview_panels.panels.push(panel);
handle
}
};
}
self.editors_changed(cx);
if options["preserveFocus"] != true {
self.focus_webview_panel(&handle, window, cx);
}
Ok(handle)
}
/// customEditors.ts `getActiveCustomEditorTextDiff`: the active diff is a custom text editor's own diff.
pub(super) fn active_custom_editor_text_diff(&self) -> bool {
let Some(custom) = self.editors.active_diff().and_then(|diff| diff.custom.as_ref()) else { return false };
let provider = self.webview_panels.custom_editors.providers.get(&custom.view_type);
provider.is_some_and(|provider| provider.text && (provider.supports_inline_diff || provider.supports_side_by_side_diff))
}
/// A custom editor diff's webview, or its sides' split as a side by side editor's.
pub(super) fn custom_editor_diff_body(&self, inline: bool, cx: &mut Context<Self>) -> gpui::Div {
let tab = self.editors.active_tab().expect("the diff editor's tab");
let side = |side| self.webview_body(|panel| panel.shows(tab) && panel.custom.as_ref().and_then(|custom| custom.diff.as_ref()).is_some_and(|part| part.side == side));
match inline {
true => side(DiffSide::Inline),
false => self.side_by_side_split(side(DiffSide::Original).into_any_element(), side(DiffSide::Modified).into_any_element(), cx),
}
}
/// A custom document's own editor: a webview panel with the placeholder model `webview-panel/webview-<viewType>-<handle>`.
pub(super) fn add_custom_document_editor(&mut self, view_type: &str, title: String, extension: &Value, retain: bool, custom: Option<CustomEditor>, preview: bool) -> String {
let handle = self.next_custom_editor_handle();
let placeholder = PathBuf::from(format!("webview-panel/webview-{view_type}-{handle}"));
let document = TextDocument::from_text(WEBVIEW_PANEL_SCHEME, &placeholder, "", "utf8".into(), None, &self.languages, &self.settings.lock().unwrap());
self.webview_panels.panels.push(WebviewPanel::new(handle.clone(), WEBVIEW_PANEL_SCHEME.into(), placeholder.clone(), view_type, title, extension, Value::Null, retain, custom));
self.leave_locked_group(WEBVIEW_PANEL_SCHEME, &placeholder);
self.editors.open(document, preview);
handle
}
/// The registered provider's extension description and whether it retains hidden webviews.
pub(super) fn custom_editor_provider(&self, view_type: &str) -> Option<(Value, bool)> {
let provider = self.webview_panels.custom_editors.providers.get(view_type)?;
Some((provider.extension.clone(), provider.options["retainContextWhenHidden"] == true))
}
/// Removes the active group's custom text editors of `resource`, as reopening it with another editor does.
fn detach_custom_editors(&mut self, resource: &Value) {
let tabs: Vec<u32> = self.editors.editors.iter().map(|editor| editor.model_id).collect();
self.detach_custom_text_editors(|panel| panel.editor.is_some_and(|tab| tabs.contains(&tab)) && panel.custom.as_ref().is_some_and(|custom| custom.resource == *resource));
}
/// Disposes the custom text editors' webviews `detached` picks: their tabs show the text editor again.
fn detach_custom_text_editors(&mut self, detached: impl Fn(&WebviewPanel) -> bool) {
let panels = std::mem::take(&mut self.webview_panels.panels);
let mut closed = Vec::new();
for panel in panels {
match panel.editor.is_some() && detached(&panel) {
true => {
self.host.send("ExtHostWebviewPanels", "$onDidDisposeWebviewPanel", vec![json!(panel.handle)]);
closed.push(panel);
}
false => self.webview_panels.panels.push(panel),
}
}
self.release_custom_documents(closed);
}
/// The custom documents of closed panels that no open panel holds are disposed (the model reference released).
pub(super) fn release_custom_documents(&mut self, closed: Vec<WebviewPanel>) {
for panel in closed {
let Some(custom) = panel.custom.filter(|custom| custom.resolved) else { continue };
for resource in custom.resources() {
let held = self.webview_panels.panels.iter().any(|other| other.view_type == panel.view_type && other.custom.as_ref().is_some_and(|other| other.resources().contains(&resource)));
if held || self.custom_document_index(resource, &panel.view_type).is_none() {
continue;
}
self.custom_document_disposed(resource, &panel.view_type);
self.host.send("ExtHostCustomEditors", "$disposeCustomDocument", vec![resource.clone(), json!(panel.view_type)]);
}
}
}
/// customEditorInput.ts for a text editor: each tab of the resource has a webview of its own. The tab keeps its
/// webview of `view_type`; one of another view type goes.
pub(super) fn attach_custom_text_editor(&mut self, tab: u32, view_type: &str, custom: CustomEditor) -> Result<String, Value> {
if let Some(panel) = self.webview_panels.panels.iter().find(|panel| panel.editor == Some(tab) && panel.view_type == view_type) {
return Ok(panel.handle.clone());
}
self.detach_custom_text_editors(|panel| panel.editor == Some(tab));
let (scheme, path) = uri_parts(&custom.resource)?;
let (scheme, title) = (scheme.to_owned(), path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default());
let provider = &self.webview_panels.custom_editors.providers[view_type];
let (extension, retain, find_enabled) = (provider.extension.clone(), provider.options["retainContextWhenHidden"] == true, provider.options["enableFindWidget"] == true);
let handle = self.next_custom_editor_handle();
let mut panel = WebviewPanel::new(handle.clone(), scheme, path, view_type, title, &extension, Value::Null, retain, Some(custom));
panel.editor = Some(tab);
panel.find_enabled = find_enabled;
self.webview_panels.panels.push(panel);
Ok(handle)
}
/// customEditorInput.ts `copy`: the copy of a custom text editor's tab that a split makes gets a webview of its own.
pub(super) fn copy_custom_text_editor(&mut self, source: u32, copy: u32) {
self.copy_custom_editor_diff(source, copy);
let Some(panel) = self.webview_panels.panels.iter().find(|panel| panel.editor == Some(source)) else { return };
let resource = panel.custom.as_ref().expect("a custom text editor's panel").resource.clone();
let custom = CustomEditor { resource, resolved: false, backup_id: None, navigation: Navigation::None, diff: None };
let view_type = panel.view_type.clone();
self.attach_custom_text_editor(copy, &view_type, custom).expect("the resource of an open panel");
}
/// customEditorDiffInput.ts `copy`: a split custom editor diff gets webviews of its own.
fn copy_custom_editor_diff(&mut self, source: u32, copy: u32) {
let is_side = |panel: &&WebviewPanel| panel.custom.as_ref().and_then(|custom| custom.diff.as_ref()).is_some_and(|part| part.tab == source);
let sides: Vec<_> = self
.webview_panels
.panels
.iter()
.filter(is_side)
.map(|side| {
let custom = side.custom.as_ref().expect("a diff side");
let part = custom.diff.as_ref().expect("a diff side");
let diff = DiffPart { side: part.side, original: part.original.clone(), modified: part.modified.clone(), joint: part.joint, tab: copy };
(side.scheme.clone(), side.path.clone(), side.view_type.clone(), side.title.clone(), side.find_enabled, custom.resource.clone(), diff)
})
.collect();
for (scheme, path, view_type, title, find_enabled, resource, diff) in sides {
let custom = CustomEditor { resource, resolved: false, backup_id: None, navigation: Navigation::None, diff: Some(diff) };
let (extension, retain) = self.custom_editor_provider(&view_type).expect("the provider of an open diff");
let mut panel = WebviewPanel::new(self.next_custom_editor_handle(), scheme, path, &view_type, title, &extension, Value::Null, retain, Some(custom));
panel.find_enabled = find_enabled;
self.webview_panels.panels.push(panel);
}
}
pub(super) fn next_custom_editor_handle(&mut self) -> String {
self.webview_panels.custom_editors.next_handle += 1;
format!("custom-editor-{}", self.webview_panels.custom_editors.next_handle)
}
/// mainThreadCustomEditors.ts `resolveWebview` for each custom editor not resolved yet: a custom document is
/// created first, once per resource and view type. The host has the text editor's document already, since
/// `editors_changed` sent it on the same channel.
pub(super) fn resolve_custom_editors(&mut self, cx: &mut Context<Self>) {
let active = self.webview_panels.panels.iter().position(|panel| !panel.is_diff_side() && self.editors.active().is_some_and(|editor| panel.shows(editor)));
let providers = &self.webview_panels.custom_editors.providers;
let (mut resolves, mut paired) = (Vec::new(), Vec::new());
for index in 0..self.webview_panels.panels.len() {
let panel = &self.webview_panels.panels[index];
let Some(provider) = providers.get(&panel.view_type) else { continue };
let Some(custom) = panel.custom.as_ref().filter(|custom| !custom.resolved) else { continue };
let document_open = |resource: &Value| {
self.webview_panels.panels.iter().any(|other| other.view_type == panel.view_type && other.custom.as_ref().is_some_and(|other| other.resolved && other.resources().contains(&resource)))
};
let creates: Vec<Vec<Value>> = match provider.text {
true => Vec::new(),
false => custom.resources().into_iter().filter(|resource| !document_open(resource)).map(|resource| vec![resource.clone(), json!(panel.view_type), json!(custom.backup_id), Value::Null]).collect(),
};
let init = |panel: &WebviewPanel, index| json!({ "title": panel.title, "contentOptions": {}, "options": provider.options, "active": active == Some(index) });
// `editorGroupToColumn`: the index in grid order of the group that shows the editor.
let group = self.webview_editor_group(&panel.handle).map(|(group, _)| group);
let column = group.and_then(|group| self.groups_in_grid_order().iter().position(|id| *id == group)).unwrap_or(0);
let (method, resolve) = match &custom.diff {
Some(part) if part.side == DiffSide::Inline => {
("$resolveCustomEditorInlineDiff", vec![part.original.clone(), part.modified.clone(), json!(panel.handle), json!(panel.view_type), init(panel, index), json!(column)])
}
// mainThreadCustomEditors.ts `resolveCustomEditorSideBySideDiff`: one call for both sides' webviews.
Some(part) if part.joint => {
if part.side == DiffSide::Original {
continue;
}
let is_original = |other: &WebviewPanel| other.path == panel.path && other.custom.as_ref().is_some_and(|other| !other.resolved && other.diff.as_ref().is_some_and(|part| part.side == DiffSide::Original));
let Some(original_index) = self.webview_panels.panels.iter().position(is_original) else { continue };
let original = &self.webview_panels.panels[original_index];
let handles = json!({ "original": original.handle, "modified": panel.handle });
let inits = json!({ "original": init(original, original_index), "modified": init(panel, index) });
paired.push(original_index);
("$resolveCustomEditorSideBySideDiff", vec![part.original.clone(), part.modified.clone(), handles, json!(panel.view_type), inits, json!(column)])
}
_ => ("$resolveCustomEditor", vec![custom.resource.clone(), json!(panel.handle), json!(panel.view_type), init(panel, index), json!(column)]),
};
let navigate = (provider.text && provider.supports_navigation && custom.diff.is_none()).then(|| custom.resource.clone());
resolves.push((panel.handle.clone(), panel.view_type.clone(), creates, method, resolve, navigate));
self.webview_panels.panels[index].custom.as_mut().expect("checked above").resolved = true;
}
for index in paired {
self.webview_panels.panels[index].custom.as_mut().expect("a diff side").resolved = true;
}
for (handle, view_type, creates, method, resolve, navigate) in resolves {
let created: Vec<_> = creates.into_iter().map(|args| ((args[0].clone(), args[2].is_string()), self.host.call("ExtHostCustomEditors", "$createCustomDocument", args))).collect();
// mainThreadCustomEditors.ts resolves the editor once `$createCustomDocument` answered: the host's
// `$resolveCustomEditor` looks the document up.
cx.spawn(async move |workbench, cx| {
let canceled = |_| Err(serialized_error("Canceled"));
let mut result = Ok(Value::Null);
for ((resource, from_backup), created) in created {
match created.await.unwrap_or_else(canceled) {
Ok(created) => {
let (editable, view_type) = (created["editable"] == true, view_type.clone());
let _ = workbench.update(cx, |workbench, cx| workbench.custom_document_created(resource, view_type, editable, from_backup, cx));
}
Err(error) => {
result = Err(error);
break;
}
}
}
let result = match result {
Ok(_) => match workbench.update(cx, |workbench, _| workbench.host.call("ExtHostCustomEditors", method, resolve)) {
Ok(resolved) => resolved.await.unwrap_or_else(canceled),
Err(_) => return,
},
Err(error) => Err(error),
};
if let (Ok(_), Some(resource)) = (&result, navigate) {
let Ok(navigation) = workbench.update(cx, |workbench, _| workbench.resolve_custom_text_editor_navigation(&handle, &view_type, resource)) else { return };
if let Some(navigation) = navigation {
let answer = navigation.await.unwrap_or_else(canceled);
let _ = workbench.update(cx, |workbench, cx| workbench.custom_text_editor_navigation_resolved(&handle, answer, cx));
}
}
let _ = workbench.update(cx, |workbench, _| {
if let Err(error) = result {
eprintln!("[custom editor] {view_type}: {error}");
workbench.show_resolve_failure(&handle, &view_type);
}
for (reply, options) in workbench.webview_panels.custom_editors.opening.remove(&handle).unwrap_or_default() {
workbench.apply_custom_editor_options(&handle, &options);
let _ = reply.send(Ok(Value::Null));
}
workbench.sync_webview_panels();
});
})
.detach();
}
}
/// Asks the host for the navigation of a custom text editor still open.
fn resolve_custom_text_editor_navigation(&mut self, handle: &str, view_type: &str, resource: Value) -> Option<oneshot::Receiver<Result<Value, Value>>> {
self.webview_panel_mut(handle)?.custom.as_mut()?.navigation = Navigation::Resolving(None);
Some(self.host.call("ExtHostCustomEditors", "$resolveCustomTextEditorNavigation", vec![json!(handle), json!(view_type), resource]))
}
/// The host's answer: the selection it reported since wins over the one answered, and the outline follows the
/// editor (`notifyOutlineChanged`). No navigation tells the host to dispose its entry.
fn custom_text_editor_navigation_resolved(&mut self, handle: &str, answer: Result<Value, Value>, cx: &mut Context<Self>) {
let Some(custom) = self.webview_panel_mut(handle).and_then(|panel| panel.custom.as_mut()) else { return };
let Navigation::Resolving(changed) = std::mem::replace(&mut custom.navigation, Navigation::None) else { return };
match answer {
Ok(result) if result.is_object() => {
custom.navigation = Navigation::Ready(changed.unwrap_or_else(|| result["selection"].clone()));
self.outline_providers_changed(cx);
}
Ok(_) => self.host.send("ExtHostCustomEditors", "$disposeCustomTextEditorNavigation", vec![json!(handle)]),
Err(error) => eprintln!("[custom editor] navigation: {error}"),
}
}
/// The provider's disposables end the navigation of its editors (`MainThreadCustomTextEditorNavigation.dispose`).
fn dispose_custom_text_editor_navigations(&mut self, view_type: &str, cx: &mut Context<Self>) {
for panel in self.webview_panels.panels.iter_mut().filter(|panel| panel.view_type == view_type) {
let Some(custom) = panel.custom.as_mut() else { continue };
if let Navigation::Ready(_) = std::mem::replace(&mut custom.navigation, Navigation::None) {
self.host.send("ExtHostCustomEditors", "$disposeCustomTextEditorNavigation", vec![json!(panel.handle)]);
}
}
self.outline_providers_changed(cx);
}
/// The custom editor's panel a tab shows instead of its text model's code editor.
pub(super) fn custom_editor_over(&self, editor: &OpenEditor) -> Option<&WebviewPanel> {
self.webview_panels.panels.iter().find(|panel| panel.scheme != WEBVIEW_PANEL_SCHEME && panel.custom.is_some() && panel.shows(editor))
}
/// customEditorInput.ts `applyOptions`: a custom text editor with navigation reveals and selects
/// `options.selection`. The editor has the focus already unless `preserveFocus`.
fn apply_custom_editor_options(&mut self, handle: &str, options: &Value) {
let selection = &options["selection"];
let Some(start) = selection["startLineNumber"].as_u64().zip(selection["startColumn"].as_u64()) else { return };
let end = (selection["endLineNumber"].as_u64().unwrap_or(start.0), selection["endColumn"].as_u64().unwrap_or(start.1));
let range = crate::outline_model::Range { start: (start.0 as usize, start.1 as usize), end: (end.0 as usize, end.1 as usize) };
drop(self.reveal_custom_text_editor_range(handle, range, Some(range), options["preserveFocus"] == true));
}
/// MainThreadCustomTextEditorNavigation `revealRange`, with `selection` selected left to right
/// (`Selection.fromRange`); None without a resolved navigation.
pub(super) fn reveal_custom_text_editor_range(&mut self, handle: &str, range: crate::outline_model::Range, selection: Option<crate::outline_model::Range>, preserve_focus: bool) -> Option<oneshot::Receiver<Result<Value, Value>>> {
custom_navigation(self.webview_panels.panels.iter().find(|panel| panel.handle == handle)?)?;
// `new Range` orders its ends.
let ordered = |range: crate::outline_model::Range| (range.start.min(range.end), range.start.max(range.end));
let (start, end) = ordered(range);
let range = json!({ "startLineNumber": start.0, "startColumn": start.1, "endLineNumber": end.0, "endColumn": end.1 });
let selection = selection.map(ordered).map(|(start, end)| json!({ "selectionStartLineNumber": start.0, "selectionStartColumn": start.1, "positionLineNumber": end.0, "positionColumn": end.1 }));
Some(self.host.call("ExtHostCustomEditors", "$revealCustomTextEditorRange", vec![json!(handle), range, json!(selection), json!(preserve_focus)]))
}
/// mainThreadWebviews.ts `getWebviewResolvedFailedContent`.
fn show_resolve_failure(&mut self, handle: &str, view_type: &str) {
let Some(panel) = self.webview_panel_mut(handle) else { return };
let escaped = view_type.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace('\'', "'");
panel.html = format!(
"<!DOCTYPE html>\n\t\t<html>\n\t\t\t<head>\n\t\t\t\t<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\">\n\t\t\t\t<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none';\">\n\t\t\t</head>\n\t\t\t<body>An error occurred while loading view: {escaped}</body>\n\t\t</html>"
);
panel.update_content();
}
/// Custom text editors whose resource `move_models` moved: with `moveCustomTextEditor` the provider follows it
/// (`$onMoveCustomEditor`), else the editor reopens at the target (`CustomEditorInput.rename`) in a new webview,
/// which `resolve_custom_editors` resolves once the host has the moved document.
pub(super) fn move_custom_editors(&mut self, source_scheme: &str, source: &Path, target_scheme: &str, target: &Path) {
for index in 0..self.webview_panels.panels.len() {
let panel = &self.webview_panels.panels[index];
let Some(rest) = panel.path.strip_prefix(source).ok().filter(|_| panel.scheme == source_scheme && panel.custom.is_some()) else { continue };
let path = if rest.as_os_str().is_empty() { target.to_path_buf() } else { target.join(rest) };
let Some(resource) = self.editors.editors.iter().find(|editor| editor.document().is(target_scheme, &path)).map(|editor| editor.document().uri()) else { continue };
let supports_move = self.webview_panels.custom_editors.providers.get(&panel.view_type).is_some_and(|provider| provider.supports_move);
let new_handle = (!supports_move).then(|| self.next_custom_editor_handle());
let panel = &mut self.webview_panels.panels[index];
panel.scheme = target_scheme.to_owned();
panel.title = path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
panel.path = path;
let custom = panel.custom.as_mut().expect("checked above");
custom.resource = resource.clone();
match new_handle {
None => self.host.send("ExtHostCustomEditors", "$onMoveCustomEditor", vec![json!(panel.handle), resource, json!(panel.view_type)]),
Some(handle) => {
let old_handle = std::mem::replace(&mut panel.handle, handle);
custom.resolved = false;
custom.navigation = Navigation::None;
panel.webview = None;
panel.html.clear();
panel.state = Value::Null;
self.host.send("ExtHostWebviewPanels", "$onDidDisposeWebviewPanel", vec![json!(old_handle)]);
}
}
}
}
}
/// editorResolverService.ts `globMatchesResource` for one resource.
pub(super) fn resource_matcher(scheme: &str, path: &Path) -> Option<impl Fn(&str) -> bool> {
// These schemes match no glob.
if matches!(scheme, "extension" | WEBVIEW_PANEL_SCHEME | "vscode-workspace-trust" | "vscode-settings") {
return None;
}
let full_path = format!("{scheme}:{}", path.display());
let basename = path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
Some(move |pattern: &str| {
let target = if pattern.contains('/') { full_path.as_str() } else { basename.as_str() };
glob::match_pattern(pattern, target, Options { ignore_case: true, ..Options::default() })
})
}
/// A `contributes.customEditors` entry as contributedCustomEditors.ts reads it.
#[derive(Clone)]
pub(super) struct Contribution {
pub(super) view_type: String,
pub(super) display_name: String,
/// `providerDisplayName`.
pub(super) provider: String,
/// `selector[].filenamePattern`.
pub(super) patterns: Vec<String>,
/// `priorityToRank` of `getPriorityFromContribution`.
pub(super) rank: u8,
/// The rank in a diff editor: `priority.diffEditor`, `explicit` when only `textEditor` is given.
pub(super) diff_rank: u8,
}
impl Contribution {
fn rank_for(&self, diff: bool) -> u8 {
if diff { self.diff_rank } else { self.rank }
}
}
/// `getSinglePriorityFromContribution` as a rank.
fn rank_of(priority: Option<&str>, is_builtin: bool) -> u8 {
match priority {
Some("exclusive") => RANK_EXCLUSIVE,
Some("option") => RANK_OPTION,
Some("explicit") => 0,
Some("builtin") if is_builtin => RANK_BUILTIN,
_ => RANK_DEFAULT,
}
}
/// contributedCustomEditors.ts `getSinglePriorityFromContribution`.
fn stored_priority(priority: Option<&str>, is_builtin: bool) -> Option<&'static str> {
match priority? {
"default" => Some("default"),
"option" => Some("option"),
"explicit" => Some("explicit"),
"builtin" if is_builtin => Some("builtin"),
"builtin" => Some("default"),
_ => None,
}
}
/// `CustomEditorInfo` of each stored editor; the priorities were stored as `getSinglePriorityFromContribution` gave them.
fn memento_contributions(memento: &Value) -> Vec<Contribution> {
let mut contributions = Vec::new();
for editor in memento["editors"].as_array().into_iter().flatten() {
let Some(view_type) = editor["id"].as_str() else { continue };
let selectors = editor["selector"].as_array().into_iter().flatten();
contributions.push(Contribution {
view_type: view_type.to_owned(),
display_name: editor["displayName"].as_str().unwrap_or_default().to_owned(),
provider: editor["providerDisplayName"].as_str().unwrap_or_default().to_owned(),
patterns: selectors.filter_map(|selector| selector["filenamePattern"].as_str()).map(str::to_owned).collect(),
rank: rank_of(editor["priority"]["editor"].as_str(), true),
diff_rank: rank_of(editor["priority"]["diff"].as_str(), true),
});
}
contributions
}
fn custom_editor_contributions(extensions: &[exthost::scan::ScannedExtension]) -> Vec<Contribution> {
let mut contributions = Vec::new();
for extension in extensions {
let is_builtin = extension.description["isBuiltin"] == true;
let provider = match is_builtin {
true => "Built-in".to_owned(),
false => extension.description["displayName"].as_str().map_or(extension.id.clone(), str::to_owned),
};
for contribution in extension.description["contributes"]["customEditors"].as_array().into_iter().flatten() {
let Some(view_type) = contribution["viewType"].as_str() else { continue };
let priority = &contribution["priority"];
let rank = rank_of(priority.as_str().or(priority["textEditor"].as_str()), is_builtin);
let diff_rank = match priority.as_str() {
Some(_) => rank,
None => priority["diffEditor"].as_str().map_or(0, |diff| rank_of(Some(diff), is_builtin)),
};
let selectors = contribution["selector"].as_array().into_iter().flatten();
let patterns = selectors.filter_map(|selector| selector["filenamePattern"].as_str()).map(str::to_owned).collect();
let display_name = contribution["displayName"].as_str().unwrap_or_default().to_owned();
contributions.push(Contribution { view_type: view_type.to_owned(), display_name, provider: provider.clone(), patterns, rank, diff_rank });
}
}
contributions.extend(notebook_contributions(extensions));
contributions
}
/// notebookServiceImpl.ts `_registerContributionPoint`: each notebook type is an editor, `default` unless it says otherwise;
/// the first contribution of a type wins.
fn notebook_contributions(extensions: &[exthost::scan::ScannedExtension]) -> Vec<Contribution> {
let mut contributions = Vec::new();
for extension in extensions {
let provider = match extension.description["isBuiltin"] == true {
true => "Built-in".to_owned(),
false => extension.description["displayName"].as_str().map_or(extension.id.clone(), str::to_owned),
};
for contribution in extension.description["contributes"]["notebooks"].as_array().into_iter().flatten() {
let view_type = contribution["type"].as_str();
if contributions.iter().any(|known: &Contribution| Some(known.view_type.as_str()) == view_type) {
continue;
}
contributions.extend(notebook_contribution(view_type, contribution, &contribution["selector"], &provider));
}
}
contributions
}
/// A notebook type, from its contribution or from the memento (`selector` there is `selectors`).
fn notebook_contribution(view_type: Option<&str>, entry: &Value, selectors: &Value, provider: &str) -> Option<Contribution> {
let rank = match entry["priority"].as_str() {
None | Some("default") => RANK_DEFAULT,
Some(_) => RANK_OPTION,
};
let selectors = selectors.as_array().into_iter().flatten();
let patterns = selectors.filter_map(|selector| selector["filenamePattern"].as_str().or(selector["filenamePattern"]["include"].as_str())).map(str::to_owned).collect();
let display_name = entry["displayName"].as_str().unwrap_or_default().to_owned();
Some(Contribution { view_type: view_type?.to_owned(), display_name, provider: provider.to_owned(), patterns, rank, diff_rank: rank })
}
#[cfg(test)]
mod tests {
use super::*;
use exthost::scan::ScannedExtension;
fn extension(builtin: bool, custom_editors: Value) -> ScannedExtension {
let description = json!({ "isBuiltin": builtin, "displayName": "Hex", "contributes": { "customEditors": custom_editors } });
ScannedExtension { id: "pub.hex".into(), location: PathBuf::new(), description }
}
#[test]
fn ranks_contributions_as_contributed_custom_editors_does() {
let editors = json!([
{ "viewType": "a", "displayName": "A", "selector": [{ "filenamePattern": "*.png" }] },
{ "viewType": "b", "priority": "option", "selector": [{ "filenamePattern": "*.png" }, { "filenamePattern": "**/x/*.bin" }] },
{ "viewType": "c", "priority": "builtin" },
{ "viewType": "d", "priority": { "textEditor": "explicit" } },
]);
let ranks = |builtin| custom_editor_contributions(&[extension(builtin, editors.clone())]).into_iter().map(|contribution| contribution.rank).collect::<Vec<_>>();
assert_eq!(ranks(false), [RANK_DEFAULT, 1, RANK_DEFAULT, 0]);
assert_eq!(ranks(true), [RANK_DEFAULT, 1, RANK_BUILTIN, 0]);
let contributions = custom_editor_contributions(&[extension(false, editors)]);
assert_eq!((contributions[1].provider.as_str(), contributions[1].patterns.len()), ("Hex", 2));
}
/// notebookServiceImpl.ts `_setupHandler`: a notebook type already contributed is not registered again.
#[test]
fn the_first_notebook_contribution_of_a_type_wins() {
let notebooks = |name: &str| ScannedExtension { id: name.into(), location: PathBuf::new(), description: json!({ "displayName": name, "contributes": { "notebooks": [{ "type": "nb", "displayName": name }] } }) };
let contributions = notebook_contributions(&[notebooks("First"), notebooks("Second")]);
assert_eq!(contributions.iter().map(|contribution| contribution.provider.as_str()).collect::<Vec<_>>(), ["First"]);
}
#[test]
fn matches_globs_as_glob_matches_resource_does() {
let matches = resource_matcher("file", Path::new("/w/x/Image.PNG")).expect("file resources match globs");
assert!(matches("*.png"));
assert!(matches("**/x/*.png"));
assert!(!matches("*.bin"));
assert!(resource_matcher(WEBVIEW_PANEL_SCHEME, Path::new("webview-panel/a.png")).is_none());
}
}