Skip to content

Visual Studio Code, rebuilt in Rust

Rust
64.0 KB
Raw Blame
//! 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::{Bounds, Context, Div, Keystroke, Modifiers, Pixels, Window, canvas, div, prelude::*};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};

use super::Workbench;
use super::custom_editors::{CustomEditor, CustomEditors};
use super::media_preview::MediaPreview;
use super::opener::{ContributedOpeners, OpenOptions, Target};
use super::webview_views::WEBVIEW_VIEW_SCHEME;
use crate::commands::Outcome;
use crate::editor::{OpenEditor, TextDocument};
use crate::host_sync::WebviewTab;
use crate::theme::ThemeKind;
use crate::webview::{self, Webview, WebviewEvent};

/// `Schemas.webviewPanel`.
pub const WEBVIEW_PANEL_SCHEME: &str = "webview-panel";
/// editorService.ts `ACTIVE_GROUP` and `SIDE_GROUP`, as a `viewColumn` of the show options.
const ACTIVE_GROUP: i64 = -1;
pub(super) const SIDE_GROUP: i64 = -2;
/// webviewEditorInput.ts `WebviewInput.typeId`, the id of a webview editor in the editor state.
pub(super) const WEBVIEW_INPUT: &str = "workbench.editors.webviewInput";
/// mainThreadWebviewPanels.ts `WebviewViewTypeTransformer`: the editor's view type is the extension's with this prefix.
const VIEW_TYPE_PREFIX: &str = "mainThreadWebview-";

#[derive(Default)]
pub struct WebviewPanels {
    pub(super) panels: Vec<WebviewPanel>,
    pub(super) custom_editors: CustomEditors,
    events: Option<UnboundedSender<WebviewEvent>>,
    /// `$registerSerializer` view types.
    serializers: HashSet<String>,
    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 {
    pub(super) handle: String,
    /// The scheme and path of the editor's model: `webview-panel/webview-<providerId>-<resourceId>`
    /// (webviewEditorInput.ts), or a custom text editor's resource.
    pub(super) scheme: String,
    pub(super) path: PathBuf,
    /// The extension's view type; the editor id is `mainThreadWebview-<viewType>` (`WebviewViewTypeTransformer`).
    pub(super) view_type: String,
    pub(super) title: String,
    pub(super) extension_id: String,
    /// `webviewOriginStore.getOrigin`: one origin per view type and extension, so its storage persists.
    pub(super) origin: String,
    pub(super) html: String,
    /// `IWebviewContentOptions`.
    pub(super) content_options: Value,
    pub(super) retain_context_when_hidden: bool,
    /// `do-update-state`: what `vscode.setState` stored, given back when a released webview loads again.
    pub(super) state: Value,
    /// `$setIconPath`: the light and the dark theme's icon file.
    icon: Option<(PathBuf, PathBuf)>,
    /// Created when the editor first shows; released while hidden unless `retainContextWhenHidden`.
    pub(super) webview: Option<Webview>,
    /// overlayWebview.ts `_firstLoadPendingMessages`: the messages posted before the first webview was made.
    first_load_messages: Option<Vec<Value>>,
    pub(super) custom: Option<CustomEditor>,
    /// A custom text editor's tab, by model id: each editor of the resource has a webview of its own
    /// (`supportsMultipleEditorsPerDocument`).
    pub(super) editor: Option<u32>,
    /// A built-in media preview's page, which talks to the workbench instead of an extension.
    pub(super) media: Option<MediaPreview>,
    /// `enableFindWidget` of the panel options, and the find widget's state (`webviewFindWidgetVisible`,
    /// `webviewFindWidgetFocused`).
    pub(super) find_enabled: bool,
    /// The files of an Images Preview (contrib/imageCarousel), whose page talks to the workbench.
    pub(super) carousel: Option<Vec<PathBuf>>,
    find_visible: bool,
    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>>>,
    /// 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,
}

impl Workbench {
    pub(crate) fn handle_webview_request(&mut self, method: &str, args: &[Value], window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        let arg = |index: usize| args.get(index).cloned().unwrap_or(Value::Null);
        let handle = arg(0).as_str().unwrap_or_default().to_owned();
        match method {
            "$createWebviewPanel" => self.create_webview_panel(args, window, cx),
            "$registerSerializer" => {
                self.webview_panels.serializers.insert(handle);
                // A restored panel that shows revives on the next render (webviewWorkbenchService.ts `reviveFor`).
                cx.notify();
            }
            "$unregisterSerializer" => {
                self.webview_panels.serializers.remove(&handle);
            }
            "$disposeWebview" => {
                if let Some((group, index)) = self.webview_editor_group(&handle) {
                    self.with_group(group, |workbench| workbench.editors.close(index));
                    self.close_group_if_empty(group);
                    self.editors_changed(cx);
                }
            }
            "$reveal" => self.reveal_webview_panel(&handle, &arg(1), window, cx),
            "$setTitle" => {
                if let Some(panel) = self.webview_panel_mut(&handle) {
                    panel.title = arg(1).as_str().unwrap_or_default().to_owned();
                    let title = panel.title.clone();
                    if let Some(webview) = &mut panel.webview {
                        webview.send("set-title", json!(title));
                    }
                    self.editors_changed(cx);
                }
            }
            "$setIconPath" => {
                if let Some(panel) = self.webview_panel_mut(&handle) {
                    let file = |uri: &Value| (uri["scheme"] == "file").then(|| PathBuf::from(uri["path"].as_str().unwrap_or_default()));
                    let icon = arg(1);
                    panel.icon = file(&icon["light"]).zip(file(&icon["dark"]));
                    cx.notify();
                }
            }
            "$setHtml" => {
                if let Some(panel) = self.webview_panel_mut(&handle) {
                    panel.html = arg(1).as_str().unwrap_or_default().to_owned();
                    panel.update_content();
                }
            }
            "$setOptions" => {
                if let Some(panel) = self.webview_panel_mut(&handle) {
                    panel.content_options = arg(1);
                    if let Some(webview) = &panel.webview {
                        webview.set_local_resource_roots(local_resource_roots(&panel.content_options));
                    }
                    panel.update_content();
                }
            }
            "$postMessage" => {
                let Some(panel) = self.webview_panel_mut(&handle) else { return Outcome::Ready(Ok(json!(false))) };
                // deserializeWebviewMessage runs in the host page's bridge, where the ArrayBuffers are made.
                let buffers: Vec<Value> = args.iter().skip(2).map(|buffer| buffer[VSBUFFER_KEY].clone()).collect();
                let message = json!({ "message": arg(1), "buffers": buffers });
                match (&mut panel.webview, &mut panel.first_load_messages) {
                    (Some(webview), _) => webview.send("message", message),
                    (None, Some(pending)) => pending.push(message),
                    (None, None) => return Outcome::Ready(Ok(json!(false))),
                }
                return Outcome::Ready(Ok(json!(true)));
            }
            _ => {}
        }
        Outcome::done()
    }

