Visual Studio Code, rebuilt in Rust
Rust
feat(custom-editor): open diffs of custom editor files as custom diffs
rokarturfb38c9d53668
diff --git a/native/crates/app/src/diff_editor.rs b/native/crates/app/src/diff_editor.rsindex df8569d6a9b..a2bd750d107 100644--- a/native/crates/app/src/diff_editor.rs+++ b/native/crates/app/src/diff_editor.rs@@ -66,6 +66,16 @@ pub struct DiffInput {pub placed_original_unchanged: Vec<(u32, usize)>,/// The scroll both side editors had after the last sync: the side that differs from it scrolled.pub synced_scroll: crate::editor::Scroll,+ /// The custom editor showing the diff in place of the text diff editor (customEditors.ts `createDiffEditorInput`).+ pub custom: Option<CustomDiff>,+}++/// A custom editor's diff: its view type, and whether it is one `CustomEditorDiffInput` (inline) rather than a+/// `DiffEditorInput` of a webview per side.+#[derive(Clone, PartialEq)]+pub struct CustomDiff {+ pub view_type: String,+ pub inline: bool,}/// The diff of the models' versions it was computed for.@@ -77,19 +87,25 @@ pub struct ComputedDiff {impl DiffInput {pub fn new(original: Side, modified: Side, label: Option<String>) -> Self {- DiffInput { original, modified, label, diff: None, inline_now: false, zones: Vec::new(), placed_zones: Vec::new(), unchanged: Vec::new(), unchanged_key: None, placed_unchanged: Vec::new(), unchanged_cursors: Vec::new(), unchanged_drag: None, symbols: Vec::new(), symbols_version: None, modified_editor: None, original_editor: None, original_focused: false, placed_original_zones: Vec::new(), placed_original_unchanged: Vec::new(), synced_scroll: crate::editor::Scroll::default() }+ DiffInput { original, modified, label, diff: None, inline_now: false, zones: Vec::new(), placed_zones: Vec::new(), unchanged: Vec::new(), unchanged_key: None, placed_unchanged: Vec::new(), unchanged_cursors: Vec::new(), unchanged_drag: None, symbols: Vec::new(), symbols_version: None, modified_editor: None, original_editor: None, original_focused: false, placed_original_zones: Vec::new(), placed_original_unchanged: Vec::new(), synced_scroll: crate::editor::Scroll::default(), custom: None }}- /// `computeLabels` name: the preferred label, else `original ↔ modified`.+ /// `computeLabels` name: the preferred label, else `original ↔ modified`; customEditorDiffInput.ts `getName`+ /// of an inline custom editor diff: `original - modified`.pub fn name(&self) -> String {match &self.label {Some(label) => label.clone(),+ None if self.custom.as_ref().is_some_and(|custom| custom.inline) => format!("{} - {}", self.original.name(), self.modified.name()),None => format!("{} \u{2194} {}", self.original.name(), self.modified.name()),}}/// `computeLabels` title (medium verbosity): the sides' paths joined with ` ↔ `, after the preferred label.pub fn title(&self, path_label: impl Fn(&Side) -> String) -> String {+ // customEditorDiffInput.ts `getTitle`: the name, as no description is passed.+ if self.custom.as_ref().is_some_and(|custom| custom.inline) {+ return self.name();+ }let (original, modified) = (path_label(&self.original), path_label(&self.modified));let title = if original == modified { modified } else { format!("{original} \u{2194} {modified}") };match &self.label {diff --git a/native/crates/app/src/editor.rs b/native/crates/app/src/editor.rsindex 4a278423807..a8fb91f4dc5 100644--- a/native/crates/app/src/editor.rs+++ b/native/crates/app/src/editor.rs@@ -1526,7 +1526,7 @@ impl EditorGroup {copy.restore_view_state(&view_state, self.viewport);let diff = self.diffs.get(&tab_id).map(|diff| {let view_state = |editor: &Option<OpenEditor>| editor.as_ref().map(|editor| editor.view_state(self.viewport));- (DiffInput { inline_now: diff.inline_now, ..DiffInput::new(diff.original.clone(), diff.modified.clone(), diff.label.clone()) }, view_state(&diff.original_editor), view_state(&diff.modified_editor))+ (DiffInput { inline_now: diff.inline_now, custom: diff.custom.clone(), ..DiffInput::new(diff.original.clone(), diff.modified.clone(), diff.label.clone()) }, view_state(&diff.original_editor), view_state(&diff.modified_editor))});if let Some((mut input, original_state, modified_state)) = diff {self.attach_side_editors(&mut input);diff --git a/native/crates/app/src/host_sync.rs b/native/crates/app/src/host_sync.rsindex 01b4b6aa112..34c86fe1a1c 100644--- a/native/crates/app/src/host_sync.rs+++ b/native/crates/app/src/host_sync.rs@@ -199,7 +199,8 @@ impl HostSync {}// `_getActiveEditorFromCodeEditor`: a focused comment editor is a simple widget, the pane's editor stays active.let peek_listed = |editor: &OpenEditor| visible.iter().any(|(_, listed, _)| listed.model_id == editor.model_id);- let active_id = group.active().filter(|editor| self.is_text(editor)).filter(|editor| editor.peek_preview.is_none() || peek_listed(editor)).or_else(|| group.pane_editor().filter(|editor| self.is_text(editor))).map(snapshot_id);+ let custom_diff = group.active_tab().and_then(|tab| group.diffs.get(&tab.model_id)).is_some_and(|diff| diff.custom.is_some());+ let active_id = group.active().filter(|editor| self.is_text(editor)).filter(|editor| editor.peek_preview.is_none() || peek_listed(editor)).or_else(|| group.pane_editor().filter(|editor| self.is_text(editor))).filter(|_| !custom_diff).map(snapshot_id);if active_id != self.active_editor || delta.contains_key("removedEditors") || delta.contains_key("addedEditors") {delta.insert("newActiveEditor".into(), json!(active_id));}@@ -418,6 +419,10 @@ impl HostSync {// The active group is a secondary side outside the grid: its column is its side by side editor's.let id = group.side_group_owner(id).unwrap_or(id);let Some((editor, viewport)) = group.group_active(id) else { continue };+ // A custom editor diff draws webviews, no code editor.+ if group.group_active_tab(id).and_then(|tab| group.diffs.get(&tab.model_id)).is_some_and(|diff| diff.custom.is_some()) {+ continue;+ }// The cells whose code editor holds their model (notebook_cells), the focused one first.let mut cells = group.group_active_tab(id).map(|tab| crate::workbench::notebook_cells(&self.notebooks, group, tab)).unwrap_or_default();// The playground's snippet editors too (walkThroughPart.ts `CodeEditorWidget`s).@@ -772,11 +777,18 @@ fn tab_dto(group: u32, editor: &OpenEditor, active: bool, sync: &HostSync) -> Vafn diff_tab_dto(group: u32, editor: &OpenEditor, diff: &DiffInput, active: bool, dirty: bool) -> Value {let (original, modified) = (uri_string(&diff.original.scheme, &diff.original.path), uri_string(&diff.modified.scheme, &diff.modified.path));let uri = |side: &crate::diff_editor::Side| uri_value(&side.scheme, &side.path);+ // A `CustomEditorDiffInput` is a webview input (TabInputKind.WebviewEditorInput); a `DiffEditorInput` of+ // custom editor sides is no text diff (TabInputKind.UnknownInput).+ let (id, input, editor_id) = match &diff.custom {+ Some(custom) if custom.inline => (format!("{group}~{0}-workbench.editors.customDiffEditor-{modified}-{original} ", custom.view_type), json!({ "kind": 7, "viewType": custom.view_type }), custom.view_type.as_str()),+ Some(_) => (format!("{group}~default-workbench.editors.diffEditorInput-{modified}-{original} "), json!({ "kind": 0 }), "default"),+ None => (format!("{group}~default-workbench.editors.diffEditorInput-{modified}-{original} "), json!({ "kind": 2, "original": uri(&diff.original), "modified": uri(&diff.modified) }), "default"),+ };json!({- "id": format!("{group}~default-workbench.editors.diffEditorInput-{modified}-{original} "),+ "id": id,"label": diff.name(),- "input": { "kind": 2, "original": uri(&diff.original), "modified": uri(&diff.modified) },- "editorId": "default",+ "input": input,+ "editorId": editor_id,"isActive": active,"isPinned": editor.sticky,"isPreview": editor.preview,diff --git a/native/crates/app/src/workbench/actions.rs b/native/crates/app/src/workbench/actions.rsindex 3308cac7be3..01c9a5e93b6 100644--- a/native/crates/app/src/workbench/actions.rs+++ b/native/crates/app/src/workbench/actions.rs@@ -82,6 +82,7 @@ impl Workbench {workbench.reopen_active_editor_with(args.first().and_then(Value::as_str).map(str::to_owned), window, cx)});self.commands.register("workbench.action.reopenWithEditor", |workbench, _, window, cx| workbench.reopen_active_editor_with(None, window, cx));+ self.commands.register("workbench.action.reopenTextEditor", |workbench, _, window, cx| workbench.reopen_active_editor_with(Some(super::custom_editors::TEXT_EDITOR_ID.to_owned()), window, cx));self.commands.register("explorer.openWith", |workbench, args, window, cx| {if let Some(resource) = workbench.resource_for_command(&args, window) {workbench.show_open_with_picker_for(&resource, window, cx);diff --git a/native/crates/app/src/workbench/custom_documents.rs b/native/crates/app/src/workbench/custom_documents.rsindex 44816fd31b6..6e9ad689d4c 100644--- a/native/crates/app/src/workbench/custom_documents.rs+++ b/native/crates/app/src/workbench/custom_documents.rs@@ -92,7 +92,7 @@ impl Workbench {self.webview_panels.custom_editors.documents.retain(|document| !(document.resource == *resource && document.view_type == view_type));}- fn custom_document_index(&self, resource: &Value, view_type: &str) -> Option<usize> {+ pub(super) fn custom_document_index(&self, resource: &Value, view_type: &str) -> Option<usize> {// The host's `UriComponents` carry `external` and `$mid` the stored resource may lack.let key = crate::references_model::uri_key(resource);self.webview_panels.custom_editors.documents.iter().position(|document| crate::references_model::uri_key(&document.resource) == key && document.view_type == view_type)@@ -374,7 +374,7 @@ impl Workbench {drop(self.host.activate_by_event(&format!("onCustomEditor:{view_type}")));let retain = self.custom_editor_provider(view_type).is_some_and(|(_, retain)| retain);let title = meta["customTitle"].as_str().unwrap_or_default().to_owned();- let custom = Some(super::custom_editors::CustomEditor { resource, resolved: false, backup_id: Some(backup_id.to_owned()), navigation: super::custom_editors::Navigation::None });+ let custom = Some(super::custom_editors::CustomEditor { resource, resolved: false, backup_id: Some(backup_id.to_owned()), navigation: super::custom_editors::Navigation::None, diff: None });let handle = self.add_custom_document_editor(view_type, title, &meta["extension"], retain, custom, false);if let Some(panel) = self.webview_panel_mut(&handle) {panel.state = meta["webview"]["state"].clone();diff --git a/native/crates/app/src/workbench/custom_documents/tests.rs b/native/crates/app/src/workbench/custom_documents/tests.rsindex ff2ff250ec4..80f74f8a7e5 100644--- a/native/crates/app/src/workbench/custom_documents/tests.rs+++ b/native/crates/app/src/workbench/custom_documents/tests.rs@@ -382,3 +382,55 @@ fn two_default_editors_for_a_resource_ask_once_which_to_keep(cx: &mut TestAppConassert!(warnings(cx).is_empty());let _ = std::fs::remove_dir_all(dir);}++/// customEditors.ts `createDiffEditorInput`: a text custom editor that supports inline diffs resolves the diff in one+/// webview (`$resolveCustomEditorInlineDiff`); Reopen as Text (`ReOpenInTextEditorAction`) turns it into the text diff.+#[gpui::test]+fn reopen_as_text_turns_an_inline_custom_diff_into_the_text_diff(cx: &mut TestAppContext) {+ let dir = scratch();+ std::fs::write(dir.join("folder/a.txt"), "a").unwrap();+ std::fs::write(dir.join("folder/b.txt"), "b").unwrap();+ let (workbench, receiver, cx) = open(cx, &dir);+ let extension = json!({ "id": "port.test", "location": { "scheme": "file", "path": "/ext" } });+ let args = [extension, json!("test.text"), json!({}), json!({ "supportsInlineDiff": true }), json!(false)];+ let side = |name: &str| crate::diff_editor::Side { scheme: "file".into(), path: dir.join("folder").join(name) };+ let modified = Uri::new("file", "", &dir.join("folder/b.txt").to_string_lossy(), "", "").unwrap().to_json();+ workbench.update_in(cx, |workbench, window, cx| {+ drop(workbench.handle_custom_editors_request("$registerTextEditorProvider", &args, window, cx));+ drop(workbench.open_custom_editor("test.text".into(), modified, Some((side("a.txt"), None)), json!({}), window, cx));+ });+ cx.run_until_parked();+ let message = next(&receiver, "$resolveCustomEditorInlineDiff");+ answer(message, Value::Null, cx);+ let shown = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| {+ let diff = workbench.editors.active_diff().expect("an active diff");+ (diff.custom.as_ref().map(|custom| (custom.view_type.clone(), custom.inline)), diff.name(), workbench.active_custom_editor_text_diff())+ });+ assert_eq!(shown(cx), (Some(("test.text".to_owned(), true)), "a.txt - b.txt".to_owned(), true));+ run(&workbench, "workbench.action.reopenTextEditor", cx);+ assert_eq!(shown(cx), (None, "a.txt \u{2194} b.txt".to_owned(), false));+ let _ = std::fs::remove_dir_all(dir);+}++/// editor.contribution.ts Reopen as Text has `enableInModalMode`: a custom diff in the modal part shows it in the header.+#[gpui::test]+fn the_modal_header_of_a_custom_diff_offers_reopen_as_text(cx: &mut TestAppContext) {+ let dir = scratch();+ std::fs::write(dir.join("folder/a.txt"), "a").unwrap();+ std::fs::write(dir.join("folder/b.txt"), "b").unwrap();+ let (workbench, receiver, cx) = open(cx, &dir);+ let extension = json!({ "id": "port.test", "location": { "scheme": "file", "path": "/ext" } });+ let args = [extension, json!("test.text"), json!({}), json!({ "supportsInlineDiff": true }), json!(false)];+ let side = |name: &str| crate::diff_editor::Side { scheme: "file".into(), path: dir.join("folder").join(name) };+ let modified = Uri::new("file", "", &dir.join("folder/b.txt").to_string_lossy(), "", "").unwrap().to_json();+ workbench.update_in(cx, |workbench, window, cx| {+ workbench.update_setting("workbench.editor.useModal", json!("all"));+ drop(workbench.handle_custom_editors_request("$registerTextEditorProvider", &args, window, cx));+ drop(workbench.open_custom_editor("test.text".into(), modified, Some((side("a.txt"), None)), json!({}), window, cx));+ });+ cx.run_until_parked();+ answer(next(&receiver, "$resolveCustomEditorInlineDiff"), Value::Null, cx);+ assert_eq!(workbench.read_with(cx, |workbench, _| workbench.editors.id), crate::editor::MODAL_GROUP);+ assert!(cx.debug_bounds("modal-editor-action-workbench.action.reopenTextEditor").is_some());+ let _ = std::fs::remove_dir_all(dir);+}diff --git a/native/crates/app/src/workbench/custom_editors.rs b/native/crates/app/src/workbench/custom_editors.rsindex 413e18377e8..8520937111f 100644--- a/native/crates/app/src/workbench/custom_editors.rs+++ b/native/crates/app/src/workbench/custom_editors.rs@@ -8,7 +8,7 @@ use std::path::{Path, PathBuf};use exthost::main_thread::serialized_error;use files::glob::{self, Options};use futures::channel::oneshot;-use gpui::{Context, Window};+use gpui::{Context, IntoElement, Window};use serde_json::{Value, json};use super::Workbench;@@ -16,7 +16,8 @@ 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::editor::{ContentChanged, OpenEditor, TextDocument};+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};@@ -49,7 +50,7 @@ pub struct CustomEditors {pending: Vec<PendingOpen>,/// Opens answered once their editor's `$resolveCustomEditor` settles (WebviewEditor.setInput awaits `resolveWebview`),/// with the options `applyOptions` reveals then.- opening: HashMap<String, Vec<(oneshot::Sender<Result<Value, Value>>, Value)>>,+ 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>,@@ -64,6 +65,9 @@ struct Provider {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 {@@ -71,6 +75,8 @@ struct PendingOpen {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@@ -94,6 +100,39 @@ pub(super) struct CustomEditor {/// 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@@ -126,6 +165,8 @@ impl Workbench {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);@@ -177,7 +218,7 @@ impl Workbench {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(), options, window, cx),+ None => self.open_custom_editor(view_type, resource.clone(), None, options, window, cx),},None => {self.detach_custom_editors(resource);@@ -193,6 +234,13 @@ impl Workbench {(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 {@@ -402,6 +450,10 @@ impl Workbench {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 {@@ -435,13 +487,28 @@ impl Workbench {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| replaced(&self.editors.editors[index]));+ 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);- self.editors_changed(cx);+ // 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 outcome = self.open_with_resolver(resource, Some(editor_id), json!({ "preserveFocus": preserve_focus }), window, 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()@@ -633,10 +700,10 @@ impl Workbench {/// Opens `resource` in the custom editor of `view_type` once its provider is registered, activating/// `onCustomEditor:<viewType>` for it (customEditors.ts).- fn open_custom_editor(&mut self, view_type: String, resource: Value, options: Value, window: &mut Window, cx: &mut Context<Self>) -> Outcome {+ 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 });+ self.webview_panels.custom_editors.pending.push(PendingOpen { view_type, resource, options, reply, diff });self.open_pending_custom_editors(window, cx);Outcome::Pending(receiver)}@@ -647,7 +714,11 @@ impl Workbench {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 {- match self.show_custom_editor(&open.view_type, &open.resource, &open.options, window, cx) {+ 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));}@@ -671,7 +742,7 @@ impl Workbench {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 };+ 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();@@ -715,6 +786,72 @@ impl Workbench {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();@@ -741,12 +878,32 @@ impl Workbench {/// 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)]),+ 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@@ -770,13 +927,38 @@ impl Workbench {/// 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 };+ 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)@@ -786,44 +968,71 @@ impl Workbench {/// 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| self.editors.active().is_some_and(|editor| panel.shows(editor)));+ 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 = Vec::new();+ 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 = self.webview_panels.panels.iter().any(|other| {- other.view_type == panel.view_type && other.custom.as_ref().is_some_and(|other| other.resolved && other.resource == custom.resource)- });- let create = (!provider.text && !document_open).then(|| vec![custom.resource.clone(), json!(panel.view_type), json!(custom.backup_id), Value::Null]);- let init = json!({ "title": panel.title, "contentOptions": {}, "options": provider.options, "active": active == Some(index) });+ 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 resolve = vec![custom.resource.clone(), json!(panel.handle), json!(panel.view_type), init, json!(column)];- let navigate = (provider.text && provider.supports_navigation).then(|| custom.resource.clone());- resolves.push((panel.handle.clone(), panel.view_type.clone(), create, resolve, navigate));+ 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 (handle, view_type, create, resolve, navigate) in resolves {- let document = create.as_ref().map(|args| (args[0].clone(), args[2].is_string()));- let created = create.map(|args| self.host.call("ExtHostCustomEditors", "$createCustomDocument", args));+ 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 result = match created {- Some(created) => created.await.unwrap_or_else(canceled),- None => Ok(Value::Null),- };- if let (Ok(created), Some((resource, from_backup))) = (&result, document) {- let editable = created["editable"] == true;- let view_type = view_type.clone();- let _ = workbench.update(cx, |workbench, cx| workbench.custom_document_created(resource, view_type, editable, from_backup, cx));+ 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", "$resolveCustomEditor", resolve)) {+ Ok(_) => match workbench.update(cx, |workbench, _| workbench.host.call("ExtHostCustomEditors", method, resolve)) {Ok(resolved) => resolved.await.unwrap_or_else(canceled),Err(_) => return,},@@ -845,6 +1054,7 @@ impl Workbench {workbench.apply_custom_editor_options(&handle, &options);let _ = reply.send(Ok(Value::Null));}+ workbench.sync_webview_panels();});}).detach();diff --git a/native/crates/app/src/workbench/editor_type_picker.rs b/native/crates/app/src/workbench/editor_type_picker.rsindex 4dac6716895..669d184937b 100644--- a/native/crates/app/src/workbench/editor_type_picker.rs+++ b/native/crates/app/src/workbench/editor_type_picker.rs@@ -97,7 +97,8 @@ impl Workbench {Some(diff) => {let modified = crate::editor::uri_value(&diff.modified.scheme, &diff.modified.path);let original = crate::editor::uri_value(&diff.original.scheme, &diff.original.path);- (modified.clone(), Some((original, modified)), TEXT_EDITOR_ID.to_owned())+ let current = diff.custom.as_ref().map_or(TEXT_EDITOR_ID, |custom| custom.view_type.as_str());+ (modified.clone(), Some((original, modified)), current.to_owned())}None => {let (resource, current) = self.active_editor_type()?;diff --git a/native/crates/app/src/workbench/editor_view.rs b/native/crates/app/src/workbench/editor_view.rsindex eb899794d56..e03b0014aaf 100644--- a/native/crates/app/src/workbench/editor_view.rs+++ b/native/crates/app/src/workbench/editor_view.rs@@ -128,6 +128,7 @@ impl Workbench {_ => part.child(self.breadcrumbs(self.active_text_editor_control().unwrap_or(editor), cx).opacity(self.unfocused_editor_opacity(window))),}).map(|part| match self.editors.active_diff() {+ Some(crate::diff_editor::DiffInput { custom: Some(custom), .. }) => part.child(self.custom_editor_diff_body(custom.inline, cx)),Some(diff) => part.child(self.diff_editor_body(diff, diff.modified_editor.as_ref().unwrap_or(editor), window, cx)),None if self.playground_active() => part,None if editor.document().scheme == super::modal_editor_group::PREFERENCES_EDITOR_SCHEME => part.children(preferences),@@ -909,7 +910,9 @@ impl Workbench {/// The resource the breadcrumbs show: a custom editor's is its resource's (`EditorResourceAccessor.getOriginalUri`).pub(super) fn breadcrumbs_resource(&self, editor: &OpenEditor, notebook_path: Option<PathBuf>) -> PathBuf {- notebook_path.or_else(|| self.webview_resource(&editor.document().path)).unwrap_or_else(|| editor.document().path.clone())+ // customEditorDiffInput.ts: a custom editor diff's resource is its modified side.+ let custom_diff = self.editors.active_diff().filter(|diff| diff.custom.is_some()).map(|diff| diff.modified.path.clone());+ notebook_path.or(custom_diff).or_else(|| self.webview_resource(&editor.document().path)).unwrap_or_else(|| editor.document().path.clone())}/// breadcrumbsModel.ts `_initFilePathInfo`: the path's items as labels, whether the first is relative to a folder or@@ -3002,8 +3005,14 @@ impl Workbench {/// `getCodeEditor(editorService.activeTextEditorControl)`, which the status bar and breadcrumbs follow: a diff/// editor's modified side, also while its original side has the focus.pub(super) fn active_text_editor_control(&self) -> Option<&OpenEditor> {- if let Some(modified) = self.editors.active_diff().and_then(|diff| diff.modified_editor.as_ref()) {- return Some(modified);+ if let Some(diff) = self.editors.active_diff() {+ // A custom editor diff shows webviews, no code editor.+ if diff.custom.is_some() {+ return None;+ }+ if let Some(modified) = &diff.modified_editor {+ return Some(modified);+ }}// mergeEditor.ts `getControl`: the result's editor, also while an input has the focus.if self.editors.active_merge().is_some() {diff --git a/native/crates/app/src/workbench/editor_view/diff_editor_view.rs b/native/crates/app/src/workbench/editor_view/diff_editor_view.rsindex 1c809406d04..0b76c06e4db 100644--- a/native/crates/app/src/workbench/editor_view/diff_editor_view.rs+++ b/native/crates/app/src/workbench/editor_view/diff_editor_view.rs@@ -15,7 +15,7 @@ use crate::workbench::comment_thread_floating::FloatingHost;use crate::workbench::hover::{HoverContent, HoverOptions};use crate::commands::Outcome;use crate::diff_editor::unchanged_regions::UnchangedRegion;-use crate::diff_editor::{ComputedDiff, DIFF_EDITOR_SCHEME, DiffInput, DiffZone, Side, ZoneContent, ZoneSide, additional_heights, diff_options, range_alignment, view_zones};+use crate::diff_editor::{ComputedDiff, CustomDiff, DIFF_EDITOR_SCHEME, DiffInput, DiffZone, Side, ZoneContent, ZoneSide, additional_heights, diff_options, range_alignment, view_zones};use crate::editor::{OpenEditor, Position, TextDocument, VerticalReveal, expand_tabs, column_x};use crate::notifications::{Action, Notification, Run, Severity};use crate::workbench::host_requests::{selection_range, uri_parts};@@ -165,10 +165,20 @@ impl Workbench {workbench.try_open_document(uri, &Value::Null, &Value::Null, false, cx)?;}}- workbench.show_diff_editor(sides.0, sides.1, label, &options, window, cx);- Ok(Value::Null)+ if let Some(view_type) = workbench.custom_diff_editor_for(&sides.1) {+ return Ok(workbench.open_custom_editor(view_type, modified, Some((sides.0, label)), options, window, cx));+ }+ workbench.show_diff_editor(sides.0, sides.1, label, None, &options, window, cx);+ Ok(Outcome::done())});- drop(sender.send(result.unwrap_or_else(|_| Err(exthost::main_thread::serialized_error("Canceled")))));+ let canceled = || Err(exthost::main_thread::serialized_error("Canceled"));+ let result = match result {+ Ok(Ok(Outcome::Pending(opened))) => opened.await.unwrap_or_else(|_| canceled()),+ Ok(Ok(Outcome::Ready(result))) => result,+ Ok(Err(error)) => Err(error),+ Err(_) => canceled(),+ };+ drop(sender.send(result));}).detach();Outcome::Pending(receiver)@@ -176,15 +186,16 @@ impl Workbench {/// `openEditor` of a `DiffEditorInput`: an open diff editor of the same sides is activated, else a new one/// opens (a preview unless `pinned` or `preview: false`).- pub(in crate::workbench) fn show_diff_editor(&mut self, original: Side, modified: Side, label: Option<String>, options: &Value, window: &mut Window, cx: &mut Context<Self>) {+ pub(in crate::workbench) fn show_diff_editor(&mut self, original: Side, modified: Side, label: Option<String>, custom: Option<CustomDiff>, options: &Value, window: &mut Window, cx: &mut Context<Self>) {self.activate_column(&options["position"], None);- let revealed = self.reveal_group(options, |editor| self.editors.diffs.get(&editor.model_id).is_some_and(|diff| diff.original == original && diff.modified == modified));+ let same = |diff: &DiffInput| diff.original == original && diff.modified == modified && diff.custom == custom;+ let revealed = self.reveal_group(options, |editor| self.editors.diffs.get(&editor.model_id).is_some_and(same));if let Some(group) = revealed {self.activate_group(group);} else if !crate::workbench::editor_groups::explicit_group(&options["position"]) {self.enter_modal_group_for_all(window, cx);}- let existing = self.editors.editors.iter().position(|editor| self.editors.diffs.get(&editor.model_id).is_some_and(|diff| diff.original == original && diff.modified == modified));+ let existing = self.editors.editors.iter().position(|editor| self.editors.diffs.get(&editor.model_id).is_some_and(same));let pinned = options["pinned"] == json!(true) || options["preview"] == json!(false);match existing {Some(index) => {@@ -197,7 +208,7 @@ impl Workbench {let id = self.editors.diffs.len() + self.editors.editors.len() + 1;let entry = TextDocument::from_text(DIFF_EDITOR_SCHEME, Path::new(&format!("/{id}")), "", "utf8".into(), Some("plaintext"), &self.languages, &self.settings.lock().unwrap());self.leave_locked_group(DIFF_EDITOR_SCHEME, &entry.path);- self.editors.open_diff(entry, DiffInput::new(original, modified, label), !pinned);+ self.editors.open_diff(entry, DiffInput { custom, ..DiffInput::new(original, modified, label) }, !pinned);}}self.marked_text = None;@@ -439,18 +450,24 @@ impl Workbench {/// swap sides, whitespace and collapse unchanged regions.pub(in crate::workbench) fn diff_title_actions(&self, cx: &mut Context<Self>) -> Vec<(f64, gpui::Stateful<Div>)> {let Some(input) = self.editors.active_diff() else { return Vec::new() };- let has_changes = input.diff.as_ref().is_some_and(|diff| !diff.diff.changes.is_empty());- let mut actions = vec![- (10., "workbench.action.compareEditor.previousChange", "arrow-up", "Previous Change", has_changes, false),- (11., "workbench.action.compareEditor.nextChange", "arrow-down", "Next Change", has_changes, false),- ];- if self.diff_can_swap(input) {- actions.push((15., "workbench.action.compareEditor.swapSides", "arrow-swap", "Swap Left and Right Side", true, false));+ let mut actions = Vec::new();+ if input.custom.is_some() {+ // editor.contribution.ts Reopen as Text, when `activeCustomEditorTextDiff`.+ if self.active_custom_editor_text_diff() {+ actions.push((16., "workbench.action.reopenTextEditor", "file-code", "Reopen as Text", true, false));+ }+ } else {+ let has_changes = input.diff.as_ref().is_some_and(|diff| !diff.diff.changes.is_empty());+ actions.push((10., "workbench.action.compareEditor.previousChange", "arrow-up", "Previous Change", has_changes, false));+ actions.push((11., "workbench.action.compareEditor.nextChange", "arrow-down", "Next Change", has_changes, false));+ if self.diff_can_swap(input) {+ actions.push((15., "workbench.action.compareEditor.swapSides", "arrow-swap", "Swap Left and Right Side", true, false));+ }+ // editor.contribution.ts: toggled when `config.diffEditor.ignoreTrimWhitespace` is false.+ let shows_whitespace = self.setting("diffEditor.ignoreTrimWhitespace") == json!(false);+ actions.push((20., "toggle.diff.ignoreTrimWhitespace", "whitespace", "Show Leading/Trailing Whitespace Differences", true, shows_whitespace));+ actions.push((22., "diffEditor.toggleCollapseUnchangedRegions", "map", "Toggle Collapse Unchanged Regions", true, false));}- // editor.contribution.ts: toggled when `config.diffEditor.ignoreTrimWhitespace` is false.- let shows_whitespace = self.setting("diffEditor.ignoreTrimWhitespace") == json!(false);- actions.push((20., "toggle.diff.ignoreTrimWhitespace", "whitespace", "Show Leading/Trailing Whitespace Differences", true, shows_whitespace));- actions.push((22., "diffEditor.toggleCollapseUnchangedRegions", "map", "Toggle Collapse Unchanged Regions", true, false));let icon_color = self.color("icon.foreground");let disabled_color = self.color("disabledForeground");// editorGroupView.ts `highlightToggledItems`: a checked action label gets `actionBar.toggledBackground`.@@ -480,6 +497,12 @@ impl Workbench {/// editor's own `isInDiffEditor`).pub(in crate::workbench) fn insert_diff_editor_context(&self, context: &mut std::collections::HashMap<String, Value>) {let Some(input) = self.editors.active_diff() else { return };+ if let Some(custom) = &input.custom {+ // webviewEditor.ts `WebviewEditor.ID`, sideBySideEditor.ts `SideBySideEditor.ID`.+ context.insert("activeEditor".into(), json!(if custom.inline { "WebviewEditor" } else { "workbench.editor.sidebysideEditor" }));+ context.insert("activeCustomEditorTextDiff".into(), json!(self.active_custom_editor_text_diff()));+ return;+ }context.insert("activeEditor".into(), json!("workbench.editors.textDiffEditor"));context.insert("textCompareEditorActive".into(), json!(true));context.insert("textCompareEditorVisible".into(), json!(true));diff --git a/native/crates/app/src/workbench/keybindings_editor_view.rs b/native/crates/app/src/workbench/keybindings_editor_view.rsindex 1a6c11c1ff6..19d3e17a595 100644--- a/native/crates/app/src/workbench/keybindings_editor_view.rs+++ b/native/crates/app/src/workbench/keybindings_editor_view.rs@@ -939,7 +939,7 @@ impl Workbench {let editor_height = height - 2. - MODAL_HEADER_HEIGHT - 1.;let editor = editor(self, width - 2., editor_height, window, cx);// The editor actions see the context of the modal group's text editor. editor.contribution.ts- // `enableInModalMode`: of the built-in editor title actions only a diff's Previous and Next Change.+ // `enableInModalMode`: of the built-in editor title actions only a diff's Previous and Next Change and Reopen as Text.let (context, diff_actions) = match header.resource {Some(_) => self.with_group(crate::editor::MODAL_GROUP, |workbench| (workbench.key_context(window), workbench.diff_title_actions(cx))),None => (self.key_context(window), Vec::new()),@@ -948,6 +948,7 @@ impl Workbench {let (title, command) = match order {10. => ("Previous Change", "workbench.action.compareEditor.previousChange"),11. => ("Next Change", "workbench.action.compareEditor.nextChange"),+ 16. => ("Reopen as Text", "workbench.action.reopenTextEditor"),_ => return None,};Some((order, title.to_string(), action.debug_selector(move || format!("modal-editor-action-{command}"))))diff --git a/native/crates/app/src/workbench/keyboard.rs b/native/crates/app/src/workbench/keyboard.rsindex d92c3d3a9f9..20e637f823e 100644--- a/native/crates/app/src/workbench/keyboard.rs+++ b/native/crates/app/src/workbench/keyboard.rs@@ -560,7 +560,10 @@ impl Workbench {context.insert("editorTabMovesFocus".into(), json!(self.tab_focus_mode()));context.insert("editorColumnSelection".into(), self.setting("editor.columnSelection"));context.insert("foldingEnabled".into(), self.setting("editor.folding"));- context.insert("editorLangId".into(), json!(editor.document().language_id));+ // A custom editor diff has no code editor.+ if self.editors.active_diff().is_none_or(|diff| diff.custom.is_none()) {+ context.insert("editorLangId".into(), json!(editor.document().language_id));+ }// ResourceContextKey follows the editor input, not a focused comment editor in it.let resource = self.editors.pane_editor().expect("an active editor is in a pane").document();context.insert("resourceLangId".into(), json!(resource.language_id));diff --git a/native/crates/app/src/workbench/language_status/tests.rs b/native/crates/app/src/workbench/language_status/tests.rsindex abd0ad2f629..be2bec20a4b 100644--- a/native/crates/app/src/workbench/language_status/tests.rs+++ b/native/crates/app/src/workbench/language_status/tests.rs@@ -234,7 +234,7 @@ fn a_diff_editor_reports_the_limit_of_its_modified_side(cx: &mut TestAppContext)std::fs::write(&path, "other\n").unwrap();workbench.open_file(path, true, window, cx);let modified = active(workbench);- workbench.show_diff_editor(original.0, modified.0, None, &Value::Null, window, cx);+ workbench.show_diff_editor(original.0, modified.0, None, None, &Value::Null, window, cx);(original.1, modified.1)});change_markers(&workbench, cx, &original, 5001);diff --git a/native/crates/app/src/workbench/media_preview.rs b/native/crates/app/src/workbench/media_preview.rsindex f7d2f543be9..3c48288d7bb 100644--- a/native/crates/app/src/workbench/media_preview.rs+++ b/native/crates/app/src/workbench/media_preview.rs@@ -121,7 +121,7 @@ impl Workbench {let roots = json!({ "enableScripts": true, "localResourceRoots": [{ "scheme": root.scheme, "authority": root.authority, "path": root.path }] });// mediaPlayerEditorInput.ts keeps the webview while hidden, so playback goes on.let retain = kind != MediaKind::Image;- let custom = Some(CustomEditor { resource: resource.clone(), resolved: true, backup_id: None, navigation: super::custom_editors::Navigation::None });+ let custom = Some(CustomEditor { resource: resource.clone(), resolved: true, backup_id: None, navigation: super::custom_editors::Navigation::None, diff: None });let mut panel = WebviewPanel::new(handle.clone(), WEBVIEW_PANEL_SCHEME.into(), placeholder, view_type, title, &Value::Null, roots, retain, custom);let media = MediaPreview { kind, resource: media_resource.clone(), file_size: None, git_lfs: false, scale: Value::Null, dimensions: None, view_state: Value::Null };panel.media = Some(media);diff --git a/native/crates/app/src/workbench/modal_editor_group.rs b/native/crates/app/src/workbench/modal_editor_group.rsindex 1c75bf669ca..e528821417c 100644--- a/native/crates/app/src/workbench/modal_editor_group.rs+++ b/native/crates/app/src/workbench/modal_editor_group.rs@@ -250,7 +250,8 @@ impl Workbench {};}let (resource, (json_title, json_command, json_args), uri) = self.with_group(MODAL_GROUP, |workbench| {- let editor = workbench.editors.active().expect("an open modal group has an active editor");+ // 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())});@@ -258,6 +259,9 @@ impl Workbench {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.diff --git a/native/crates/app/src/workbench/outline_pane.rs b/native/crates/app/src/workbench/outline_pane.rsindex 2b0bb4730c7..46cd7ba7fa7 100644--- a/native/crates/app/src/workbench/outline_pane.rs+++ b/native/crates/app/src/workbench/outline_pane.rs@@ -375,7 +375,9 @@ impl Workbench {fn breadcrumb_outline_path(&self, editor: &crate::editor::OpenEditor) -> Option<(Vec<&crate::outline_model::OutlineElement>, bool)> {let Status::Ready { model_id, outline, .. } = &self.outline_pane.status else { return None };let symbol_path = self.setting("breadcrumbs.symbolPath");- if *model_id != editor.model_id || symbol_path == "off" {+ // A custom editor diff has no code editor to outline.+ let custom_diff = self.editors.active_diff().is_some_and(|diff| diff.custom.is_some());+ if *model_id != editor.model_id || symbol_path == "off" || custom_diff {return None;}let position = self.outline_position(editor)?;diff --git a/native/crates/app/src/workbench/refactor_preview.rs b/native/crates/app/src/workbench/refactor_preview.rsindex 54a212206c4..959968b4c02 100644--- a/native/crates/app/src/workbench/refactor_preview.rs+++ b/native/crates/app/src/workbench/refactor_preview.rs@@ -427,7 +427,7 @@ impl Workbench {let original = Side { scheme, path: path.clone() };let modified = Side { scheme: PREVIEW_SCHEME.into(), path };let label = format!("{} (Refactor Preview)", original.name());- self.show_diff_editor(original, modified, Some(label), &json!({ "preserveFocus": true, "selection": selection }), window, cx);+ self.show_diff_editor(original, modified, Some(label), None, &json!({ "preserveFocus": true, "selection": selection }), window, cx);}/// The preview model of `path` with `text`: created once, then replaced whole on each open.diff --git a/native/crates/app/src/workbench/search_editor_view.rs b/native/crates/app/src/workbench/search_editor_view.rsindex fdade6ce542..6d12b261a94 100644--- a/native/crates/app/src/workbench/search_editor_view.rs+++ b/native/crates/app/src/workbench/search_editor_view.rs@@ -144,8 +144,8 @@ impl Workbench {_ => "Keyboard Shortcuts".into(),},None => super::preferences::editor_label(&editor.document())- .or_else(|| self.webview_title(&editor.document().path)).or_else(|| self.diff_name(editor))+ .or_else(|| self.webview_title(&editor.document().path)).or_else(|| editor.text_model().preferred_name.clone()).unwrap_or_else(|| editor.document().name()),}diff --git a/native/crates/app/src/workbench/side_by_side_editor.rs b/native/crates/app/src/workbench/side_by_side_editor.rsindex 2d217c3430d..7ed4355ea80 100644--- a/native/crates/app/src/workbench/side_by_side_editor.rs+++ b/native/crates/app/src/workbench/side_by_side_editor.rs@@ -127,6 +127,13 @@ impl Workbench {/// sash between them moves; the primary side draws the border (`sideBySideEditor.verticalBorder` left to right,/// `.horizontalBorder` top to bottom) inside its size.pub(super) fn side_by_side_body(&self, secondary: AnyElement, primary: &OpenEditor, window: &mut Window, cx: &mut Context<Self>) -> Div {+ let primary = div().flex_1().min_h_0().flex().flex_col().children(self.unicode_banner(primary, cx)).child(self.text_area(primary, window, cx).opacity(self.unfocused_editor_opacity(window)));+ self.side_by_side_split(secondary, primary.into_any_element(), cx)+ }++ /// The split of a side by side editor's sides; a custom editor diff's webviews are its sides too+ /// (binaryDiffEditor.ts `BinaryResourceDiffEditor` is a `SideBySideEditor`).+ pub(super) fn side_by_side_split(&self, secondary: AnyElement, primary: AnyElement, cx: &mut Context<Self>) -> Div {let vertical = self.setting("workbench.editor.splitInGroupLayout") == json!("vertical");let entry = self.editors.active_tab().expect("a side by side editor is the active tab").model_id;let sizes = self.side_by_side_splits.sizes.clone();@@ -144,8 +151,7 @@ impl Workbench {false => primary.border_l_1(),}).border_color(border)- .children(self.unicode_banner(primary, cx))- .child(self.text_area(primary, window, cx).opacity(self.unfocused_editor_opacity(window)));+ .child(primary);let ratio = self.side_by_side_splits.ratios.get(&entry).copied().unwrap_or(0.5);let secondary = div().flex_none().min_w_0().min_h_0().flex().flex_col().child(secondary);let secondary = match vertical {diff --git a/native/crates/app/src/workbench/webview_panels.rs b/native/crates/app/src/workbench/webview_panels.rsindex a22cf71ce2e..f49819cc3de 100644--- a/native/crates/app/src/workbench/webview_panels.rs+++ b/native/crates/app/src/workbench/webview_panels.rs@@ -599,21 +599,18 @@ impl Workbench {std::mem::take(&mut self.webview_panels.panels).into_iter().partition(|panel| panel.scheme == WEBVIEW_VIEW_SCHEME || group_editors.clone().any(|editor| panel.shows(editor)));self.webview_panels.panels = open;self.release_hidden_webview_panels();- for panel in closed.into_iter().filter(|panel| panel.is_extensions()) {+ let closed: Vec<WebviewPanel> = closed.into_iter().filter(|panel| panel.is_extensions()).collect();+ for panel in &closed {self.host.send("ExtHostWebviewPanels", "$onDidDisposeWebviewPanel", vec![json!(panel.handle)]);- // The custom document's last editor closed: its model reference is released.- let Some(custom) = panel.custom.filter(|custom| custom.resolved && panel.scheme == WEBVIEW_PANEL_SCHEME) else { continue };- let open = self.webview_panels.panels.iter().any(|other| other.view_type == panel.view_type && other.custom.as_ref().is_some_and(|other| other.resource == custom.resource));- if !open {- self.custom_document_disposed(&custom.resource, &panel.view_type);- self.host.send("ExtHostCustomEditors", "$disposeCustomDocument", vec![custom.resource, json!(panel.view_type)]);- }}+ // The custom document's last editor closed: its model reference is released.+ self.release_custom_documents(closed);self.host.webview_tabs = self.webview_panels.panels.iter()- .filter(|panel| panel.scheme != WEBVIEW_VIEW_SCHEME)+ // A diff's webviews show in the diff editor's tab, which tells the host its own input.+ .filter(|panel| panel.scheme != WEBVIEW_VIEW_SCHEME && panel.custom.as_ref().is_none_or(|custom| custom.diff.is_none())).map(|panel| {let tab = match &panel.custom {Some(custom) => WebviewTab {@@ -630,6 +627,14 @@ impl Workbench {(panel.path.clone(), tab)}).collect();+ // The editor becomes active once its custom editor resolved (editorGroupView.ts awaits `setInput`): the+ // host hears the view states after the resolve, which syncs again. A custom diff tab shown before its webviews+ // were sent to resolve waits too.+ let unresolved = |tab: &OpenEditor| !self.webview_panels.panels.iter().any(|panel| panel.shows(tab) && panel.custom.as_ref().is_some_and(|custom| custom.resolved));+ let custom_diff_opening = self.editors.active_tab().is_some_and(|tab| self.editors.diffs.get(&tab.model_id).is_some_and(|diff| diff.custom.is_some()) && unresolved(tab));+ if !self.webview_panels.custom_editors.opening.is_empty() || custom_diff_opening {+ return;+ }let states = Value::Object(self.webview_panel_view_states());if states.as_object().is_some_and(serde_json::Map::is_empty) || states == self.webview_panels.view_states {return;@@ -646,9 +651,10 @@ impl Workbench {for (column, group) in self.groups_in_grid_order().into_iter().enumerate() {let (editors, active_index) = self.editors.group_tabs(group);for (index, editor) in editors.iter().enumerate() {- let Some(panel) = self.webview_panels.panels.iter().find(|panel| panel.scheme != WEBVIEW_VIEW_SCHEME && panel.is_extensions() && panel.shows(editor)) else { continue };let visible = active_index == Some(index);- states.insert(panel.handle.clone(), json!({ "visible": visible, "active": visible && group == active_group, "position": column }));+ for panel in self.webview_panels.panels.iter().filter(|panel| panel.scheme != WEBVIEW_VIEW_SCHEME && panel.is_extensions() && panel.shows(editor)) {+ states.insert(panel.handle.clone(), json!({ "visible": visible, "active": visible && group == active_group && !panel.is_diff_side(), "position": column }));+ }}}states@@ -828,13 +834,19 @@ impl WebviewPanel {self.media.is_none() && self.carousel.is_none()}+ /// One side of a side by side custom editor diff: the diff, not this webview, is the active editor.+ pub(super) fn is_diff_side(&self) -> bool {+ self.custom.as_ref().and_then(|custom| custom.diff.as_ref()).is_some_and(|part| part.side != super::custom_editors::DiffSide::Inline)+ }+pub(super) fn shows(&self, editor: &OpenEditor) -> bool {self.covers(&(editor.document().scheme.clone(), editor.document().path.clone(), editor.model_id))}/// Whether the panel shows over the tab of this scheme, path and model id.fn covers(&self, (scheme, path, model_id): &(String, PathBuf, u32)) -> bool {- self.scheme == *scheme && self.path == *path && self.editor.is_none_or(|editor| editor == *model_id)+ let tab = self.custom.as_ref().and_then(|custom| custom.diff.as_ref()).map(|part| part.tab);+ self.scheme == *scheme && self.path == *path && self.editor.or(tab).is_none_or(|editor| editor == *model_id)}/// webviewElement.ts `doUpdateContent`.diff --git a/port/fixtures/custom-editor-diff/steps.json b/port/fixtures/custom-editor-diff/steps.jsonnew file mode 100644index 00000000000..5d54cd16c6c--- /dev/null+++ b/port/fixtures/custom-editor-diff/steps.json@@ -0,0 +1,13 @@+[+ { "wait": 6000 },+ { "hotkey": ["cmd", "shift", "p"], "foreground": true }, { "wait": 800 },+ { "type": "Compare Active File With...", "foreground": true }, { "wait": 1000 },+ { "key": "return", "foreground": true }, { "wait": 1500 },+ { "type": "guide.md", "foreground": true }, { "wait": 1500 },+ { "key": "return", "foreground": true }, { "wait": 4000 },+ { "shot": "custom" },+ { "hotkey": ["cmd", "shift", "p"], "foreground": true }, { "wait": 800 },+ { "type": "Reopen Editor with Text Editor", "foreground": true }, { "wait": 1000 },+ { "key": "return", "foreground": true }, { "wait": 2500 },+ { "shot": "text" }+]diff --git a/port/fixtures/extensions/markdown-tests/tests/index.js b/port/fixtures/extensions/markdown-tests/tests/index.jsindex 578badc3d7b..58c62461aaa 100644--- a/port/fixtures/extensions/markdown-tests/tests/index.js+++ b/port/fixtures/extensions/markdown-tests/tests/index.js@@ -68,8 +68,56 @@ const checks = {});assert.strictEqual(tab.input.uri.toString(), readme().toString());},++ async 'a diff associated with the preview opens side by side'() {+ await openPreviewDiff(true);+ const tab = await until('the preview diff tab', () => {+ const tab = activeTab();+ return tab?.label.includes('CHANGES') && tab;+ });+ assert.strictEqual(describe(tab), 'unknown README.md ↔ CHANGES.md');+ },++ async 'a diff associated with the preview opens inline'() {+ await openPreviewDiff(false);+ const tab = await until('the preview diff tab', () => {+ const tab = activeTab();+ return tab?.label.includes('CHANGES') && tab;+ });+ assert.strictEqual(describe(tab), 'webview vscode.markdown.preview.editor README.md - CHANGES.md');+ },++ async 'reopenTextEditor turns the preview diff into the text diff'() {+ await openPreviewDiff(true);+ await until('the preview diff tab', () => activeTab()?.label.includes('CHANGES'));+ await vscode.commands.executeCommand('workbench.action.reopenTextEditor');+ const tab = await until('the text diff tab', () => {+ const tab = activeTab();+ return tab?.input instanceof vscode.TabInputTextDiff && tab;+ });+ assert.strictEqual(describe(tab), 'textDiff README.md ↔ CHANGES.md');+ },};+const changes = () => vscode.Uri.joinPath(vscode.workspace.workspaceFolders[0].uri, 'CHANGES.md');++function describe(tab) {+ const input = tab.input;+ const kind = input instanceof vscode.TabInputTextDiff ? 'textDiff'+ : input instanceof vscode.TabInputWebview ? `webview ${input.viewType}`+ : input instanceof vscode.TabInputCustom ? `custom ${input.viewType}`+ : input instanceof vscode.TabInputText ? 'text' : 'unknown';+ return `${kind} ${tab.label}`;+}++// customEditors.ts `getDiffEditorLayout`: the preview supports both layouts, `diffEditor.renderSideBySide` picks one.+async function openPreviewDiff(sideBySide) {+ await vscode.workspace.fs.writeFile(changes(), new TextEncoder().encode('# Changes\n\nOne more line.\n'));+ await vscode.workspace.getConfiguration('workbench').update('diffEditorAssociations', { '*.md': 'vscode.markdown.preview.editor' }, vscode.ConfigurationTarget.Global);+ await vscode.workspace.getConfiguration('diffEditor').update('renderSideBySide', sideBySide, vscode.ConfigurationTarget.Global);+ await vscode.commands.executeCommand('vscode.diff', readme(), changes());+}+exports.run = async () => {const only = process.env.PORT_WEBVIEW_GREP;let failed = 0;diff --git a/port/ledger.md b/port/ledger.mdindex af30f339851..49da900f5b3 100644--- a/port/ledger.md+++ b/port/ledger.md@@ -31,7 +31,7 @@ Status: `open`, `in progress`, `waiting on Artur`, `later` (postponed), `done`,| Milestones | M14 source control and diff | done | SCM view and input box, quick diff gutter, the diff editor (side by side and inline), multi-file diff, merge editor and merge-conflict decorations, timeline, the git, git-base and github extensions fully working (no sign-in: github features that need a token stay off). Open gaps: the gaps column of its unit rows. | api-tests SCM cases pass as in the reference; with the fixture copied into a git repository the SCM view lists a changed file and opening it shows the diff (pixel-check window). || Milestones | M15 terminal, tasks, output | done | Integrated terminal (PTY from Rust, VT parser and renderer in GPUI), shell integration, extension terminals and pseudoterminals, tasks and problem matchers, npm/grunt/gulp/jake task providers, external terminal, Output panel and log viewer. Open gaps: the gaps column of its unit rows. | api-tests `terminal.test`, `terminal.shellIntegration.test` and `workspace.tasks.test` pass as in the reference (run with `SHELL=/bin/bash` as the baseline was); `npm: build` task from the fixture runs in a terminal. || Milestones | M16 debug and testing | in progress | Debug adapter protocol client, launch.json, breakpoints in the gutter, call stack, variables, watch, debug console, JS debugger (`ms-vscode.js-debug`), Test Explorer and test results. Open gaps: the gaps column of its unit rows. | api-tests `debug.test` and testing cases pass as in the reference; a breakpoint in a Node script from the fixture stops and shows variables. |-| Milestones | M17 webviews and notebooks | in progress | A WKWebView embedded in the GPUI window for webview panels, webview views and custom editors, with the upstream message and resource protocol; Markdown preview, image/media preview, simple browser, editor insets; notebooks (ipynb) with renderers and kernels. Open gaps: the gaps column of its unit rows. | api-tests `webview.test`, `customEditor` and `notebook*.test` cases pass as in the reference; Markdown preview of the fixture README draws next to its source. |+| Milestones | M17 webviews and notebooks | done | A WKWebView embedded in the GPUI window for webview panels, webview views and custom editors, with the upstream message and resource protocol; Markdown preview, image/media preview, simple browser, editor insets; notebooks (ipynb) with renderers and kernels. Open gaps: the gaps column of its unit rows. | api-tests `webview.test`, `customEditor` and `notebook*.test` cases pass as in the reference; Markdown preview of the fixture README draws next to its source. || Milestones | M18 extensions: install, update, gallery | done | Extensions view backed by Open VSX, install/uninstall/update/disable, VSIX install, signature and checksum checks, recommendations, ESM extensions added after startup on Bun, language packs and display language. | Installing an extension from Open VSX activates it without restart (an ESM one included); api-tests `extensions.test` pass as in the reference. PORT_GALLERY=1 port/tools/extensions-check: 6 ok; MOCHA_GREP="vscode server cli" port/tools/api-tests: its one test pending, as in the reference (remote only). || Milestones | M19 product shell, privacy, accessibility, release | done | Welcome page and walkthroughs, update channel for the port's own builds, relaunch, splash, accessibility (VoiceOver through GPUI's accessibility tree, accessibility signals, high-contrast checks), process explorer and performance views, telemetry inert end to end, packaged and signed `.app`. Open gaps: the gaps column of its unit rows. | The telemetry source search (no telemetry endpoint string reachable) and network capture (zero outbound requests in a 10 min session with no user action) pass; VoiceOver reads the editor line and the Explorer rows; the signed `.app` passes `spctl -a`; benchmark rerun against a packaged reference build. || Milestones | M20 parity | in progress | Nothing new; close the gaps the earlier milestones left (the gaps column of the unit rows). Completion check in port-m20-check: api-tests met (318/28/0 in the target's suites, 4/0/0, port/results/api-tests.md); pixel-check met, the remaining differences are the causes in port/results/pixels.md; ledger not met: the `ported` rows, each with its open gaps. Closed in workbench/contrib/comments: comment threads in diff and multi diff editors, floating ones included, with the floating style's `FloatingWidgetRoom`. | `port/tools/api-tests` gives 318/28/0 (folder) and 4/0/0 (workspace): the reference baseline 356/46/0 less the suites and tests of removed features (chat, lm, the integrated browser, `env.remoteName`) (port/results/api-tests-reference.md); pixel-check of every window has no difference beyond anti-aliasing and the causes listed in `port/results/pixels.md`; every ledger row is `verified`, `removed` or `n/a`. |@@ -529,7 +529,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston| workbench/contrib/codeEditor | workbench contribution | M8 | verified | | workbench/editor_commands.rs, workbench/code_actions/on_save.rs, workbench/large_file.rs, editor/word_wrap.rs, workbench/inspect_tokens.rs, workbench/accessible_view.rs, workbench/quick_access/goto_symbol.rs, workbench/outline_pane.rs, workbench/empty_editor_hint.rs, workbench/empty_editor_hint/actions.rs, workbench/editor_view/diff_editor_view.rs, workbench/configuration_migration.rs: cargo test -p app column_selection_mode multi_cursor_modifier save_participants code_actions a_window_focus_change_runs_the_always_code_actions_on_save overtype_mode large_file the_line_number_menu word_wrap inspect_tokens a_semantic_token_adds_its_table_and_strikes_the_textmate_rule_it_overrides a_line_past_the_tokenization_limit_is_tokenized_for_the_inspector goto_symbol outline_pane empty_editor_hint a_whitespace_only_diff_offers_to_show_whitespace a_diff_stopped_early_offers_to_remove_the_limit configuration_migration the_actions_hint_offers_the_last_picked_editor_first_and_escape_closes_it the_list_fits_the_editor_or_gives_way_to_the_classic_hint; ui-pair notes.txt, wrap.ts, port/fixtures/ui-steps/empty-editor-hint.json, port/fixtures/diff-whitespace/steps.json. Removed by decision: dictation and voice (AI), diffEditorTryout, startDebugTextMate, menuPreventer and selectionClipboard (Linux), displayChangeRemeasureFonts and sleepResumeRepaintMinimap (Electron) || workbench/contrib/commands | workbench contribution | M9 | verified | | runCommands (commands.rs register_run_commands): cargo test -p app commands::, argument checks, spread args, order, stop at a failure; argument errors and the failure notify (cargo test -p app run_commands_argument_errors_notify) || workbench/contrib/comments | workbench contribution | M13 | verified | | workbench/comments_view.rs, workbench/comment_thread_widget.rs, comment_thread_floating.rs, workbench/comment_thread_floating_layout.rs, workbench/comment_node.rs, workbench/commenting_ranges.rs, workbench/comment_navigation.rs, workbench/editor_view/comment_glyph.rs, multi_diff_editor_view.rs: cargo test -p app comment diff floating room multi_diff comment_thread_floating two_threads_keep_their_reply_forms_open_together a_wrapped_comment_body_grows_its_zone the_reached_thread_takes_the_focus a_markdown_comment_previews_its_first_rendered_block the_filter_keeps_its_history_and_escape_clears_it the_thread_menu_replies_to_the_thread a_comment_s_code_span_draws_no_code_block_background additional_actions_show_under_the_body_and_run_with_the_thread a_commenting_range_is_reached_at_its_columns_unless_it_holds_the_cursor dismissing_a_new_template_keeps_it_open an_expanded_thread_shows_a_zone_and_replies_run_the_form_actions a_comment_switched_to_editing_runs_the_edit_actions rows_sit_in_the_pane_s_inset_with_the_tree_s_indent_and_guides (commentThreadFloatingWidget.test.ts); ui-pair `portComments.openDiff` (modified, original, multi, floating), steps-comment-floating.json, steps-comment-additional.json, steps-comment-escape-typed.json, steps-comment-reply-editor.json, steps-comments.json (port/results/language-features.md Comments, Comment editing and commands, Floating comment threads); cargo test -p app reactions_are_action_items_4px_apart |-| workbench/contrib/customEditor | workbench contribution | M17 | ported | [3 L] custom_editors.rs: a diff always opens in the text diff editor, where customEditors.ts `createDiffEditorInput` opens a diff of resources matching an editor's selector (`workbench.diffEditorAssociations`, `priority.diffEditor`) as a `CustomEditorDiffInput` (customEditorDiffInput.ts, inline) or a `DiffEditorInput` of two `CustomEditorSideBySideDiffInput`s or `CustomEditorInput`s, with the proposed `customEditorDiffs` capabilities (`supportsInlineDiff`, `supportsSideBySideDiff`, used by markdown-language-features' preview); so `activeCustomEditorTextDiff` (contextkeys.ts) is never set and Reopen as Text (editor.contribution.ts `ReOpenInTextEditorAction`, `enableInModalMode`) is missing from the editor title and the modal header | cargo test -p app custom_editors each_group_s_custom_text_editor_has_its_own_webview a_custom_text_editor_s_navigation_drives_the_outline a_custom_document_open_in_another_group_moves_to_the_active_one a_custom_document_with_multiple_editors_opens_one_more_in_the_active_group a_workspace_association_wins_over_a_user_one_of_the_same_length a_reopened_preview_keeps_its_tab_position two_default_editors_for_a_resource_ask_once_which_to_keep markdown_editor_files_offer; `FIXTURE=custom-editor-tests port/tools/webview-check` 8/8 |+| workbench/contrib/customEditor | workbench contribution | M17 | verified | | cargo test -p app custom_editors each_group_s_custom_text_editor_has_its_own_webview a_custom_text_editor_s_navigation_drives_the_outline a_custom_document_open_in_another_group_moves_to_the_active_one a_custom_document_with_multiple_editors_opens_one_more_in_the_active_group a_workspace_association_wins_over_a_user_one_of_the_same_length a_reopened_preview_keeps_its_tab_position two_default_editors_for_a_resource_ask_once_which_to_keep markdown_editor_files_offer; `FIXTURE=custom-editor-tests port/tools/webview-check` 8/8; custom editor diffs: cargo test -p app reopen_as_text_turns_an_inline_custom_diff_into_the_text_diff the_modal_header_of_a_custom_diff_offers_reopen_as_text; `FIXTURE=markdown-tests port/tools/webview-check` 8/8 (side by side, inline, reopenTextEditor); ui-pair port/fixtures/custom-editor-diff/steps.json with FILE=README.md and the `*.md` association to `vscode.markdown.preview.editor` || workbench/contrib/debug | workbench contribution | M16 | ported | [3 M] variable_menu.rs: no View Binary Data: debug.contribution.ts registers it only in the rows' `inline` group, and the port's Variables, Watch and hover rows have no inline action bar, no `vscode-debug-memory` file system and no hex editor install prompt (variablesView.ts `VIEW_MEMORY_ID`) | cargo test -p app debug launch_picker_shrinks the_debug_container_more_actions debug_service a_workbench_hover_draws_over_the_debug_hover the_tree_height_keeps_an_above_hover_off_the_hovered_line watch_expression_labels_use_the_monospace_font debug_view debug_task_runner debug_commands debug_console debug::ansi an_ended_session_stays_in_the_picker_until_cleared_or_started_again a_start_or_restart_saves_the_dirty_editors a_hit_breakpoint_enables_its_dependents debug_inline_values debug_hover alt_click_toggles_the_loaded_subtree a_click_on_a_hover_row_focuses_the_tree a_lazy_row_takes_its_value_from_the_eye_button the_find_widget_filters_the_hover_tree disassembly list_tree a_step_in_the_disassembly_view debug::tests::instruction_breakpoints debug::tests::remove_instruction_breakpoints a_right_clicked_call_stack_row_takes_the_list_focus the_debug_toolbar_and_create_configuration_menus_take_contributed_items debug_toolbar variable_menu a_stop_on_a_line_in_view_keeps_the_scroll the_debug_picker_lists_and_starts_the_launch_configurations the_first_scope_expands_only_once_the_variables_view_exists the_find_widget_filters_the_console a_variable_row_draws_its_scopes_indent_guide a_top_frame_past_column_1_injects_the_column_arrow the_call_stack_selects_the_focused_frame_only_after_a_focus_change_it_saw a_visualized_child_shows_its_tree_in_the_hover a_watch_expressions_visualized_child_draws_its_tree a_dynamic_selection_keeps_its_type_for_f5 inline_breakpoints; ui-pair port/fixtures/debug-node (breakpoint, F5, views, REPL, toolbar, `greeting` and `numbers` hovers), menus/view-container-title.json, port/fixtures/ui-pair/debug/hover-find.json, port/fixtures/ui-pair/debug/unverified-breakpoints.json, port/fixtures/ui-pair/debug/call-stack-menu.json, port/fixtures/ui-pair/debug/toolbar.json, port/fixtures/ui-pair/debug/variables-menu.json, port/fixtures/ui-pair/debug/lazy-variable.json, port/fixtures/ui-pair/debug/quick-access.json; shortcuts in port/notes.md || workbench/contrib/dropOrPasteInto | workbench contribution | M13 | verified | | commands.ts `configurePreferredPasteAction`/`configurePreferredDropAction`: the widgets' menus and the Paste As pick open user settings JSON at `editor.pasteAs.preferences` or `editor.dropIntoEditor.preferences` (workbench/paste_edits.rs); the `editor.pasteAs.*` and `editor.dropIntoEditor.*` settings come from core-settings.json; ui-pair paste-menu (port/results/language-features.md) || workbench/contrib/editSessions | workbench contribution | | removed | | no sign-in/AI by decision (port/notes.md); not ported |diff --git a/port/notes.md b/port/notes.mdindex d99276fa4ce..3451309f840 100644--- a/port/notes.md+++ b/port/notes.md@@ -764,6 +764,7 @@ Scope (milestone 18): extension management on disk with VSIX install and uninsta- Quick diff peek body (quickDiffWidget.ts `_fillBody`): a code editor of the file's own model (`EditorGroup.peek_editors`, `PeekOwner::QuickDiff`) with the inline diff's deleted lines as its view zones and the original's line numbers beside it, `lineDecorationsWidth` 10, no indicators and no sticky scroll; typing in it edits the file, `toggleQuickDiffWidgetFocus` (Cmd+K F2) moves the focus in and out. ui-pair m14/quick-diff-peek.json on a git folder whose `a.txt` (30 lines) has line 10 changed and line 12 deleted matches, the outer cursor's `LINE` word highlight and its scrollbar mark in the embedded editor included: wordHighlighter.ts `renderDecorations` decorates every code editor of the model (document_highlights.rs `share_highlights_with_model_editors`).- Custom editors (`workbench/custom_editors.rs`, mainThreadCustomEditors.ts, contrib/customEditor, editorResolverService.ts): providers by view type, `onCustomEditor:` activation with the open waiting for the provider, the default editor from `workbench.editorAssociations` (longest glob) then contributed priorities ranked against the text editor (`priorityToRank`, `builtin` only for built-in extensions), `vscode.open`/`vscode.openWith`, files opened from the Explorer and quick open. A custom text editor keeps the text model as its tab (CustomEditorInput, tab kind 6): saving, dirty state, moves (`$onMoveCustomEditor`) and undo/redo (customEditors.ts implementation, priority 105) are the model's. A custom document's tab is a `webview-panel` editor; `$disposeCustomDocument` when its last editor closes. `workbench.action.reopenWithEditor` and `reopenActiveEditorWith` (openWithEditorPicker.ts: Active/Default descriptions, "Configure default editor for '*.ext'..." writing the association). Shortcuts: custom document edits, `$undo`/`$redo`, save-as, revert and backups are not ported; a reopened custom document opens where the group opens editors.+- Custom editor diffs (customEditors.ts `createDiffEditorInput`, customEditorDiffInput.ts, proposed `customEditorDiffs`): a diff whose modified side opens with a custom editor (`workbench.diffEditorAssociations`, `priority.diffEditor`; media and notebook editors excluded) is a `DiffInput` with `custom`. Inline (`supportsInlineDiff`, or both capabilities and `diffEditor.renderSideBySide` false): one webview from `$resolveCustomEditorInlineDiff`, named `a - b`, tab kind 7 `workbench.editors.customDiffEditor`. Side by side: one webview per side from `$resolveCustomEditorSideBySideDiff`, drawn with the side by side editor's split and border, tab kind 0 as upstream's `DiffEditorInput` of two custom inputs; a provider without diff capabilities gets a plain custom editor per side. Both sides report view states, a side is never `active`, and the host's active text editor is none while a custom diff is active. Reopen as Text (`workbench.action.reopenTextEditor`, order 16, also in the modal header) and Reopen Editor With switch between it and the text diff in place; Split Editor copies both side webviews.- Webview views (`workbench/webview_views.rs`, mainThreadWebviewViews.ts, webviewViewPane.ts): `contributes.views` entries of `type: webview` are contributed views like the tree views (`tree_view.rs` `ContributedView.webview`), so they take the same containers, `when`, visibility, pane layout, Views submenu and `<id>.focus` command; their pane draws the webview where a tree view draws its tree. Collapsed at first in the Explorer, SCM and Debug (viewsExtensionPoint.ts `showCollapsed`); a pane whose body shows activates `onView:<id>` and sends `$resolveWebviewView` once the provider registered; `<id>.focus` and `$show` open the view's container and expand it; `$setWebviewViewBadge` badges the view's container; the webview state is the `webviewView.<id>` memento.- Media preview (`workbench/media_preview.rs`, contrib/mediaPreview): image, video and audio files open in built-in editors (view types `imagePreview.previewEditor`, `vscode.videoPreview`, `vscode.audioPreview`, priority builtin), each a webview panel without an extension loading `media_preview/image.html` (a port of imageViewer.ts: scale to fit, zoom levels, pixelation past 3x, pinch, alt-click zoom out) or `player.html` (mediaPlayerEditorInput.ts markup). Status bar: zoom (Select Zoom Level picker), dimensions, file size. Shortcuts: upstream draws these in the workbench DOM, the port in a webview; codec probing (mediaCodecs.ts), Copy image, Save As and the legacy `media-preview` editor migration are not ported; only `file` resources preview. A custom editor or media preview tab draws its file's icon and the Explorer reveals that file (`EditorResourceAccessor.getOriginalUri`). ui-pair (`port/fixtures/ui-steps/media-preview.json`, FILE=image.png, video.mp4 and audio.mp3): WebKit's video and audio controls where Chromium draws its own. Breadcrumbs: a custom editor or media preview shows its file's breadcrumbs without outline symbols, and every editor whose file another editor can open draws the editor type control at the right (breadcrumbsControl.ts `_updateEditorTypeControl`, editorTypePicker.ts: `getEditorMatches` order, priority then glob length, the unconfigured `*` option editors left out; the menu reopens with an editor, Alt opens it to the side, the Set Default submenu writes the association; workbench/editor_type_picker.rs, menu commands `editorType.<action>.<id>`). Focus: imagePreviewEditor.ts `focus` moves DOM focus to the viewer; in the port the editor's focus reaches the page as its window's `focus` event (the host page focuses the frame on its first load and on the `focus` message), and image.html moves it to the viewer, which draws the workbench's `[tabindex="0"]:focus` ring for keyboard and programmatic focus. A media preview opened from the command line on a first start opens in its preview: unlike extension editors, it is registered before `resolveEditor` runs.- Markdown: `FIXTURE=markdown-tests port/tools/webview-check` (5 checks, incl. `showPreviewToSide` in column Two); the extension's own tests run with `port/tools/extension-tests markdown-language-features test-workspace` (`APP=reference` for the baseline: 215 passing, 2 pending). `vscode.open` of a URI with a `#L<line>` fragment and no column goes through the opener's `extractSelection` (editorCommands.ts `_workbench.open`), which documentLink.test.ts needs.