Skip to content

Visual Studio Code, rebuilt in Rust

Rust
9.5 KB
Raw Blame
//! mainThreadWebviewViews.ts with contrib/webviewView: the webview views extensions contribute (`type: webview`), panes of
//! their containers like the tree views (tree_view.rs), whose webview lives in the webview panels' list (handled by the
//! same MainThreadWebviews calls), resolved once the pane first shows and its provider is registered.

use std::collections::HashMap;
use std::path::PathBuf;

use gpui::{Context, Window, prelude::*};
use serde_json::{Value, json};

use super::Workbench;
use super::view_panes::ViewPane;
use super::webview_panels::WebviewPanel;
use crate::commands::Outcome;
use crate::menus::MenuId;

/// The scheme of a webview view's entry in the webview panels' list; its path is the view id.
pub const WEBVIEW_VIEW_SCHEME: &str = "webview-view";
/// webviewViewPane.ts `storageKeys.webviewState`.
const WEBVIEW_STATE_KEY: &str = "webviewState";

#[derive(Default)]
pub struct WebviewViews {
    /// `$registerWebviewViewProvider`: the extension and the `retainContextWhenHidden` option, by view type.
    providers: HashMap<String, (Value, bool)>,
    /// Each contributed view's pane, by view id.
    panes: HashMap<String, Pane>,
    next_handle: u64,
}

#[derive(Default)]
struct Pane {
    /// `$setWebviewViewTitle`, shown in place of the contributed name.
    title: Option<String>,
    description: Option<String>,
    /// `$setWebviewViewBadge` (`{ value, tooltip }`), shown on its container's activity bar item.
    badge: Option<Value>,
    /// Set once `$resolveWebviewView` is sent; the webview is the panel entry with this handle.
    handle: Option<String>,
    /// The body visibility the extension host last heard.
    visible: bool,
}