    /// `$createWebviewPanel`: the panel opens pinned in the group of its view column and, unless `preserveFocus`,
    /// takes the focus.
    fn create_webview_panel(&mut self, args: &[Value], window: &mut Window, cx: &mut Context<Self>) {
        let (extension, handle, view_type, init, show) = (&args[0], args[1].as_str().unwrap_or_default(), args[2].as_str().unwrap_or_default(), &args[3], &args[4]);
        let path = PathBuf::from(format!("webview-panel/webview-undefined-{handle}"));
        let document = TextDocument::from_text(WEBVIEW_PANEL_SCHEME, &path, "", "utf8".into(), None, &self.languages, &self.settings.lock().unwrap());
        let title = init["title"].as_str().unwrap_or_default().to_owned();
        let retain = init["panelOptions"]["retainContextWhenHidden"] == true;
        let mut panel = WebviewPanel::new(handle.to_owned(), WEBVIEW_PANEL_SCHEME.into(), path, view_type, title, extension, init["webviewOptions"].clone(), retain, None);
        panel.find_enabled = init["panelOptions"]["enableFindWidget"] == true;
        self.webview_panels.panels.push(panel);
        let column = &show["viewColumn"];
        let target = match self.webview_target_group(column) {
            Some(group) => group,
            None => {
                self.leave_locked_group(WEBVIEW_PANEL_SCHEME, &document.path);
                self.editors.id
            }
        };
        let preserve_focus = show["preserveFocus"] == true;
        self.open_in_group(target, preserve_focus, |workbench| workbench.editors.open(document, false));
        self.editors_changed(cx);
        if !preserve_focus {
            self.focus_webview_panel(handle, window, cx);
        }
    }

    /// webviewWorkbenchService.ts `revealWebview`: the panel shows in the group of the view column, moving there
    /// from its group (webviewPanel.contribution.ts `onEditorOpening`); without a column it shows where it is.
    pub(super) fn reveal_webview_panel(&mut self, handle: &str, show: &Value, window: &mut Window, cx: &mut Context<Self>) {
        let Some((group, index)) = self.webview_editor_group(handle) else { return };
        let target = self.webview_target_group(&show["viewColumn"]).unwrap_or(group);
        let preserve_focus = show["preserveFocus"] == true;
        self.open_in_group(target, preserve_focus, |workbench| {
            if target == group {
                workbench.editors.activate(index);
                return;
            }
            let editor = workbench.with_group(group, |workbench| workbench.editors.take_editor(index));
            workbench.insert_moved_editor(editor);
        });
        if target != group {
            self.close_group_if_empty(group);
        }
        self.editors_changed(cx);
        if !preserve_focus {
            self.focus_webview_panel(handle, window, cx);
        }
    }

    /// Runs `open` in `group`, which becomes the active group unless `stay`: a preserveFocus open of a webview
    /// leaves the active group (webviewWorkbenchService.ts `EditorActivation.RESTORE`).
    fn open_in_group(&mut self, group: u32, stay: bool, open: impl FnOnce(&mut Self)) {
        match stay {
            true => self.with_group(group, open),
            false => {
                self.activate_group(group);
                open(self);
            }
        }
    }

    /// mainThreadWebviewPanels.ts `getTargetGroupFromShowOptions`, resolved to a group: none for the active group
    /// (no column, ACTIVE, or one empty group); SIDE is the group beside the active one, made when missing; a column
    /// past the last group adds one group after the last.
    pub(super) fn webview_target_group(&mut self, column: &Value) -> Option<u32> {
        let column = column.as_i64().filter(|column| *column != ACTIVE_GROUP)?;
        let groups = self.groups_in_grid_order();
        if groups.len() == 1 && self.editors.editors.is_empty() {
            return None;
        }
        let direction = self.side_by_side_direction();
        if column == SIDE_GROUP {
            // editorGroupFinder.ts: a locked side group gives way to a new one.
            let side = self.group_in_direction(direction).filter(|group| !self.editors.locked.contains(group));
            return Some(side.unwrap_or_else(|| self.add_group_beside(direction)));
        }
        let index = usize::try_from(column).ok()?;
        Some(match groups.get(index) {
            Some(&group) => group,
            None => self.with_group(*groups.last().expect("one group at least"), |workbench| workbench.add_group_beside(direction)),
        })
    }

    /// The editor is a webview panel's or a custom editor's, which draws a webview in place of the text.
    pub(super) fn shows_webview(&self, editor: &OpenEditor) -> bool {
        self.webview_panels.panels.iter().any(|panel| panel.shows(editor))
    }

    /// The body of a webview editor: an empty box the native view is placed over once laid out.
    pub(super) fn webview_editor_body(&self, editor: &OpenEditor) -> Div {
        self.webview_body(|panel| panel.shows(editor))
    }

