Skip to content

Visual Studio Code, rebuilt in Rust

Rust

fix(webview): show and run the webview context menu

rokartur2bffcbf19a77
diff --git a/native/crates/app/src/webview/linux.rs b/native/crates/app/src/webview/linux.rs
index 5437a69a247..01524ae9ffc 100644
--- a/native/crates/app/src/webview/linux.rs
+++ b/native/crates/app/src/webview/linux.rs
@@ -53,6 +53,10 @@ impl Webview {
match self.never {}
}
+ pub fn clipboard_command(&mut self, _command: &str) {
+ match self.never {}
+ }
+
pub fn take_keyboard(&self) {
match self.never {}
}
diff --git a/native/crates/app/src/webview/macos.rs b/native/crates/app/src/webview/macos.rs
index 90b59b7b98b..73b6ae3766c 100644
--- a/native/crates/app/src/webview/macos.rs
+++ b/native/crates/app/src/webview/macos.rs
@@ -129,6 +129,22 @@ impl Webview {
self.send("focus", Value::Null);
}
+ /// `webviewElement.ts` `cut`, `copy`, `paste`: WebKit's own editing commands in the page, as Cmd+C runs them.
+ /// The host page's `execCommand` needs `javaScriptCanAccessClipboard` and `DOMPasteAllowed` in WebKit, which would
+ /// let every page in the webview, a Simple Browser site too, read the clipboard.
+ pub fn clipboard_command(&mut self, command: &str) {
+ self.take_keyboard();
+ let nil = std::ptr::null::<objc2::runtime::AnyObject>();
+ // SAFETY: WKWebView answers the NSResponder editing actions, whose sender may be nil.
+ unsafe {
+ match command {
+ "cut" => msg_send![&*self.view, cut: nil],
+ "copy" => msg_send![&*self.view, copy: nil],
+ _ => msg_send![&*self.view, paste: nil],
+ }
+ }
+ }
+
/// Makes the view the first responder, as a click into it does.
pub fn take_keyboard(&self) {
if let Some(window) = self.view.window().filter(|window| !self.is_first_responder(window)) {
diff --git a/native/crates/app/src/workbench/webview_panels.rs b/native/crates/app/src/workbench/webview_panels.rs
index b32ad9f34a9..a22cf71ce2e 100644
--- a/native/crates/app/src/workbench/webview_panels.rs
+++ b/native/crates/app/src/workbench/webview_panels.rs
@@ -89,6 +89,8 @@ pub(super) struct WebviewPanel {
pub(super) focused: bool,
/// Where the webview was placed last, in window coordinates.
bounds: Rc<Cell<Bounds<Pixels>>>,
+ /// Hidden under a menu, quick input or the modal part: the body stops placing (and so showing) the webview.
+ covered: bool,
/// Restored from the editor state (`LazilyResolvedWebviewEditorInput`): `$deserializeWebviewPanel` waits for
/// the editor to show and a serializer of its view type.
revive: bool,
@@ -263,7 +265,7 @@ impl Workbench {
/// The box the webview of the first matching panel is placed over.
pub(super) fn webview_body(&self, matches: impl Fn(&WebviewPanel) -> bool) -> Div {
let panel = self.webview_panels.panels.iter().find(|panel| matches(panel));
- let view = panel.and_then(|panel| panel.webview.as_ref()).map(Webview::view);
+ let view = panel.filter(|panel| !panel.covered).and_then(|panel| panel.webview.as_ref()).map(Webview::view);
let placed = panel.map(|panel| panel.bounds.clone());
div().flex_1().min_h_0().child(
canvas(
@@ -307,9 +309,9 @@ impl Workbench {
if shown && panel.revive {
revived.push(panel.handle.clone());
}
- let under_modal = modal.as_ref().is_some_and(|modal| !panel.covers(modal));
+ panel.covered = covered || modal.as_ref().is_some_and(|modal| !panel.covers(modal));
match (&panel.webview, shown) {
- (Some(webview), true) if covered || under_modal => webview.hide(),
+ (Some(webview), true) if panel.covered => webview.hide(),
(Some(webview), true) if gpui_focused => webview.release_keyboard(),
(Some(webview), false) if panel.retain_context_when_hidden => webview.hide(),
(Some(_), false) => panel.webview = None,
@@ -467,6 +469,7 @@ impl Workbench {
if let Some(tab) = event.id.strip_prefix(super::notebook_editor::WEBVIEW_ID_PREFIX) {
return self.handle_notebook_webview_event(tab.parse().unwrap_or_default(), &event.channel, &event.data, window, cx);
}
+ let its_menu_open = self.context_menu.is_some() && self.webview_panels.context_menu_panel.as_ref() == Some(&event.id);
let Some(panel) = self.webview_panel_mut(&event.id) else { return };
let data = event.data;
match event.channel.as_str() {
@@ -509,6 +512,11 @@ impl Workbench {
"did-blur" => panel.focused = false,
"did-focus" => {
panel.focused = true;
+ // The right click that opened this webview's menu focused the page; the host page polls its focus
+ // every 250ms (pre/index.html `trackFocus`), so this comes after the menu took the focus, which it keeps.
+ if its_menu_open {
+ return;
+ }
// The webview has the keyboard; GPUI's elements lose the focus, as the iframe's focus blurs them.
if let Some(webview) = &panel.webview {
webview.take_keyboard();
@@ -759,7 +767,7 @@ impl Workbench {
}
let Some(handle) = self.webview_panels.context_menu_panel.clone() else { return false };
let Some(webview) = self.webview_panel_mut(&handle).and_then(|panel| panel.webview.as_mut()) else { return false };
- webview.send("execCommand", json!(command));
+ webview.clipboard_command(command);
true
}
@@ -810,6 +818,7 @@ impl WebviewPanel {
find_focused: false,
focused: false,
bounds: Rc::default(),
+ covered: false,
revive: false,
}
}
@@ -971,6 +980,10 @@ mod tests {
let (titles, args) = right_click(json!({ "portItem": true, "preventDefaultContextMenuItems": true }), cx);
assert_eq!(titles, ["Port Item"]);
assert_eq!(args, [json!({ "portItem": true, "preventDefaultContextMenuItems": true, "webview": "preview" })]);
+ workbench.update_in(cx, |workbench, window, cx| {
+ workbench.handle_webview_event(WebviewEvent { id: "h1".into(), channel: "did-focus".into(), data: Value::Null, read: None }, window, cx);
+ assert!(workbench.context_menu.is_some() && window.focused(cx).is_some(), "the right click's late did-focus leaves the focus in the menu");
+ });
}
#[gpui::test]
diff --git a/port/fixtures/extensions/webview-context-pair/extension.js b/port/fixtures/extensions/webview-context-pair/extension.js
new file mode 100644
index 00000000000..d6204e2fb11
--- /dev/null
+++ b/port/fixtures/extensions/webview-context-pair/extension.js
@@ -0,0 +1,18 @@
+// A webview panel for the `webview/context` pair of `port/tools/ui-pair` with
+// `ARGS=--extensionDevelopmentPath=<this folder>`: a selected textarea in a `data-vscode-context` section, so a right
+// click shows the extension's item and Cut, Copy and Paste, which run in the page.
+const vscode = require('vscode');
+
+exports.activate = context => {
+ context.subscriptions.push(vscode.commands.registerCommand('webviewContextPair.hello', () => vscode.window.showInformationMessage('Hello from the webview menu')));
+ const panel = vscode.window.createWebviewPanel('webviewContextPair', 'Context Pair', vscode.ViewColumn.One, { enableScripts: true });
+ panel.webview.html = `<!DOCTYPE html>
+<html><body data-vscode-context='{"webviewSection": "text", "preventDefaultContextMenuItems": false}'>
+<textarea id="text" style="position: absolute; left: 40px; top: 40px; width: 400px; height: 120px; font-size: 20px">hello webview</textarea>
+<script>
+const text = document.getElementById('text');
+// WebKit selects the word under a right click where Chromium keeps the selection: both select all here.
+text.addEventListener('contextmenu', () => text.select());
+</script>
+</body></html>`;
+};
diff --git a/port/fixtures/extensions/webview-context-pair/package.json b/port/fixtures/extensions/webview-context-pair/package.json
new file mode 100644
index 00000000000..3750f291ac0
--- /dev/null
+++ b/port/fixtures/extensions/webview-context-pair/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "webview-context-pair",
+ "publisher": "port",
+ "version": "0.0.1",
+ "main": "./extension.js",
+ "activationEvents": ["onStartupFinished"],
+ "engines": { "vscode": "^1.90.0" },
+ "contributes": {
+ "commands": [{ "command": "webviewContextPair.hello", "title": "Say Hello" }],
+ "menus": {
+ "webview/context": [{ "command": "webviewContextPair.hello", "when": "webviewId == 'webviewContextPair' && webviewSection == 'text'" }]
+ }
+ }
+}
diff --git a/port/fixtures/ui-pair/m17/webview-context.json b/port/fixtures/ui-pair/m17/webview-context.json
new file mode 100644
index 00000000000..0dd3d0c54fe
--- /dev/null
+++ b/port/fixtures/ui-pair/m17/webview-context.json
@@ -0,0 +1,26 @@
+[
+ { "wait": 15000 },
+ { "rightClick": [150, 125], "foreground": true },
+ { "wait": 1000 },
+ { "shot": "menu" },
+ { "click": [196, 168] },
+ { "wait": 1000 },
+ { "clipboard": "copy" },
+ { "rightClick": [150, 125], "foreground": true },
+ { "wait": 1000 },
+ { "click": [190, 144] },
+ { "wait": 1000 },
+ { "clipboard": "cut" },
+ { "shot": "cut" },
+ { "rightClick": [150, 125], "foreground": true },
+ { "wait": 1000 },
+ { "click": [197, 192] },
+ { "wait": 1000 },
+ { "shot": "paste" },
+ { "rightClick": [150, 125], "foreground": true },
+ { "wait": 1000 },
+ { "shot": "hello-menu" },
+ { "click": [209, 227] },
+ { "wait": 1500 },
+ { "shot": "hello" }
+]
diff --git a/port/ledger.md b/port/ledger.md
index b61167cd2ef..610dd64e387 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 | in progress | 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`. |
@@ -608,7 +608,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston
| workbench/contrib/url | workbench contribution | M12 | verified | | trusted_domains.rs (isURLDomainTrusted, globs, localhost) and workbench/url_actions.rs: workbench.action.url.openUrl, workbench.action.manageTrustedDomain (trustedDomains:/Trusted Domains.jsonc editor, saved to http.linkProtectionTrustedDomains), link prompt "Do you want Code - OSS to open the external website?" with Copy and Configure Trusted Domains; cargo test -p app -- trusted_domains:: url_actions; verified at port-m12b-verify: cargo test -p app trusted_domains 10/10, url_actions 2/2; trustedDomainsValidator `fromWorkspace` (editor links and webview links ask for workspace trust before a command link, skip the domain prompt in a trusted workspace unless `workbench.trustedDomains.promptInTrustedWorkspace`): cargo test -p app -- a_workspace_link_follows_workspace_trust an_editor_link_opens_without_the_domain_prompt a_webview_command_link_asks_for_workspace_trust |
| workbench/contrib/userDataProfile | workbench contribution | M10 | verified | | workbench/user_data_profile.rs, workbench/profiles_editor_view.rs, workbench/icon_select_box.rs: cargo test -p app icon_select_box profiles_editor_view preview_opens_a_window_on_a_transient_profile_that_goes_with_it; ui-pair Profiles editor and new profile form (port/results/profiles.md) |
| workbench/contrib/userDataSync | workbench contribution | | removed | | no sign-in/AI by decision (port/notes.md); not ported |
-| workbench/contrib/webview | workbench contribution | M17 | ported | [3 S] webview_panels.rs `did-context-menu`: no ui-pair check against the reference yet (needs a webview fixture contributing `webview/context`), and Cut, Copy and Paste of the menu (`execCommand` in the page) are not run on a real WKWebView | webview.rs: cargo test -p app a_webview_right_click_shows_the_webview_context_menu maps_resource_urls_to_resources_inside_the_roots webview_resource_reads_answer_with_the_file_service_bytes reads_resource_roots_and_stable_origins; `FIXTURE=webview-tests port/tools/webview-check` 8/8; api-tests `MOCHA_GREP="vscode API - webview"` 1 passing; ui-pair markdown-preview.json find (port/results/webviews.md), `webview-devtools.json` (a Web Inspector window per webview, where upstream docks Chromium devtools) |
+| workbench/contrib/webview | workbench contribution | M17 | verified | | webview.rs, webview/macos.rs: cargo test -p app a_webview_right_click_shows_the_webview_context_menu maps_resource_urls_to_resources_inside_the_roots webview_resource_reads_answer_with_the_file_service_bytes reads_resource_roots_and_stable_origins; `FIXTURE=webview-tests port/tools/webview-check` 8/8; api-tests `MOCHA_GREP="vscode API - webview"` 1 passing; ui-pair markdown-preview.json find (port/results/webviews.md), `webview-devtools.json` (a Web Inspector window per webview, where upstream docks Chromium devtools); ui-pair m17/webview-context.json with port/fixtures/extensions/webview-context-pair: `webview/context` item, Cut, Copy and Paste on a real WKWebView, pasteboard text as the reference's (port/notes.md Webview context menu) |
| workbench/contrib/webviewPanel | workbench contribution | M17 | verified | | webview panels as editors in groups (workbench/webview_panels.rs), reveal moves to the target group, `activeWebviewPanelId`/`activeCustomEditorId` per group, a focused group focuses its webview; `FIXTURE=webview-tests` and `FIXTURE=markdown-tests port/tools/webview-check`; cargo test -p app webview_panels; panel restore on restart and reload: ui-pair webview-panel-restore.json, cargo test -p app panels_with_a_serializer |
| workbench/contrib/webviewView | workbench contribution | M17 | verified | | `contributes.views` of type webview as contributed views beside the tree views: their container, `when`, pane layout and `<id>.focus`, collapsed at first (viewsExtensionPoint.ts `showCollapsed`), resolved on first show with `onView:` activation (workbench/webview_views.rs); `$setWebviewViewBadge` on the view's container (webviewViewPane.ts `updateBadge`: cargo test -p app a_webview_view_shows_in_its_own_container_while_its_when_holds); `FIXTURE=webview-view-tests port/tools/webview-check` 5/5 on both apps |
| workbench/contrib/welcomeBanner | workbench contribution | M19 | n/a | | shows the web embedder's `welcomeBanner` option; a desktop window has none |
diff --git a/port/notes.md b/port/notes.md
index c0e64244c3d..50b5f3e5962 100644
--- a/port/notes.md
+++ b/port/notes.md
@@ -742,6 +742,7 @@ Scope (milestone 18): extension management on disk with VSIX install and uninsta
- Session m17d: the MRU kernel picker (`workbench/kernel_picker.rs`), `onRenderer:` activation, the outline's Filter Entries, `notebook.cellToolbarVisibility` click, the notebook and interactive status bar items, restored editors taking the focus, REPL scratchpad backups, dirty notebooks in the Explorer badge. The cell list's vertical scrollbar and `NotebookOverviewRuler` (`workbench/notebook_editor/overview_ruler.rs`): the list scrolls as a workbench list (`ListId::Notebook`, list_scroll.rs: wheel sensitivity, smooth scrolling, the fading 10px scrollbar, the top shadow), the back layer's `did-scroll-wheel` takes the same path, and the list scrolls until 50px of the last cell are left (`paddingBottom` of `editor.scrollBeyondLastLine`, not in interactive and REPL history lists). The webview clip leaves the list's right 10px to the scrollbar and ruler (the cells end 16px from it). The ruler draws find's decorations in the center lane as notebookOverviewRuler.ts: scaled by the editor height with the 26px toolbar over the scroll height, a line at most the editor line height in canvas pixels (half of it on a 2x display). An unfocused cell editor has a cover that takes the mouse: a press focuses the cell and places its cursor (`click_active_editor_at`, shared with the playground); its lines answered for the active editor before, and a hover past the focused cell's last line panicked. Checks: `cargo test -p app the_notebook_list_scrolls_beyond, the_mouse_over_a_longer_unfocused_cell, overview_ruler`; ui-pair m17/notebook-find.json (ruler marks at the reference's place), m17/notebook-scroll.json. Differences named, not copied: the cell title toolbar keeps stale actions until a menu context key changes (the reference shows only `...` and delete on a cell focused by keyboard or click); the reference's breadcrumbs show `…` for a code cell until its content changes; the webview hides under menus and quick input (native layer, see above); a restored notebook's status bar in the reference leaves out the cell editor's items (`Ln, Col`, `LF`) though the cell editor has the focus; Add Cell Output to Chat (AI removed). Unfocused cell editors show their hovers since (`the_mouse_over_an_unfocused_cell_shows_its_hover`). Hovering a markdown preview then Down moves the focused cell in both (ui-pair hover-down, the open question of m17c closed).
- Views audit (ui-pairs m17/notebook-open, notebook-keys-outline, notebook-output-toolbar, notebook-toolbars, notebook-cli at 8f138e76960, Studio /tmp/views-ipynb and /tmp/views-ipynb2): the "differences left" above now match: breadcrumbs (also `sample.ipynb > …` and the chain after keyboard moves), Run All `...`, output `...` and its menu, fold chevron, code and markup cell toolbars, title gear, focus bars over the outputs, `Spaces: 4`, the Outline filter action, and on the command line the JSON breadcrumbs `> …` and the `{ }` language status. Left: the reference shows only `...` and delete on the markup cell right after opening (its stale toolbar, named above, not copied); the Output menu leaves out Add Cell Output to Chat (AI removed); in one of two runs a click on the markdown preview then Down kept Cell 1 focused (ledger row extension/ipynb). The reference showed git's "A git repository was found in the parent folders" prompt within 6 s of notebook-cli, the port did not (fixture inside this repository; not notebook code).
- Session m17-gaps: the cell execute dropdown (codeCellRunToolbar.ts): with `notebook.consolidatedRunButton` the run button gets a chevron that opens the non-inline groups of `notebook/cell/execute` (Execute Above Cells, Execute Cell and Below), the button placed as `.run-button-container` in notebook.css (`cargo test -p app the_cell_execute_menu`, ui-pair m17/notebook-cell-execute.json). The kernel picker lists `notebook/kernelSource` actions (notebookKernelServiceImpl.ts `getSourceActions`) and runs them with `{uri, $mid: 14}`, the notebook toolbar's kernel button shows `sync~spin` and the action's title while one runs; a failed action is logged to stderr, as upstream only warns (`kernel_source_actions_run_from_the_kernel_picker`). The Notebook Variables view (`workbench/notebook_variables.rs`, notebookVariablesView.ts) sits in Run and Debug after Breakpoints when `notebook.variablesView` is on (or a REPL is active) and the bound kernel has a variable provider; it pages children by 100 and its context menu is `notebook/variables/context` with Copy Value (`the_notebook_variables_view_lists_the_kernels_variables`). Not seen in a ui-pair: no extension in the fixtures contributes kernel source actions or a variable provider for the reference.
+- Webview context menu (session m17-gaps, ui-pair m17/webview-context.json with `FOLDER= ARGS=--extensionDevelopmentPath=<port/fixtures/extensions/webview-context-pair>` and the pasteboard emptied before each app): the `webview/context` item and Cut, Copy and Paste show and run as the reference's, the copied and cut text and the pasted textarea match, Say Hello's toast too. Three fixes: the webview hid under the menu only until the next paint placed it again (`WebviewPanel::covered` now stops the placing); the host page's focus poll (250ms) reports the right click's focus after the menu took it, and that blurred the menu shut (the late `did-focus` of the menu's webview is ignored); WebKit's `execCommand` runs Cut, Copy and Paste only with `javaScriptCanAccessClipboard` and `DOMPasteAllowed`, which would let any page in a webview read the clipboard, so the menu runs WKWebView's own `cut:`, `copy:` and `paste:` actions (`Webview::clipboard_command`) instead of the host page's `execCommand`. Left: the webview hides under the menu (native layer, above); WebKit selects the word under a right click where Chromium keeps the selection, so the fixture selects all on `contextmenu`.
## Milestone 14: source control and diff