impl Workbench {
    pub(crate) fn handle_webview_views_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 text = |value: Value| value.as_str().map(str::to_owned);
        match method {
            "$registerWebviewViewProvider" => {
                let view_type = text(arg(1)).unwrap_or_default();
                let retain = arg(2)["retainContextWhenHidden"] == true;
                self.webview_views.providers.insert(view_type, (arg(0), retain));
                cx.notify();
            }
            "$unregisterWebviewViewProvider" => {
                self.webview_views.providers.remove(arg(0).as_str().unwrap_or_default());
            }
            "$setWebviewViewTitle" | "$setWebviewViewDescription" => {
                let handle = arg(0);
                let Some(pane) = self.webview_views.panes.values_mut().find(|pane| pane.handle.as_deref() == handle.as_str()) else { return Outcome::done() };
                match method {
                    "$setWebviewViewTitle" => pane.title = text(arg(1)),
                    _ => pane.description = text(arg(1)),
                }
                cx.notify();
            }
            "$show" => self.show_webview_view(arg(0).as_str().unwrap_or_default(), arg(1) == true, window, cx),
            // webviewViewPane.ts `updateBadge`: `showViewActivity` puts the badge on the view's container.
            "$setWebviewViewBadge" => {
                let handle = arg(0);
                let Some(pane) = self.webview_views.panes.values_mut().find(|pane| pane.handle.as_deref() == handle.as_str()) else { return Outcome::done() };
                pane.badge = Some(arg(1)).filter(|badge| !badge.is_null());
                cx.notify();
            }
            _ => {}
        }
        Outcome::done()
    }

    /// webviewViewPane.ts `show`: `viewsService.openView`, which opens the Explorer and expands the pane.
    fn show_webview_view(&mut self, handle: &str, preserve_focus: bool, window: &mut Window, cx: &mut Context<Self>) {
        let Some(view_id) = self.webview_views.panes.iter().find(|(_, pane)| pane.handle.as_deref() == Some(handle)).map(|(id, _)| id.clone()) else { return };
        self.open_webview_view(&view_id, preserve_focus, window, cx);
    }

    /// `viewsService.openView`: shows the view's container and expands its pane.
    pub(super) fn open_webview_view(&mut self, view_id: &str, preserve_focus: bool, window: &mut Window, cx: &mut Context<Self>) {
        self.open_tree_view(view_id, !preserve_focus, window, cx);
    }

    /// The focus of `openView(id, true)`: the resolved webview; a pane not resolved yet takes the focus once its webview exists.
    pub(super) fn focus_webview_view(&mut self, view_id: &str, window: &mut Window, cx: &mut Context<Self>) {
        match self.webview_views.panes.get(view_id).and_then(|pane| pane.handle.clone()) {
            Some(handle) => self.focus_webview_panel(&handle, window, cx),
            None => self.update_webview_panels(window, cx),
        }
    }

    /// Runs before the webview panels update each render (webviewViewPane.ts `updateTreeVisibility`): a pane whose body
    /// shows activates `onView:<id>` and is resolved once its provider is there; the host hears visibility changes.
    pub(super) fn update_webview_views(&mut self) {
        let views: Vec<_> = self.tree_views.views.iter().filter(|view| view.webview).map(|view| (view.id, view.name.clone(), self.tree_view_body_visible(view.id))).collect();
        for (id, name, visible) in views {
            let pane = self.webview_views.panes.entry(id.to_owned()).or_default();
            if let Some(handle) = &pane.handle
                && pane.visible != visible
            {
                self.host.send("ExtHostWebviewViews", "$onDidChangeWebviewViewVisibility", vec![json!(handle), json!(visible)]);
            }
            pane.visible = visible;
            if visible && pane.handle.is_none() {
                self.resolve_webview_view(id, name);
            }
        }
    }

    /// webviewViewPane.ts `activate`, then mainThreadWebviewViews.ts `resolve`.
    fn resolve_webview_view(&mut self, id: &str, name: String) {
        drop(self.host.activate_by_event(&format!("onView:{id}")));
        let Some((extension, retain)) = self.webview_views.providers.get(id).cloned() else { return };
        self.webview_views.next_handle += 1;
        let handle = format!("webview-view-{}", self.webview_views.next_handle);
        let state_key = view_state_key(id);
        let memento = self.workspace_storage.lock().unwrap().get(&state_key).and_then(|text| serde_json::from_str::<Value>(text).ok());
        let state = memento.map_or(Value::Null, |memento| memento[WEBVIEW_STATE_KEY].clone());
        let pane = self.webview_views.panes.get_mut(id).expect("the pane of a contributed view");
        pane.handle = Some(handle.clone());
        let mut panel = WebviewPanel::new(handle.clone(), WEBVIEW_VIEW_SCHEME.into(), PathBuf::from(id), id, name, &extension, json!({}), retain, None);
        panel.state = state.clone();
        self.webview_panels.panels.push(panel);
        let parsed = state.as_str().and_then(|text| serde_json::from_str(text).ok()).unwrap_or(Value::Null);
        let title = pane.title.clone().map_or(Value::Null, Value::String);
        self.host.send("ExtHostWebviewViews", "$resolveWebviewView", vec![json!(handle), json!(id), title, parsed]);
    }

    /// The webview view whose webview has the keyboard: its pane is the focused view.
    pub(super) fn focused_webview_view(&self) -> Option<&'static str> {
        let panel = self.webview_panels.panels.iter().find(|panel| panel.scheme == WEBVIEW_VIEW_SCHEME && panel.focused)?;
        Some(super::tree_view::static_id(&panel.view_type))
    }

    /// The `$setWebviewViewBadge` value of a webview view.
    pub(super) fn webview_view_badge(&self, view_id: &str) -> Option<&Value> {
        self.webview_views.panes.get(view_id)?.badge.as_ref()
    }

    /// The view ids whose pane body shows, as the paths of their webview panel entries.
    pub(super) fn visible_webview_views(&self) -> Vec<PathBuf> {
        self.webview_views.panes.iter().filter(|(_, pane)| pane.visible).map(|(id, _)| PathBuf::from(id)).collect()
    }

    /// webviewViewPane.ts `onDidUpdateState`: the webview's `vscode.setState` text, in the view's workspace memento.
    pub(super) fn save_webview_view_state(&mut self, view_id: &str, state: &Value) {
        let memento = json!({ WEBVIEW_STATE_KEY: state });
        self.workspace_storage.lock().unwrap().set(&view_state_key(view_id), memento.to_string());
    }

    /// webviewViewPane.ts: the view's title (`$setWebviewViewTitle`, else its `name`), description, title actions
    /// and the box its webview is placed over.
    pub(super) fn webview_view_pane(&self, id: &'static str, name: String, window: &Window, cx: &mut Context<Self>) -> ViewPane {
        let pane = self.webview_views.panes.get(id);
        let mut context = self.key_context(window);
        context.insert("view".into(), json!(id));
        // paneCompositePart.css: 4px after each title action.
        let actions = self.inline_actions(MenuId::ViewTitle, Some(id), &context, Vec::new(), self.foreground_or("sideBar.foreground"), cx).gap(gpui::px(4.)).into_any_element();
        let handle = pane.and_then(|pane| pane.handle.as_deref());
        ViewPane {
            id,
            title: pane.and_then(|pane| pane.title.clone()).unwrap_or(name),
            description: pane.and_then(|pane| pane.description.clone()),
            actions: Some(actions),
            draws_more: false,
            show_actions: self.focused_webview_view() == Some(id),
            body: self.webview_body(|panel| Some(panel.handle.as_str()) == handle).into_any_element(),
        }
    }
}

fn view_state_key(view_id: &str) -> String {
    format!("memento/webviewView.{view_id}")
}

#[cfg(test)]
mod tests;