    /// 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.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(
                move |bounds, window, _| {
                    if let Some(view) = &view {
                        webview::place(view, window, bounds);
                    }
                    if let Some(placed) = &placed {
                        placed.set(bounds);
                    }
                },
                |_, _, _, _| {},
            )
            .size_full(),
        )
    }

    /// Runs each render: the active panel's webview exists, the others hide or are released, and a webview
    /// gives the keyboard back once GPUI focused one of its own elements.
    pub(super) fn update_webview_panels(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.update_webview_views();
        let visible_views = self.visible_webview_views();
        let visible_editors = self.visible_editor_documents();
        // Native views draw over GPUI's layer: a quick input or menu on top of the webview would be hidden.
        // shortcut: the webview hides under these overlays, where Electron draws them over its iframe.
        let covered = self.quick_inputs.current().is_some() || self.keybindings_editor.open || self.context_menu.is_some();
        // The modal part covers the grid's webviews.
        let modal = self.modal_group_open().then(|| self.editors.group_tabs(crate::editor::MODAL_GROUP)).and_then(|(editors, active)| active.map(|index| &editors[index]));
        let modal = modal.map(|editor| (editor.document().scheme.clone(), editor.document().path.clone(), editor.model_id));
        let gpui_focused = window.focused(cx).is_some();
        let mut created = Vec::new();
        let mut revived = Vec::new();
        for panel in &mut self.webview_panels.panels {
            let shown = match panel.scheme == WEBVIEW_VIEW_SCHEME {
                true => visible_views.contains(&panel.path),
                false => visible_editors.iter().any(|visible| panel.covers(visible)),
            };
            if shown && panel.webview.is_none() && webview::supported() {
                created.push(panel.handle.clone());
            }
            if shown && panel.revive {
                revived.push(panel.handle.clone());
            }
            panel.covered = covered || modal.as_ref().is_some_and(|modal| !panel.covers(modal));
            match (&panel.webview, shown) {
                (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,
                _ => {}
            }
        }
        for handle in created {
            self.create_webview(&handle, window, cx);
        }
        for handle in revived {
            self.revive_webview_panel(&handle);
        }
        self.update_editor_insets(window, cx);
    }

    /// mainThreadWebviewPanels.ts revivers of a restored panel that shows: without a serializer of its view type the
    /// extension activates (`onWebviewPanel:<viewType>`); with one, the host fills the panel in `$deserializeWebviewPanel`.
    fn revive_webview_panel(&mut self, handle: &str) {
        let Some((group, _)) = self.webview_editor_group(handle) else { return };
        let position = self.groups_in_grid_order().iter().position(|id| *id == group);
        let index = self.webview_panels.panels.iter().position(|panel| panel.handle == handle).expect("a shown panel");
        let active = self.editors.active().is_some_and(|editor| self.webview_panels.panels[index].shows(editor));
        let panel = &mut self.webview_panels.panels[index];
        if !self.webview_panels.serializers.contains(&panel.view_type) {
            let event = format!("onWebviewPanel:{}", panel.view_type);
            drop(self.host.activate_by_event(&event));
            return;
        }
        panel.revive = false;
        let state = panel.state.as_str().and_then(|state| serde_json::from_str(state).ok()).unwrap_or(Value::Null);
        let init = json!({
            "title": panel.title,
            "state": state,
            "panelOptions": { "enableFindWidget": panel.find_enabled, "retainContextWhenHidden": panel.retain_context_when_hidden },
            "webviewOptions": panel.content_options,
            "active": active,
        });
        let args = vec![json!(handle), json!(panel.view_type), init, json!(position)];
        self.host.send("ExtHostWebviewPanels", "$deserializeWebviewPanel", args);
    }

    /// webviewEditorInputSerializer.ts `toJson` of a panel `shouldPersist` keeps: one restored, or one whose view type
    /// has a serializer.
    pub(super) fn serialized_webview_editor(&self, editor: &OpenEditor) -> Option<Value> {
        let panel = self.webview_panels.panels.iter().find(|panel| panel.scheme == WEBVIEW_PANEL_SCHEME && panel.is_extensions() && panel.custom.is_none() && panel.shows(editor))?;
        if !panel.revive && !self.webview_panels.serializers.contains(&panel.view_type) {
            return None;
        }
        let mut options = panel.content_options.clone();
        options["enableFindWidget"] = json!(panel.find_enabled);
        options["retainContextWhenHidden"] = json!(panel.retain_context_when_hidden);
        let icon = panel.icon.as_ref().map(|(light, dark)| json!({ "light": exthost::scan::file_uri(light), "dark": exthost::scan::file_uri(dark) }));
        Some(json!({
            "origin": panel.origin,
            "viewType": format!("{VIEW_TYPE_PREFIX}{}", panel.view_type),
            "providedId": panel.view_type,
            "title": panel.title,
            "options": options,
            "extensionId": panel.extension_id,
            "state": panel.state,
            "iconPath": icon,
        }))
    }

    /// webviewEditorInputSerializer.ts `deserialize` and `openRevivedWebview`: the panel's editor, filled in once it shows.
    pub(super) fn restore_webview_editor(&mut self, value: &Value) -> Option<TextDocument> {
        let view_type = value["viewType"].as_str()?.strip_prefix(VIEW_TYPE_PREFIX)?;
        let handle = crate::debug::generate_uuid();
        let path = PathBuf::from(format!("webview-panel/webview-undefined-{handle}"));
        let document = TextDocument::from_text(WEBVIEW_PANEL_SCHEME, &path, "", "utf8".into(), None, &self.languages, &self.settings.lock().unwrap());
        let options = &value["options"];
        let title = value["title"].as_str().unwrap_or_default().to_owned();
        let extension = json!({ "id": value["extensionId"] });
        let mut panel = WebviewPanel::new(handle, WEBVIEW_PANEL_SCHEME.into(), path, view_type, title, &extension, options.clone(), options["retainContextWhenHidden"] == true, None);
        panel.find_enabled = options["enableFindWidget"] == true;
        panel.state = value["state"].clone();
        let file = |uri: &Value| (uri["scheme"] == "file").then(|| PathBuf::from(uri["path"].as_str().unwrap_or_default()));
        panel.icon = file(&value["iconPath"]["light"]).zip(file(&value["iconPath"]["dark"]));
        panel.revive = true;
        self.webview_panels.panels.push(panel);
        Some(document)
    }

    /// The scheme, path and model id of each group's active editor, the modal group's included while it is open.
    fn visible_editor_documents(&self) -> Vec<(String, PathBuf, u32)> {
        let modal = self.modal_group_open().then_some(crate::editor::MODAL_GROUP);
        let groups = self.groups_in_grid_order().into_iter().chain(modal);
        let active = groups.filter_map(|group| {
            let (editors, active) = self.editors.group_tabs(group);
            active.map(|index| (editors[index].document().scheme.clone(), editors[index].document().path.clone(), editors[index].model_id))
        });
        active.collect()
    }

    /// webviewEditor.ts `setEditorVisible(false)` and `clearInput`: a panel's webview without `retainContextWhenHidden` is released
    /// as its editor hides, not at the next frame, so a reveal right after loads it again.
    fn release_hidden_webview_panels(&mut self) {
        let visible_editors = self.visible_editor_documents();
        for panel in &mut self.webview_panels.panels {
            let shown = visible_editors.iter().any(|visible| panel.covers(visible));
            if panel.scheme != WEBVIEW_VIEW_SCHEME && !shown && !panel.retain_context_when_hidden {
                panel.webview = None;
            }
        }
    }

    fn create_webview(&mut self, handle: &str, window: &mut Window, cx: &mut Context<Self>) {
        if !webview::supported() {
            return;
        }
        let events = self.webview_events(window, cx);
        let pre = self.app_root.join("src/vs/workbench/contrib/webview/browser/pre");
        let styles = self.webview_styles();
        let panel = self.webview_panel_mut(handle).expect("a shown panel");
        let mut webview = Webview::new(window, &panel.handle, &panel.origin, &panel.extension_id, pre, local_resource_roots(&panel.content_options), events);
        webview.send("styles", styles);
        panel.webview = Some(webview);
        panel.update_content();
        let webview = panel.webview.as_mut().expect("just made");
        for message in panel.first_load_messages.take().unwrap_or_default() {
            webview.send("message", message);
        }
    }

    /// The channel the webviews' host pages post on, read on the window's executor.
    pub(super) fn webview_events(&mut self, window: &mut Window, cx: &mut Context<Self>) -> UnboundedSender<WebviewEvent> {
        if let Some(events) = &self.webview_panels.events {
            return events.clone();
        }
        let (sender, mut receiver) = unbounded();
        cx.spawn_in(window, async move |workbench, cx| {
            while let Some(event) = receiver.next().await {
                if workbench.update_in(cx, |workbench, window, cx| workbench.handle_webview_event(event, window, cx)).is_err() {
                    break;
                }
            }
        })
        .detach();
        self.webview_panels.events = Some(sender.clone());
        sender
    }

    /// webviewElement.ts `on(...)` handlers, with mainThreadWebviews.ts forwarding to the extension host.
    fn handle_webview_event(&mut self, event: WebviewEvent, window: &mut Window, cx: &mut Context<Self>) {
        if let Some(read) = event.read {
            let bytes = self.host.read_file(read.resource);
            return cx.spawn(async move |_, _| (read.respond)(bytes.await.ok().and_then(Result::ok))).detach();
        }
        if event.id.starts_with("extension-editor-") {
            return self.handle_extension_editor_event(&event.id, &event.channel, &event.data, window, cx);
        }
        if event.id.starts_with(super::editor_insets::INSET_ID_PREFIX) {
            return self.handle_editor_inset_event(event);
        }
        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() {
            "webview-ready" => {
                if let Some(webview) = &mut panel.webview {
                    webview.did_become_ready();
                }
            }
            "onmessage" if panel.carousel.is_some() => {
                let message = data["message"].as_str().and_then(|text| serde_json::from_str(text).ok()).unwrap_or_default();
                self.handle_carousel_message(&event.id, &message, cx);
            }
            "onmessage" if panel.is_release_notes() => {
                let message = data["message"].as_str().and_then(|text| serde_json::from_str(text).ok()).unwrap_or_default();
                self.handle_release_notes_message(&message);
            }
            "onmessage" if panel.media.is_some() => {
                let message = data["message"].as_str().and_then(|text| serde_json::from_str(text).ok()).unwrap_or_default();
                self.handle_media_preview_message(&event.id, &message, window, cx);
            }
            "onmessage" => {
                // serializeWebviewMessage ran in the host page's bridge: JSON text, the ArrayBuffers as base64.
                self.host.send("ExtHostWebviews", "$onMessage", vec![json!(event.id), data["message"].clone(), data["buffers"].clone()]);
            }
            "do-update-state" => {
                panel.state = data.clone();
                if panel.scheme == WEBVIEW_VIEW_SCHEME {
                    let view_id = panel.view_type.clone();
                    self.save_webview_view_state(&view_id, &data);
                }
            }
            "no-csp-found" => {
                let extension_id = panel.extension_id.clone();
                self.host.send("ExtHostWebviews", "$onMissingCsp", vec![json!(event.id), json!(extension_id)]);
            }
            "did-click-link" => {
                let enable_command_uris = panel.content_options["enableCommandUris"].clone();
                self.open_webview_link(data["uri"].as_str().unwrap_or_default(), &enable_command_uris, window, cx);
            }
            "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();
                }
                window.blur(cx);
            }
            "did-keydown" => {
                // Deferred: the keystroke interceptors update the workbench, which this handler is updating.
                if let Some(keystroke) = keystroke(&data) {
                    window.defer(cx, move |window, cx| {
                        window.dispatch_keystroke(keystroke, cx);
                    });
                }
            }
            "find-focus" => {
                panel.find_focused = data["focused"] == true;
                if panel.find_focused {
                    window.blur(cx);
                }
            }
            "find-hidden" => {
                (panel.find_visible, panel.find_focused) = (false, false);
                // `WebviewFindWidget.hide` gives the focus back to the webview.
                if let Some(webview) = &mut panel.webview {
                    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()),
            _ => {}
        }
    }

    /// mainThreadWebviews.ts `onDidClickLink`: `isSupportedLink`, then the opener service as a workspace link.
    pub(super) fn open_webview_link(&mut self, link: &str, enable_command_uris: &Value, window: &mut Window, cx: &mut Context<Self>) {
        let (scheme, rest) = link.split_once(':').unwrap_or_default();
        let command = rest.split_once('?').map_or(rest, |(command, _)| command);
        let allow_commands = enable_command_uris == true || enable_command_uris.as_array().is_some_and(|ids| ids.iter().any(|id| id == command));
        let supported = match scheme {
            "http" | "https" | "mailto" | URL_PROTOCOL => true,
            "command" => allow_commands,
            _ => false,
        };
        if supported {
            let options = OpenOptions { allow_commands, from_workspace: true, contributed_openers: ContributedOpeners::Any, ..OpenOptions::default() };
            drop(self.open_link(Target::Text(link.into()), options, window, cx));
        }
    }

    /// Focuses the panel's webview, or does once it is created on the next render.
    pub(super) fn focus_webview_panel(&mut self, handle: &str, window: &mut Window, cx: &mut Context<Self>) {
        self.update_webview_panels(window, cx);
        window.blur(cx);
        if let Some(webview) = self.webview_panel_mut(handle).and_then(|panel| panel.webview.as_mut()) {
            webview.focus();
        }
    }

    /// Run from `editors_changed`: panels whose editor closed are disposed, tabs get titles, and the host hears
    /// where each panel shows (`updateWebviewViewStates`).
    pub(super) fn sync_webview_panels(&mut self) {
        let editors = &self.editors;
        let (open, closed): (Vec<WebviewPanel>, Vec<WebviewPanel>) =
            std::mem::take(&mut self.webview_panels.panels).into_iter().partition(|panel| panel.scheme == WEBVIEW_VIEW_SCHEME || editors.all_tabs().any(|editor| panel.shows(editor)));
        self.webview_panels.panels = open;
        self.release_hidden_webview_panels();
        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.
        self.release_custom_documents(closed);
        self.host.webview_tabs = self
            .webview_panels
            .panels
            .iter()
            // 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 {
                        label: panel.title.clone(),
                        view_type: panel.view_type.clone(),
                        custom_resource: Some(custom.resource.clone()),
                        custom_text: panel.scheme != WEBVIEW_PANEL_SCHEME,
                    },
                    // Images Preview is no webview input upstream (TabInputKind.UnknownInput); the release notes'
                    // view type has no extension prefix.
                    None if panel.carousel.is_some() || panel.is_release_notes() => WebviewTab { label: panel.title.clone(), view_type: panel.view_type.clone(), custom_resource: None, custom_text: false },
                    None => WebviewTab { label: panel.title.clone(), view_type: format!("mainThreadWebview-{}", panel.view_type), custom_resource: None, custom_text: false },
                };
                (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;
        }
        self.webview_panels.view_states = states.clone();
        self.host.send("ExtHostWebviewPanels", "$onDidChangeWebviewPanelViewStates", vec![states]);
    }

    /// Each editor panel's state: visible as its group's active editor, active as the active editor, and its
    /// group's index in grid order (`editorGroupToColumn`, which the host turns into a ViewColumn).
    fn webview_panel_view_states(&self) -> serde_json::Map<String, Value> {
        let active_group = self.editors.id;
        let mut states = serde_json::Map::new();
        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 visible = active_index == Some(index);
                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
    }

    /// webviewCommands.ts (find in the active webview editor) and the Developer commands of webview.contribution.ts.
    pub(super) fn register_webview_actions(&mut self) {
        self.commands.register("editor.action.webvieweditor.showFind", |workbench, _, _, _| {
            let styles = workbench.webview_styles();
            let icon = |name: &str| std::fs::read_to_string(crate::codicons::svg_path(&workbench.app_root, name)).unwrap_or_default();
            let icons = [icon("arrow-up"), icon("arrow-down"), icon("close")];
            if let Some(panel) = workbench.active_webview_panel_mut().filter(|panel| panel.find_enabled) {
                panel.find_visible = true;
                if let Some(webview) = &panel.webview {
                    webview.show_find(&styles, icons);
                }
            }
            Outcome::done()
        });
        self.commands.register("editor.action.webvieweditor.hideFind", |workbench, _, _, _| {
            if let Some(webview) = workbench.active_webview_panel_mut().and_then(|panel| panel.webview.as_ref()) {
                webview.hide_find();
            }
            Outcome::done()
        });
        for (command, previous) in [("editor.action.webvieweditor.findNext", false), ("editor.action.webvieweditor.findPrevious", true)] {
            self.commands.register(command, move |workbench, _, _, _| {
                if let Some(webview) = workbench.active_webview_panel_mut().and_then(|panel| panel.webview.as_ref()) {
                    webview.find(previous);
                }
                Outcome::done()
            });
        }
        self.commands.register("workbench.action.webview.openDeveloperTools", |workbench, _, _, _| {
            for webview in workbench.webview_panels.panels.iter().filter_map(|panel| panel.webview.as_ref()) {
                webview.open_inspector();
            }
            Outcome::done()
        });
        self.commands.register("workbench.action.webview.reloadWebviewAction", |workbench, _, _, _| {
            for panel in &mut workbench.webview_panels.panels {
                panel.update_content();
            }
            Outcome::done()
        });
    }

    /// The panel of the active editor when it is a webview editor (`WebviewEditor`), not a built-in media preview.
    fn active_webview_panel_mut(&mut self) -> Option<&mut WebviewPanel> {
        let active = self.editors.active()?;
        let index = self.webview_panels.panels.iter().position(|panel| panel.is_extensions() && panel.shows(active))?;
        Some(&mut self.webview_panels.panels[index])
    }

    /// The context keys of the active webview editor: its editor id and its find widget's state.
    pub(super) fn webview_editor_context(&self, context: &mut std::collections::HashMap<String, Value>) {
        let Some(active) = self.editors.active() else { return };
        let Some(panel) = self.webview_panels.panels.iter().find(|panel| panel.is_extensions() && panel.shows(active)) else { return };
        context.insert("activeEditor".into(), json!("WebviewEditor"));
        // webviewWorkbenchService.ts `getWebviewId` and customEditors.ts `getActiveCustomEditorId`, per group.
        context.insert("activeWebviewPanelId".into(), json!(panel.view_type));
        if panel.custom.is_some() {
            context.insert("activeCustomEditorId".into(), json!(panel.view_type));
        }
        context.insert("webviewFindWidgetEnabled".into(), json!(panel.find_enabled));
        context.insert("webviewFindWidgetVisible".into(), json!(panel.find_visible));
        context.insert("webviewFindWidgetFocused".into(), json!(panel.find_focused));
    }

    /// Sends the theme to every webview, as `WebviewThemeDataProvider.onThemeDataChanged` does.
    pub(super) fn restyle_webviews(&mut self) {
        let styles = self.webview_styles();
        for webview in self.webview_panels.panels.iter_mut().filter_map(|panel| panel.webview.as_mut()) {
            webview.send("styles", styles.clone());
        }
        for webview in self.webview_panels.insets.iter_mut().filter_map(|inset| inset.webview.as_mut()) {
            webview.send("styles", styles.clone());
        }
    }

    /// The title of a webview editor's tab, `WebviewInput.getName`.
    pub(super) fn webview_title(&self, path: &Path) -> Option<String> {
        self.webview_panel(path).map(|panel| panel.title.clone())
    }

    pub(super) fn webview_styles(&self) -> Value {
        let label = self.color_themes.iter().find(|entry| entry.settings_id == self.theme.settings_id).map_or(self.theme.settings_id.clone(), |entry| entry.label.clone());
        webview::theme_data(&self.theme, &label, &self.setting("editor"), self.setting("accessibility.underlineLinks") == true, self.is_motion_reduced())
    }

    /// webviewIconManager.ts: the dark icon for dark and high contrast themes, the light one otherwise.
    pub(super) fn webview_icon(&self, path: &Path) -> Option<&Path> {
        let (light, dark) = self.webview_panel(path)?.icon.as_ref()?;
        Some(match self.theme.kind {
            ThemeKind::Dark | ThemeKind::HighContrastDark => dark,
            ThemeKind::Light | ThemeKind::HighContrastLight => light,
        })
    }

    /// The file a custom editor or media preview panel shows.
    pub(super) fn webview_resource(&self, path: &Path) -> Option<PathBuf> {
        self.custom_editor_resource(path).filter(|(scheme, _)| scheme == "file").map(|(_, path)| path)
    }

    /// A custom editor's resource when a file system provider serves its scheme (breadcrumbsControl.ts
    /// `fileService.hasProvider`), as `vscode-debug-memory` for View Binary Data's hex editor.
    pub(super) fn custom_editor_resource(&self, path: &Path) -> Option<(String, PathBuf)> {
        let resource = &self.webview_panel(path)?.custom.as_ref()?.resource;
        let scheme = resource["scheme"].as_str()?;
        let has_provider = crate::editor::on_disk(scheme) || scheme == exthost::main_thread_files::DEBUG_MEMORY_SCHEME || self.file_system_providers.contains(scheme);
        has_provider.then(|| (scheme.to_owned(), PathBuf::from(resource["path"].as_str().unwrap_or_default())))
    }

    fn webview_panel(&self, path: &Path) -> Option<&WebviewPanel> {
        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.clipboard_command(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)
    }

    /// The group and index of the editor that shows the panel, in any group of the grid.
    pub(super) fn webview_editor_group(&self, handle: &str) -> Option<(u32, usize)> {
        let panel = self.webview_panels.panels.iter().find(|panel| panel.handle == handle)?;
        self.groups_in_grid_order().into_iter().find_map(|group| self.editors.group_tabs(group).0.iter().position(|editor| panel.shows(editor)).map(|index| (group, index)))
    }
}

