Skip to content

Visual Studio Code, rebuilt in Rust

Rust

feat(webview): show the webview/context menu on a right click

rokartur77ae8575495b
diff --git a/native/crates/app/src/menus.rs b/native/crates/app/src/menus.rs
index 37030e658d2..35194908c02 100644
--- a/native/crates/app/src/menus.rs
+++ b/native/crates/app/src/menus.rs
@@ -172,6 +172,8 @@ pub enum MenuId {
ExtensionContext,
ViewItemContext,
EditorContent,
+ /// `MenuId.WebviewContext`: a webview's context menu.
+ WebviewContext,
/// suggest.ts `suggestWidgetStatusbarMenu`.
SuggestWidgetStatusBar,
TerminalEditorInstanceContext,
@@ -487,6 +489,10 @@ const WORKBENCH_MENUS: &[Row] = &[
(MenuId::EditorContext, None, "editor.action.clipboardCutAction", "Cut", "9_cutcopypaste", 1., Some("!editorReadonly"), None),
(MenuId::EditorContext, None, "editor.action.clipboardCopyAction", "Copy", "9_cutcopypaste", 2., None, None),
(MenuId::EditorContext, None, "editor.action.clipboardPasteAction", "Paste", "9_cutcopypaste", 4., Some("!editorReadonly"), None),
+ // webview.contribution.ts.
+ (MenuId::WebviewContext, None, "editor.action.clipboardCutAction", "Cut", "5_cutcopypaste", 1., Some("!preventDefaultContextMenuItems"), None),
+ (MenuId::WebviewContext, None, "editor.action.clipboardCopyAction", "Copy", "5_cutcopypaste", 2., Some("!preventDefaultContextMenuItems"), None),
+ (MenuId::WebviewContext, None, "editor.action.clipboardPasteAction", "Paste", "5_cutcopypaste", 3., Some("!preventDefaultContextMenuItems"), None),
// debugEditorActions.ts `OpenDisassemblyViewAction`.
(MenuId::EditorContext, None, "debug.action.openDisassemblyView", "Open Disassembly View", "debug", 5., Some("inDebugMode && !panelFocus && debugState == 'stopped' && editorTextFocus && disassembleRequestSupported && languageSupportsDisassembleRequest"), Some("focusedStackFrameHasInstructionReference")),
(MenuId::EditorContext, None, "workbench.action.showCommands", "Command Palette...", "z_commands", 1., Some("!editorSimpleInput"), None),
@@ -1058,6 +1064,7 @@ const API_MENUS: &[(&str, MenuId)] = &[
("file/share", MenuId::MenubarShare),
("menuBar/edit/copy", MenuId::MenubarCopy),
("editor/content", MenuId::EditorContent),
+ ("webview/context", MenuId::WebviewContext),
("comments/commentThread/title", MenuId::CommentThreadTitle),
("comments/commentThread/context", MenuId::CommentThreadActions),
("comments/commentThread/additionalActions", MenuId::CommentThreadAdditionalActions),
diff --git a/native/crates/app/src/workbench/context_menu.rs b/native/crates/app/src/workbench/context_menu.rs
index c784008350d..e580407fcb9 100644
--- a/native/crates/app/src/workbench/context_menu.rs
+++ b/native/crates/app/src/workbench/context_menu.rs
@@ -266,6 +266,7 @@ impl Workbench {
/// `hideContextView`: focus goes back to where it was if the menu still has it.
pub(super) fn hide_context_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(menu) = self.context_menu.take() else { return };
+ self.webview_context_menu_hidden();
if menu.focus.is_focused(window) {
match &menu.focus_to_return {
Some(focus) => window.focus(focus, cx),
diff --git a/native/crates/app/src/workbench/editor_commands.rs b/native/crates/app/src/workbench/editor_commands.rs
index 22895b7b647..eade6268016 100644
--- a/native/crates/app/src/workbench/editor_commands.rs
+++ b/native/crates/app/src/workbench/editor_commands.rs
@@ -295,8 +295,18 @@ impl Workbench {
});
self.commands.register("cursorUndo", |workbench, _, _, cx| workbench.run_cursor_undo(false, cx));
self.commands.register("cursorRedo", |workbench, _, _, cx| workbench.run_cursor_undo(true, cx));
- self.commands.register("editor.action.clipboardCopyAction", |workbench, _, window, cx| workbench.copy_to_clipboard(false, window, cx));
- self.commands.register("editor.action.clipboardCutAction", |workbench, _, window, cx| workbench.copy_to_clipboard(true, window, cx));
+ self.commands.register("editor.action.clipboardCopyAction", |workbench, args, window, cx| {
+ if workbench.run_in_context_menu_webview("copy", &args) {
+ return Outcome::done();
+ }
+ workbench.copy_to_clipboard(false, window, cx)
+ });
+ self.commands.register("editor.action.clipboardCutAction", |workbench, args, window, cx| {
+ if workbench.run_in_context_menu_webview("cut", &args) {
+ return Outcome::done();
+ }
+ workbench.copy_to_clipboard(true, window, cx)
+ });
self.commands.register("editor.action.jumpToBracket", |workbench, _, _, cx| {
let languages = &workbench.languages;
let Some(editor) = workbench.editors.active_mut() else { return Outcome::done() };
@@ -364,7 +374,10 @@ impl Workbench {
workbench.copy_editor_text(true, cx);
Outcome::done()
});
- self.commands.register("editor.action.clipboardPasteAction", |workbench, _, window, cx| {
+ self.commands.register("editor.action.clipboardPasteAction", |workbench, args, window, cx| {
+ if workbench.run_in_context_menu_webview("paste", &args) {
+ return Outcome::done();
+ }
if !workbench.editor_focus.is_focused(window) {
return workbench.input_text_command("editor.action.clipboardPasteAction", window, cx).unwrap_or(Outcome::done());
}
diff --git a/native/crates/app/src/workbench/webview_panels.rs b/native/crates/app/src/workbench/webview_panels.rs
index ffd112bcb88..b32ad9f34a9 100644
--- a/native/crates/app/src/workbench/webview_panels.rs
+++ b/native/crates/app/src/workbench/webview_panels.rs
@@ -1,13 +1,15 @@
//! mainThreadWebviews.ts and mainThreadWebviewPanels.ts: an extension's webview panels as editors of the group,
//! each drawn by a native `Webview` over the editor's body.
+use std::cell::Cell;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
+use std::rc::Rc;
use exthost::session::{URL_PROTOCOL, VSBUFFER_KEY};
use futures::StreamExt;
use futures::channel::mpsc::{UnboundedSender, unbounded};
-use gpui::{Context, Div, Keystroke, Modifiers, Window, canvas, div, prelude::*};
+use gpui::{Bounds, Context, Div, Keystroke, Modifiers, Pixels, Window, canvas, div, prelude::*};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
@@ -42,6 +44,8 @@ pub struct WebviewPanels {
pub(super) insets: Vec<super::editor_insets::EditorInset>,
/// The view states the host heard last.
view_states: Value,
+ /// The panel whose `webview/context` menu showed last, where its Cut, Copy and Paste run.
+ context_menu_panel: Option<String>,
}
pub(super) struct WebviewPanel {
@@ -83,6 +87,8 @@ pub(super) struct WebviewPanel {
find_focused: bool,
/// webviewElement.ts `_focused`: between the host page's `did-focus` and `did-blur`.
pub(super) focused: bool,
+ /// Where the webview was placed last, in window coordinates.
+ bounds: Rc<Cell<Bounds<Pixels>>>,
/// Restored from the editor state (`LazilyResolvedWebviewEditorInput`): `$deserializeWebviewPanel` waits for
/// the editor to show and a serializer of its view type.
revive: bool,
@@ -256,13 +262,18 @@ 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 view = self.webview_panels.panels.iter().find(|panel| matches(panel)).and_then(|panel| panel.webview.as_ref()).map(Webview::view);
+ 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 placed = panel.map(|panel| panel.bounds.clone());
div().flex_1().min_h_0().child(
canvas(
move |bounds, window, _| {
if let Some(view) = &view {
webview::place(view, window, bounds);
}
+ if let Some(placed) = &placed {
+ placed.set(bounds);
+ }
},
|_, _, _, _| {},
)
@@ -525,6 +536,22 @@ impl Workbench {
webview.focus();
}
}
+ "did-context-menu" => {
+ // webviewElement.ts: the menu at the press, with the `data-vscode-context` keys and the webview id.
+ let (view_type, origin) = (panel.view_type.clone(), panel.bounds.get().origin);
+ if let Some(webview) = &mut panel.webview {
+ webview.send("set-context-menu-visible", json!({ "visible": true }));
+ }
+ let mut context = self.key_context(window);
+ let mut arg = data["context"].as_object().cloned().unwrap_or_default();
+ context.extend(arg.iter().map(|(key, value)| (key.clone(), value.clone())));
+ context.insert("webviewId".into(), json!(view_type));
+ arg.insert("webview".into(), json!(view_type));
+ let press = gpui::point(gpui::px(data["clientX"].as_f64().unwrap_or_default() as f32), gpui::px(data["clientY"].as_f64().unwrap_or_default() as f32));
+ let anchor = Bounds::new(origin + press, gpui::Size::default());
+ self.webview_panels.context_menu_panel = Some(event.id.clone());
+ self.show_context_menu(crate::menus::MenuId::WebviewContext, &context, anchor, vec![Value::Object(arg)], window, cx);
+ }
"fatal-error" => eprintln!("[webview] {}: {}", event.id, data["message"].as_str().unwrap_or_default()),
_ => {}
}
@@ -724,6 +751,26 @@ impl Workbench {
self.webview_panels.panels.iter().find(|panel| panel.path == path)
}
+ /// webview.contribution.ts `overrideCommandForWebview`: Cut, Copy and Paste run from a webview's context menu run in
+ /// its page (`execCommand`); keys pressed in the page reach WebKit's own editing commands.
+ pub(super) fn run_in_context_menu_webview(&mut self, command: &str, args: &[Value]) -> bool {
+ if !args.first().is_some_and(|arg| arg.get("webview").is_some()) {
+ return false;
+ }
+ 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));
+ true
+ }
+
+ /// `onDidHideContextMenu`: the page drops its `vscode-context-menu-visible` class.
+ pub(super) fn webview_context_menu_hidden(&mut self) {
+ let Some(handle) = self.webview_panels.context_menu_panel.clone() else { return };
+ if let Some(webview) = self.webview_panel_mut(&handle).and_then(|panel| panel.webview.as_mut()) {
+ webview.send("set-context-menu-visible", json!({ "visible": false }));
+ }
+ }
+
pub(super) fn webview_panel_mut(&mut self, handle: &str) -> Option<&mut WebviewPanel> {
self.webview_panels.panels.iter_mut().find(|panel| panel.handle == handle)
}
@@ -762,6 +809,7 @@ impl WebviewPanel {
find_visible: false,
find_focused: false,
focused: false,
+ bounds: Rc::default(),
revive: false,
}
}
@@ -893,6 +941,38 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
+ /// webviewElement.ts `did-context-menu`: `MenuId.WebviewContext` in the press's `data-vscode-context` keys and
+ /// `webviewId`, its commands given that context and `webview`; Cut, Copy and Paste unless
+ /// `preventDefaultContextMenuItems` (webview.contribution.ts).
+ #[gpui::test]
+ fn a_webview_right_click_shows_the_webview_context_menu(cx: &mut gpui::TestAppContext) {
+ use crate::menus::{Entry, MenuAction, MenuId, MenuItem};
+ let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
+ let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
+ let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
+ let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), crate::default_settings(), crate::host_sync::HostSync::new(std::sync::mpsc::channel().0), cx));
+ let init = json!({ "title": "Preview", "panelOptions": {}, "webviewOptions": {} });
+ workbench.update_in(cx, |workbench, window, cx| {
+ drop(workbench.handle_webview_request("$createWebviewPanel", &[json!({ "id": "ext" }), json!("h1"), json!("preview"), init, json!({ "viewColumn": 0 })], window, cx));
+ let entry = Entry::Command { id: "port.item".into(), precondition: None, toggled: None, alt: None };
+ let when = crate::contextkey::Expr::deserialize("webviewId == 'preview' && portItem");
+ workbench.menus.push(MenuItem { menu: MenuId::WebviewContext, entry, title: "Port Item".into(), group: "navigation".into(), order: 0., when });
+ });
+ let right_click = |context: Value, cx: &mut gpui::VisualTestContext| {
+ workbench.update_in(cx, |workbench, window, cx| {
+ let data = json!({ "clientX": 10, "clientY": 20, "context": context });
+ workbench.handle_webview_event(WebviewEvent { id: "h1".into(), channel: "did-context-menu".into(), data, read: None }, window, cx);
+ let menu = workbench.context_menu.as_ref().expect("the webview context menu shows");
+ let titles: Vec<String> = menu.levels[0].actions.iter().filter_map(|action| match action { MenuAction::Command { title, .. } => Some(title.clone()), _ => None }).collect();
+ (titles, menu.args.clone())
+ })
+ };
+ assert_eq!(right_click(json!({}), cx).0, ["Cut", "Copy", "Paste"]);
+ 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" })]);
+ }
+
#[gpui::test]
fn webview_resource_reads_answer_with_the_file_service_bytes(cx: &mut gpui::TestAppContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
diff --git a/port/ledger.md b/port/ledger.md
index bfe68f564e0..90fe4988be1 100644
--- a/port/ledger.md
+++ b/port/ledger.md
@@ -554,7 +554,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 | | userDataProfile.ts and userDataProfileActions.ts commands and menus (Switch, New, Save Current As, Delete, Export, New Window with Profile, the profile entries, Cleanup, Reset Workspace Associations, Help) in workbench/user_data_profile.rs; userDataProfilesEditor.ts as workbench/profiles_editor_view.rs (rename, Icon with the iconSelectBox.ts picker in workbench/icon_select_box.rs, Use for Current Window, Use for New Windows, Contents with the Source radio of each resource (`useDefaultFlags`), Folders & Workspaces with Add Folder, the row actions Duplicate/Export/Delete, the new profile form named Untitled N with Copy from, the Copy, Default or None source of each resource and the pinned Cancel/Preview/Create, Import Profile... from a URL or a file); the Manage activity item's profile icon and badge (globalCompositeBar.ts): ui-pair of the Profiles editor and the new profile form against the reference, port/results/profiles.md; cargo test -p app icon_select_box profiles_editor_view; Preview opens an in-process window on a transient profile that storage.json never holds and that goes when the window closes (preview_opens_a_window_on_a_transient_profile_that_goes_with_it) |
| 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.rs: the frame's `did-context-menu` shows no `webview/context` menu (webviewElement.ts:286) | webviewElement.ts host protocol, theme variables, focus handoff, local resource loading, http frames (webview.rs); resources of extension file system providers through the file service: `cargo test -p app maps_resource_urls_to_resources_inside_the_roots webview_resource_reads_answer_with_the_file_service_bytes reads_resource_roots_and_stable_origins`; find widget (Cmd+F, Enter, Escape) in the host page; Open Webview Developer Tools (Web Inspector), Reload Webviews; `FIXTURE=webview-tests port/tools/webview-check` 8/8 (provider resources inside and outside the roots); api-tests `MOCHA_GREP="vscode API - webview"` 1 passing; ui-pair markdown-preview.json find shots (port/results/webviews.md); Open Webview Developer Tools opens a Web Inspector window per webview: ui-pair `webview-devtools.json` `windows` step lists "Web Inspector — …index.html" (upstream docks the workbench's Chromium devtools) |
+| 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 | the `webview/context` menu at the press with the `data-vscode-context` keys, `webviewId` and Cut, Copy and Paste unless `preventDefaultContextMenuItems`, its commands given the context and `webview`, `set-context-menu-visible` (webviewElement.ts:273, webview.contribution.ts): cargo test -p app a_webview_right_click_shows_the_webview_context_menu; webviewElement.ts host protocol, theme variables, focus handoff, local resource loading, http frames (webview.rs); resources of extension file system providers through the file service: `cargo test -p app maps_resource_urls_to_resources_inside_the_roots webview_resource_reads_answer_with_the_file_service_bytes reads_resource_roots_and_stable_origins`; find widget (Cmd+F, Enter, Escape) in the host page; Open Webview Developer Tools (Web Inspector), Reload Webviews; `FIXTURE=webview-tests port/tools/webview-check` 8/8 (provider resources inside and outside the roots); api-tests `MOCHA_GREP="vscode API - webview"` 1 passing; ui-pair markdown-preview.json find shots (port/results/webviews.md); Open Webview Developer Tools opens a Web Inspector window per webview: ui-pair `webview-devtools.json` `windows` step lists "Web Inspector — …index.html" (upstream docks the workbench's Chromium devtools) |
| 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 |