impl WebviewPanel {
    #[allow(clippy::too_many_arguments)]
    pub(super) fn new(handle: String, scheme: String, path: PathBuf, view_type: &str, title: String, extension: &Value, content_options: Value, retain_context_when_hidden: bool, custom: Option<CustomEditor>) -> Self {
        let extension_id = extension["id"]["value"].as_str().or(extension["id"].as_str()).unwrap_or_default().to_owned();
        WebviewPanel {
            handle,
            scheme,
            path,
            view_type: view_type.to_owned(),
            title,
            origin: webview_origin(view_type, &extension_id),
            extension_id,
            html: String::new(),
            content_options,
            retain_context_when_hidden,
            state: Value::Null,
            icon: None,
            webview: None,
            first_load_messages: Some(Vec::new()),
            custom,
            editor: None,
            media: None,
            find_enabled: false,
            carousel: None,
            find_visible: false,
            find_focused: false,
            focused: false,
            bounds: Rc::default(),
            covered: false,
            revive: false,
        }
    }

    /// A panel an extension made, not a built-in page (media preview, Images Preview).
    fn is_extensions(&self) -> bool {
        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 {
        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`.
    pub(super) fn update_content(&mut self) {
        let Some(webview) = &mut self.webview else { return };
        let allow_scripts = self.content_options["enableScripts"] == true;
        let allow_forms = self.content_options["enableForms"].as_bool().unwrap_or(allow_scripts);
        webview.send(
            "content",
            json!({
                "contents": self.html,
                "title": self.title,
                "options": { "allowMultipleAPIAcquire": false, "allowScripts": allow_scripts, "allowForms": allow_forms },
                "state": self.state,
                "cspSource": "'self' https://*.vscode-cdn.net",
                "confirmBeforeClose": "keyboardOnly",
            }),
        );
    }
}

/// `localResourceRoots`; the extension host already put in the defaults.
pub(super) fn local_resource_roots(options: &Value) -> Vec<files::Resource> {
    options["localResourceRoots"].as_array().into_iter().flatten().map(exthost::main_thread_files::resource).collect()
}

/// A UUID-shaped origin that stays the same for a view type of an extension, as the stored one upstream does.
fn webview_origin(view_type: &str, extension_id: &str) -> String {
    let digest = Sha256::digest(format!("{extension_id}/{view_type}").as_bytes());
    let hex: String = digest.iter().take(16).map(|byte| format!("{byte:02x}")).collect();
    format!("{}-{}-{}-{}-{}", &hex[..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32])
}

/// A `did-keydown` from the host page as the keystroke GPUI would have seen: index.html forwards the keys its
/// frame does not handle, which upstream go to the workbench's keybinding service.
pub(super) fn keystroke(data: &Value) -> Option<Keystroke> {
    let code = data["code"].as_str().unwrap_or_default();
    let key = data["key"].as_str()?;
    let key = if let Some(letter) = code.strip_prefix("Key") {
        letter.to_ascii_lowercase()
    } else if let Some(digit) = code.strip_prefix("Digit") {
        digit.to_owned()
    } else {
        match key {
            "ArrowUp" => "up".into(),
            "ArrowDown" => "down".into(),
            "ArrowLeft" => "left".into(),
            "ArrowRight" => "right".into(),
            "PageUp" => "pageup".into(),
            "PageDown" => "pagedown".into(),
            " " => "space".into(),
            "Meta" | "Shift" | "Control" | "Alt" => return None,
            key if key.chars().count() == 1 => key.to_lowercase(),
            key => key.to_ascii_lowercase(),
        }
    };
    let modifiers = Modifiers { control: data["ctrlKey"] == true, alt: data["altKey"] == true, shift: data["shiftKey"] == true, platform: data["metaKey"] == true, function: false };
    Some(Keystroke { modifiers, key, key_char: None })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn maps_forwarded_key_events_to_keystrokes() {
        let event = |key: &str, code: &str, meta: bool, shift: bool| json!({ "key": key, "code": code, "metaKey": meta, "shiftKey": shift });
        let parsed = |data: Value| keystroke(&data).map(|keystroke| keystroke.unparse(crate::host_os()));
        #[cfg(target_os = "macos")]
        assert_eq!(parsed(event("P", "KeyP", true, true)), Some("cmd-shift-p".into()));
        #[cfg(target_os = "linux")]
        assert_eq!(parsed(event("P", "KeyP", true, true)), Some("super-shift-p".into()));
        assert_eq!(parsed(event("!", "Digit1", false, true)), Some("shift-1".into()));
        assert_eq!(parsed(event("F1", "F1", false, false)), Some("f1".into()));
        assert_eq!(parsed(event("ArrowUp", "ArrowUp", false, false)), Some("up".into()));
        assert_eq!(parsed(event("Escape", "Escape", false, false)), Some("escape".into()));
        assert_eq!(parsed(event("Shift", "ShiftLeft", false, true)), None);
    }

    #[gpui::test]
    fn panels_open_in_their_view_column_and_move_on_reveal(cx: &mut gpui::TestAppContext) {
        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 dir = std::env::temp_dir().join(format!("code-gpui-webview-columns-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("a.md"), "# a").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 file = json!({ "scheme": "file", "path": dir.join("a.md").to_string_lossy() });
        workbench.update_in(cx, |workbench, window, cx| workbench.api_open_editor(&[file], window, cx)).unwrap();
        let request = |method: &str, args: Vec<Value>, cx: &mut gpui::VisualTestContext| workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_webview_request(method, &args, window, cx)));
        let states = |cx: &mut gpui::VisualTestContext| workbench.read_with(cx, |workbench, _| (workbench.groups_in_grid_order().len(), Value::Object(workbench.webview_panel_view_states())));
        let init = json!({ "title": "Preview", "panelOptions": {}, "webviewOptions": {} });

        // Beside with preserveFocus adds a group and leaves the source's group active.
        request("$createWebviewPanel", vec![json!({ "id": "ext" }), json!("h1"), json!("preview"), init, json!({ "viewColumn": SIDE_GROUP, "preserveFocus": true })], cx);
        assert_eq!(states(cx), (2, json!({ "h1": { "visible": true, "active": false, "position": 1 } })));

        // A message posted before the first webview is made waits for it.
        let posted = workbench.update_in(cx, |workbench, window, cx| workbench.handle_webview_request("$postMessage", &[json!("h1"), json!("{}")], window, cx));
        assert!(matches!(posted, Outcome::Ready(Ok(Value::Bool(true)))));
        assert_eq!(workbench.read_with(cx, |workbench, _| workbench.webview_panels.panels[0].first_load_messages.as_ref().map(Vec::len)), Some(1));

        // A reveal in column One moves the panel there; its emptied group closes.
        request("$reveal", vec![json!("h1"), json!({ "viewColumn": 0, "preserveFocus": true })], cx);
        assert_eq!(states(cx), (1, json!({ "h1": { "visible": true, "active": true, "position": 0 } })));
        let mut context = std::collections::HashMap::new();
        workbench.read_with(cx, |workbench, _| workbench.webview_editor_context(&mut context));
        assert_eq!(context.get("activeWebviewPanelId"), Some(&json!("preview")));

        request("$disposeWebview", vec![json!("h1")], cx);
        assert!(workbench.read_with(cx, |workbench, _| workbench.webview_panels.panels.is_empty()));
        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" })]);
        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]
    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();
        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 dir = std::env::temp_dir().join(format!("code-gpui-webview-read-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("a.css"), "body {}").unwrap();
        // With no extension host the file service's reads run on the disk.
        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 read = |name: &str, cx: &mut gpui::VisualTestContext| {
            let answer = std::rc::Rc::new(std::cell::RefCell::new(None));
            let respond = Box::new({
                let answer = answer.clone();
                move |bytes: Option<Vec<u8>>| *answer.borrow_mut() = Some(bytes)
            });
            let read = crate::webview::ResourceRead { resource: files::Resource::file(dir.join(name).to_string_lossy()), respond };
            let events = workbench.update_in(cx, |workbench, window, cx| workbench.webview_events(window, cx));
            events.unbounded_send(WebviewEvent { id: "h1".into(), channel: "load-resource".into(), data: Value::Null, read: Some(read) }).unwrap();
            cx.run_until_parked();
            answer.take()
        };
        assert_eq!(read("a.css", cx), Some(Some(b"body {}".to_vec())));
        assert_eq!(read("missing.css", cx), Some(None), "a failed read answers, so the load gets its 404");
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[gpui::test]
    fn panels_with_a_serializer_are_restored_from_the_editor_state(cx: &mut gpui::TestAppContext) {
        const EDITOR_PART_KEY: &str = "memento/workbench.parts.editor";
        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 (sender, host) = std::sync::mpsc::channel();
        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(sender), cx));
        let request = |method: &str, args: Vec<Value>, cx: &mut gpui::VisualTestContext| workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_webview_request(method, &args, window, cx)));
        let sent = |method: &str| host.try_iter().filter(|message| message.method == method).map(|message| message.args).collect::<Vec<_>>();
        let init = json!({ "title": "Preview", "panelOptions": { "enableFindWidget": true }, "webviewOptions": { "enableScripts": true } });
        request("$createWebviewPanel", vec![json!({ "id": "ext" }), json!("h1"), json!("preview"), init.clone(), json!({})], cx);
        workbench.update(cx, |workbench, _| workbench.webview_panels.panels[0].state = json!("{\"page\":2}"));

        // Without a serializer the panel is not kept.
        let saved = workbench.update(cx, |workbench, _| {
            workbench.save_editor_part_state();
            workbench.workspace_storage.lock().unwrap().get(EDITOR_PART_KEY).unwrap().to_owned()
        });
        request("$disposeWebview", vec![json!("h1")], cx);
        workbench.update(cx, |workbench, _| {
            workbench.workspace_storage.lock().unwrap().set(EDITOR_PART_KEY, saved);
            workbench.restore_editor_part_state();
        });
        assert!(workbench.read_with(cx, |workbench, _| workbench.editors.editors.is_empty()));

        request("$createWebviewPanel", vec![json!({ "id": "ext" }), json!("h2"), json!("preview"), init, json!({})], cx);
        workbench.update(cx, |workbench, _| workbench.webview_panels.panels[0].state = json!("{\"page\":2}"));
        request("$registerSerializer", vec![json!("preview")], cx);
        // The state a window closing with the panel leaves, read by the next window on that workspace.
        let saved = workbench.update(cx, |workbench, _| {
            workbench.save_editor_part_state();
            workbench.workspace_storage.lock().unwrap().get(EDITOR_PART_KEY).unwrap().to_owned()
        });
        request("$disposeWebview", vec![json!("h2")], cx);
        request("$unregisterSerializer", vec![json!("preview")], cx);
        workbench.update(cx, |workbench, _| workbench.workspace_storage.lock().unwrap().set(EDITOR_PART_KEY, saved));
        drop(sent(""));

        // The restored editor shows: its extension activates, and once the serializer registers the host fills it in.
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.restore_editor_part_state();
            workbench.update_webview_panels(window, cx);
        });
        assert_eq!(workbench.read_with(cx, |workbench, _| workbench.webview_title(&workbench.editors.active().unwrap().document().path)), Some("Preview".into()));
        assert!(sent("$activateByEvent").iter().any(|args| args[0] == "onWebviewPanel:preview"));
        request("$registerSerializer", vec![json!("preview")], cx);
        workbench.update_in(cx, |workbench, window, cx| workbench.update_webview_panels(window, cx));
        let deserialize = sent("$deserializeWebviewPanel");
        assert_eq!(deserialize.len(), 1);
        let handle = workbench.read_with(cx, |workbench, _| workbench.webview_panels.panels[0].handle.clone());
        assert_eq!(deserialize[0], vec![json!(handle), json!("preview"), json!({ "title": "Preview", "state": { "page": 2 }, "panelOptions": { "enableFindWidget": true, "retainContextWhenHidden": false }, "webviewOptions": { "enableScripts": true, "enableFindWidget": true, "retainContextWhenHidden": false }, "active": true }), json!(0)]);
    }

    #[test]
    fn reads_resource_roots_and_stable_origins() {
        let options = json!({ "localResourceRoots": [{ "scheme": "file", "path": "/a" }, { "scheme": "vscode-vfs", "authority": "github", "path": "/b" }] });
        let roots = local_resource_roots(&options);
        assert_eq!(roots.iter().map(|root| (root.scheme.as_str(), root.authority.as_str(), root.path.as_str())).collect::<Vec<_>>(), [("file", "", "/a"), ("vscode-vfs", "github", "/b")]);
        assert_eq!(webview_origin("t", "e"), webview_origin("t", "e"));
        assert_ne!(webview_origin("t", "e"), webview_origin("u", "e"));
        assert_eq!(webview_origin("t", "e").len(), 36);
    }

    // mainThreadWebviews.ts `onDidClickLink` opens with `fromWorkspace`: an allowed command link of an untrusted
    // workspace asks for trust before it runs.
    #[gpui::test]
    fn a_webview_command_link_asks_for_workspace_trust(cx: &mut gpui::TestAppContext) {
        use std::sync::{Arc, Mutex};

        use crate::workspace_trust::{Startup, WorkspaceTrust};

        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let theme = crate::theme::load_theme(&[exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
        let (workbench, cx) = cx.add_window_view(|_, cx| {
            let mut workbench = 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 mut storage = storage::Storage::in_memory();
            let startup = Startup { enabled: true, workspace: None, empty_window_trusted: false, workspace_storage: &mut storage };
            workbench.workspace_trust = WorkspaceTrust::new(Arc::new(Mutex::new(storage::Storage::in_memory())), startup);
            workbench
        });
        workbench.update_in(cx, |workbench, window, cx| workbench.open_webview_link("command:workbench.action.togglePanel", &json!(true), window, cx));
        cx.run_until_parked();
        assert_eq!(workbench.read_with(cx, |workbench, _| workbench.dialogs.len()), 1, "the trust request shows");
        workbench.update(cx, |workbench, cx| workbench.close_custom_dialog(2, cx));
        cx.run_until_parked();
        assert!(!workbench.read_with(cx, |workbench, _| workbench.workspace_trust.is_trusted()));
    }
}