Skip to content

Visual Studio Code, rebuilt in Rust

Rust
42.8 KB
Raw Blame
//! platform/webview: the host page (src/vs/workbench/contrib/webview/browser/pre/index.html) and what the workbench
//! answers it, shared by the native views: a WKWebView on macOS (`macos.rs`), a WebKitGTK view on Linux (`linux.rs`), a
//! WebView2 on Windows (`windows.rs`). Each `Native` creates, places and focuses its view and hands requests and
//! messages to `Resources`; everything else is here.

use std::cell::RefCell;
use std::path::{Component, Path, PathBuf};
use std::rc::Rc;

use futures::channel::mpsc::UnboundedSender;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};

use crate::theme::{Theme, ThemeKind};

#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "linux")]
use linux::Native;
#[cfg(target_os = "linux")]
pub use linux::{ClipView, Retained, View, gpui_x_window, pump_gtk, place, supported};
#[cfg(target_os = "macos")]
use macos::Native;
#[cfg(target_os = "macos")]
pub use macos::{ClipView, Retained, View, place, supported};
#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "windows")]
use windows::Native;
#[cfg(target_os = "windows")]
pub use windows::{ClipView, Retained, View, place, supported};

/// common/webview.ts `webviewRootResourceAuthority`.
const RESOURCE_AUTHORITY: &str = "vscode-resource.vscode-cdn.net";
/// The host page's site; index.html only checks that the hostname starts with the parent origin hash.
const HOST_SITE: &str = "vscode-webview.vscode-cdn.net";
/// `window.origin` of the Electron workbench, which index.html hashes into the host name.
const PARENT_ORIGIN: &str = "vscode-file://vscode-app";
const MESSAGE_HANDLER: &str = "vscodeWebviewHost";
/// WebKit blocks every http load in the https host page, loopback included, where Chromium lets loopback through (the
/// Simple Browser's dev servers). With `http` registered secure, these content rules block the rest: http stays loopback
/// only. A rule ends at `(:port)?/` so `http://localhost:[email protected]/` (a user name) does not match. WebView2 is Chromium.
#[cfg(not(target_os = "windows"))]
const HTTP_LOOPBACK_ONLY_RULES: &str = r#"[
    { "trigger": { "url-filter": "^http:" }, "action": { "type": "block" } },
    { "trigger": { "url-filter": "^http://localhost(:[0-9]+)?/" }, "action": { "type": "ignore-previous-rules" } },
    { "trigger": { "url-filter": "^http://[^/:@]*\\.localhost(:[0-9]+)?/" }, "action": { "type": "ignore-previous-rules" } },
    { "trigger": { "url-filter": "^http://127\\.[0-9.]+(:[0-9]+)?/" }, "action": { "type": "ignore-previous-rules" } },
    { "trigger": { "url-filter": "^http://\\[::1\\](:[0-9]+)?/" }, "action": { "type": "ignore-previous-rules" } }
]"#;

/// What the host page sends the workbench: the `FromWebviewMessage` channels of webviewMessages.d.ts, and
/// `webview-ready` once the page handed over its port.
#[derive(Debug)]
pub struct WebviewEvent {
    pub id: String,
    pub channel: String,
    pub data: Value,
    /// `load-resource` of a resource the disk does not hold: the workbench reads it through the file service.
    pub read: Option<ResourceRead>,
}

/// webviewElement.ts `loadResource` of an extension file system provider's resource: `respond` gets its bytes, or
/// `None` when the read failed.
pub struct ResourceRead {
    pub resource: files::Resource,
    pub respond: Box<dyn FnOnce(Option<Vec<u8>>)>,
}

impl std::fmt::Debug for ResourceRead {
    fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.debug_struct("ResourceRead").field("resource", &self.resource).finish_non_exhaustive()
    }
}

pub struct Webview {
    native: Native,
    resources: Rc<Resources>,
    /// Messages for the host page before it posted `webview-ready`, sent in order once it has.
    pending: Option<Vec<String>>,
}

impl Webview {
    /// A hidden webview over `window` loading the host page; `origin` is the webview's `this.origin`, the salt of its host name.
    pub fn new(window: &gpui::Window, id: &str, origin: &str, extension_id: &str, pre_dir: PathBuf, roots: Vec<files::Resource>, events: UnboundedSender<WebviewEvent>) -> Self {
        let resources = Rc::new(Resources { id: id.to_string(), pre_dir, roots: RefCell::new(roots), events });
        let native = Native::new(window, resources.clone(), host_page_url(id, origin, extension_id));
        Webview { native, resources, pending: Some(Vec::new()) }
    }

    /// `webviewElement.ts` `_send`: posts `{ channel, args }` on the host page's port.
    pub fn send(&mut self, channel: &str, data: Value) {
        let script = format!("globalThis.__vscodeWebviewHost.post({}, {})", json!(channel), data);
        match &mut self.pending {
            Some(pending) => pending.push(script),
            None => self.native.evaluate(&script),
        }
    }

    /// The host page posted `webview-ready`: messages queued before go out now.
    pub fn did_become_ready(&mut self) {
        for script in self.pending.take().unwrap_or_default() {
            self.native.evaluate(&script);
        }
    }

    pub fn set_local_resource_roots(&self, roots: Vec<files::Resource>) {
        *self.resources.roots.borrow_mut() = roots;
    }

    /// The native view, for `place` from a paint callback.
    pub fn view(&self) -> View {
        self.native.view()
    }

    pub fn hide(&self) {
        self.native.hide();
    }

    /// `webviewElement.ts` `focus`: the view takes the keyboard and the host page focuses its content frame.
    pub fn focus(&mut self) {
        self.native.take_keyboard();
        self.send("focus", Value::Null);
    }

    /// `webviewElement.ts` `cut`, `copy`, `paste`. WebView2's Chromium runs the host page's `execCommand` as Electron's
    /// does; WebKit's needs clipboard access that every page in the webview would get, so it runs its own command.
    pub fn clipboard_command(&mut self, command: &str) {
        self.native.take_keyboard();
        #[cfg(target_os = "windows")]
        self.send("execCommand", json!(command));
        #[cfg(not(target_os = "windows"))]
        self.native.clipboard_command(command);
    }

    /// Gives the view the keyboard, as a click into it does.
    pub fn take_keyboard(&self) {
        self.native.take_keyboard();
    }

    /// Gives the keyboard back to GPUI's window.
    pub fn release_keyboard(&self) {
        self.native.release_keyboard();
    }

    pub fn has_keyboard(&self) -> bool {
        self.native.has_keyboard()
    }

    /// webviewFindWidget.ts `reveal`: the find widget over the host page's top right, its input focused. `styles` is
    /// `theme_data`; `icons` the arrow-up, arrow-down and close codicons as SVG markup.
    pub fn show_find(&self, styles: &Value, icons: [String; 3]) {
        self.native.take_keyboard();
        self.native.evaluate(&format!("({FIND_SCRIPT})({styles}, {}).show()", json!(icons)));
    }

    pub fn hide_find(&self) {
        self.native.evaluate("globalThis.__vscodeFind?.hide()");
    }

    /// `WebviewFindWidget.find`: the next or previous match of the widget's text.
    pub fn find(&self, previous: bool) {
        self.native.evaluate(&format!("globalThis.__vscodeFind?.find({previous})"));
    }

    /// The engine's own developer tools, as the Electron webview's.
    pub fn open_inspector(&self) {
        self.native.open_inspector();
    }
}

type Response = (u16, Vec<(&'static str, String)>, Vec<u8>);

/// What one webview's request and message handlers answer with.
struct Resources {
    id: String,
    /// src/vs/workbench/contrib/webview/browser/pre, the host page's files.
    pre_dir: PathBuf,
    roots: RefCell<Vec<files::Resource>>,
    /// Where host page messages go, and resources of extension file system providers are asked for.
    events: UnboundedSender<WebviewEvent>,
}

impl Resources {
    /// A `{ channel, data }` text the bridge script posted to the native message handler.
    fn receive(&self, text: &str) {
        if let Some(event) = host_message(&self.id, text) {
            let _ = self.events.unbounded_send(event);
        }
    }

    /// What the service worker answers upstream for an `https` request: the host page's files, and resources as
    /// webviewElement.ts `loadResource` with resourceLoading.ts `loadLocalResource` read them, a `file` one here,
    /// another scheme's through the workbench's file service, where extension file system providers answer. `respond`
    /// gets the answer now or once the file service read it; `false` for another host, which goes to the network.
    fn serve(&self, host: &str, path: &str, query: &str, range: Option<String>, respond: impl FnOnce(Response) + 'static) -> bool {
        if is_subdomain(host, HOST_SITE) {
            let name = path.trim_start_matches('/');
            // `join` puts a drive (`C:/`) or UNC path in place of pre_dir: only plain names stay inside it.
            let inside = Path::new(name).components().all(|component| matches!(component, Component::Normal(_)));
            let file = self.pre_dir.join(name);
            respond(match inside.then(|| std::fs::read(&file)) {
                Some(Ok(bytes)) => (200, vec![("Content-Type", mime_type(&file).to_string())], bytes),
                _ => (404, Vec::new(), Vec::new()),
            });
            return true;
        }
        if !is_subdomain(host, RESOURCE_AUTHORITY) {
            return false;
        }
        let Some(resource) = resource_uri(host, path, query) else {
            respond((404, Vec::new(), Vec::new()));
            return true;
        };
        if !is_contained(&resource, &self.roots.borrow()) {
            respond((401, Vec::new(), Vec::new()));
            return true;
        }
        if resource.scheme == "file" {
            let bytes = std::fs::read(crate::uri::fs_path(&resource.scheme, &resource.authority, &resource.path)).ok();
            respond(resource_response(&resource.path, bytes, range.as_deref()));
            return true;
        }
        let path = resource.path.clone();
        let respond = Box::new(move |bytes: Option<Vec<u8>>| respond(resource_response(&path, bytes, range.as_deref())));
        let read = ResourceRead { resource, respond };
        let _ = self.events.unbounded_send(WebviewEvent { id: self.id.clone(), channel: "load-resource".into(), data: Value::Null, read: Some(read) });
        true
    }
}

fn is_subdomain(host: &str, site: &str) -> bool {
    host.strip_suffix(site).is_some_and(|rest| rest.ends_with('.'))
}

/// base/browser/iframe.ts `parentOriginHash`: SHA-256 of `{"parentOrigin":…,"salt":…}` in base 32, 52 digits.
pub fn parent_origin_hash(parent_origin: &str, salt: &str) -> String {
    let data = json!({ "parentOrigin": parent_origin, "salt": salt }).to_string();
    let digest = Sha256::digest(data.as_bytes());
    // 52 base-32 digits hold 260 bits; the 256-bit hash fills them from the low end, as BigInt.toString(32).padStart does.
    let mut digits = Vec::with_capacity(52);
    for index in 0..52 {
        let bit = index * 5;
        let mut value = 0u8;
        for offset in 0..5 {
            let position = bit + offset;
            if position < 256 && digest[31 - position / 8] >> (position % 8) & 1 == 1 {
                value |= 1 << offset;
            }
        }
        digits.push(char::from_digit(value.into(), 32).unwrap());
    }
    digits.iter().rev().collect()
}

fn query_escape(value: &str) -> String {
    let mut out = String::new();
    for byte in value.bytes() {
        match byte {
            b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'*' => out.push(byte as char),
            _ => out.push_str(&format!("%{byte:02X}")),
        }
    }
    out
}

/// The lowercase host and the percent-decoded path and query of an `https` URL, as NSURL's `host`, `path` and `query`
/// give them to macos.rs.
#[cfg(any(target_os = "windows", test))]
fn https_url_parts(url: &str) -> Option<(String, String, String)> {
    let rest = url.strip_prefix("https://")?;
    let rest = rest.split_once('#').map_or(rest, |(rest, _)| rest);
    let (host, target) = rest.find(['/', '?']).map_or((rest, ""), |index| rest.split_at(index));
    let (path, query) = target.split_once('?').unwrap_or((target, ""));
    let path = if path.is_empty() { "/" } else { path };
    Some((host.to_ascii_lowercase(), crate::uri::percent_decode(path), crate::uri::percent_decode(query)))
}

/// The resource an `asWebviewUri` URL names, `https://{scheme}+{authority}.vscode-resource.vscode-cdn.net{path}`,
/// with the authority as webview.ts `decodeAuthority` restores it.
pub fn resource_uri(host: &str, decoded_path: &str, decoded_query: &str) -> Option<files::Resource> {
    let authority = host.strip_suffix(RESOURCE_AUTHORITY)?.strip_suffix('.')?;
    let (scheme, encoded_authority) = authority.split_once('+')?;
    Some(files::Resource { scheme: scheme.to_owned(), authority: decode_authority(encoded_authority), path: decoded_path.to_owned(), query: decoded_query.to_owned() })
}

/// webview.ts `decodeAuthority`: each `-` and four hex digits is the character of that code.
fn decode_authority(encoded: &str) -> String {
    let mut decoded = String::new();
    let mut rest = encoded;
    while let Some(index) = rest.find('-') {
        decoded.push_str(&rest[..index]);
        let digits = rest.get(index + 1..index + 5).filter(|digits| digits.bytes().all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')));
        match digits.and_then(|digits| char::from_u32(u32::from_str_radix(digits, 16).ok()?)) {
            Some(character) => {
                decoded.push(character);
                rest = &rest[index + 5..];
            }
            None => {
                decoded.push('-');
                rest = &rest[index + 1..];
            }
        }
    }
    decoded + rest
}

/// Local resource roots of folders on the disk.
pub fn file_roots(paths: &[PathBuf]) -> Vec<files::Resource> {
    let resource = |uri: crate::uri::Uri| files::Resource { scheme: uri.scheme, authority: uri.authority, path: uri.path, query: String::new() };
    paths.iter().map(|path| resource(crate::uri::Uri::file(&path.to_string_lossy()))).collect()
}

/// resourceLoading.ts containment: the resource, without its query and `..` escapes, under a root of its scheme and
/// authority; a `file` resource also as resolved. Extension file system providers have no realpath, so theirs is the
/// lexical check only, and `vscode-remote` is denied without a remote connection.
pub fn is_contained(resource: &files::Resource, roots: &[files::Resource]) -> bool {
    is_contained_on(resource, roots, cfg!(windows))
}

/// The containment on Windows or elsewhere: `file` paths as `fsPath` gives them, compared ignoring case on Windows
/// (uriIdentityService's `extUri` for a file system without `PathCaseSensitive`).
fn is_contained_on(resource: &files::Resource, roots: &[files::Resource], windows: bool) -> bool {
    let separators: &[char] = if windows { &['/', '\\'] } else { &['/'] };
    let fs_path = |resource: &files::Resource| match resource.scheme.as_str() {
        "file" => crate::uri::fs_path_on(&resource.scheme, &resource.authority, &resource.path, windows),
        _ => resource.path.clone(),
    };
    let comparable = |path: &str| if windows && resource.scheme == "file" { path.to_lowercase() } else { path.to_owned() };
    let path = fs_path(resource);
    if resource.scheme == "vscode-remote" || path.split(separators).any(|segment| segment == "..") {
        return false;
    }
    let under = |root: &str| {
        let (path, root) = (comparable(&path), comparable(root));
        let root = root.trim_end_matches(separators);
        path == root || path.strip_prefix(root).is_some_and(|rest| rest.starts_with(separators))
    };
    let Some(root) = roots.iter().find(|root| root.scheme == resource.scheme && root.authority.eq_ignore_ascii_case(&resource.authority) && under(&fs_path(root))) else { return false };
    if resource.scheme != "file" {
        return true;
    }
    // The file service's read refuses the host (diskFileSystemProvider.ts), before canonicalize reaches it.
    if files::unc::check_unc_access(Path::new(&path)).is_err() {
        return false;
    }
    match (std::fs::canonicalize(&path), std::fs::canonicalize(fs_path(root))) {
        (Ok(real), Ok(real_root)) => real.starts_with(real_root),
        _ => true,
    }
}

/// platform/webview/common/mimeTypes.ts `getWebviewContentMimeType`.
pub fn mime_type(path: &Path) -> &'static str {
    let extension = path.extension().and_then(|extension| extension.to_str()).map(str::to_ascii_lowercase).unwrap_or_default();
    match extension.as_str() {
        "svg" => "image/svg+xml",
        "txt" => "text/plain",
        "css" => "text/css",
        "js" | "cjs" | "mjs" => "application/javascript",
        "json" => "application/json",
        "html" | "htm" => "text/html",
        "xhtml" => "application/xhtml+xml",
        "oft" | "otf" => "font/otf",
        "xml" => "application/xml",
        "wasm" => "application/wasm",
        // base/common/mime.ts `mapExtToMediaMimes`.
        "aac" => "audio/x-aac",
        "avi" => "video/x-msvideo",
        "avif" => "image/avif",
        "bmp" => "image/bmp",
        "flv" => "video/x-flv",
        "gif" => "image/gif",
        "ico" => "image/x-icon",
        "jpe" | "jpeg" | "jpg" => "image/jpg",
        "m1v" | "m2v" | "mpe" | "mpeg" | "mpg" => "video/mpeg",
        "m2a" | "m3a" | "mp2" | "mp2a" | "mp3" | "mpga" => "audio/mpeg",
        "mid" | "midi" => "audio/midi",
        "mk3d" | "mks" | "mkv" => "video/x-matroska",
        "mov" | "qt" => "video/quicktime",
        "movie" => "video/x-sgi-movie",
        "mp4" | "mp4v" | "mpg4" => "video/mp4",
        "mp4a" => "audio/mp4",
        "oga" | "ogg" | "spx" => "audio/ogg",
        "opus" => "audio/opus",
        "ogv" => "video/ogg",
        "pdf" => "application/pdf",
        "png" => "image/png",
        "psd" => "image/vnd.adobe.photoshop",
        "tga" => "image/x-tga",
        "tif" | "tiff" => "image/tiff",
        "ttf" => "font/ttf",
        "wav" => "audio/x-wav",
        "webm" => "video/webm",
        "webp" => "image/webp",
        "wma" => "audio/x-ms-wma",
        "wmv" => "video/x-ms-wmv",
        "woff" => "application/font-woff",
        "woff2" => "font/woff2",
        _ => "application/unknown",
    }
}

/// The host page's URL, with the query webviewElement.ts `_initElement` gives the iframe.
fn host_page_url(id: &str, origin: &str, extension_id: &str) -> String {
    let params = [
        ("id", id),
        ("parentId", "1"),
        ("origin", origin),
        ("swVersion", "1"),
        ("extensionId", extension_id),
        ("platform", "electron"),
        ("vscode-resource-base-authority", RESOURCE_AUTHORITY),
        ("parentOrigin", PARENT_ORIGIN),
        ("mountId", id),
        ("disableServiceWorker", "true"),
    ];
    let query: Vec<String> = params.iter().map(|(key, value)| format!("{key}={}", query_escape(value))).collect();
    format!("https://{}.{HOST_SITE}/index.html?{}", parent_origin_hash(PARENT_ORIGIN, origin), query.join("&"))
}

/// A `{ channel, data }` the bridge script posted to the native message handler, as the event of webview `id`.
fn host_message(id: &str, text: &str) -> Option<WebviewEvent> {
    let Ok(Value::Object(mut message)) = serde_json::from_str(text) else { return None };
    let channel = message.remove("channel").and_then(|channel| channel.as_str().map(str::to_string)).unwrap_or_default();
    let data = message.remove("data").unwrap_or(Value::Null);
    Some(WebviewEvent { id: id.to_string(), channel, data, read: None })
}

/// The answer to a resource load: 404 when the read failed, else the bytes or the byte range asked for.
fn resource_response(path: &str, bytes: Option<Vec<u8>>, range: Option<&str>) -> (u16, Vec<(&'static str, String)>, Vec<u8>) {
    let Some(bytes) = bytes else { return (404, Vec::new(), Vec::new()) };
    // service-worker.js answers with these headers; media elements ask for byte ranges.
    let mut headers = vec![("Content-Type", mime_type(Path::new(path)).to_string()), ("Access-Control-Allow-Origin", "*".to_string()), ("Cache-Control", "no-cache".to_string())];
    let Some((start, end)) = range.and_then(|range| byte_range(range, bytes.len() as u64)) else {
        return (200, headers, bytes);
    };
    headers.push(("Content-Range", format!("bytes {start}-{end}/{}", bytes.len())));
    headers.push(("Accept-Ranges", "bytes".to_string()));
    (206, headers, bytes[start as usize..=end as usize].to_vec())
}

/// A `Range: bytes=start-end` header over `len` bytes, as the inclusive byte range to send.
pub fn byte_range(header: &str, len: u64) -> Option<(u64, u64)> {
    let (start, end) = header.strip_prefix("bytes=")?.split_once('-')?;
    let start: u64 = start.trim().parse().ok()?;
    let end = match end.trim() {
        "" => len.checked_sub(1)?,
        end => end.parse::<u64>().ok()?.min(len.checked_sub(1)?),
    };
    (start <= end).then_some((start, end))
}

/// themeing.ts `getWebviewThemeData`: the `styles` message of the host page.
pub fn theme_data(theme: &Theme, theme_label: &str, editor: &Value, underline_links: bool, reduce_motion: bool) -> Value {
    let mut styles = serde_json::Map::new();
    let font = |key: &str| editor[key].as_str().filter(|value| !value.is_empty()).map(str::to_string);
    styles.insert("vscode-font-family".into(), json!("-apple-system, BlinkMacSystemFont, sans-serif"));
    styles.insert("vscode-font-weight".into(), json!("normal"));
    styles.insert("vscode-font-size".into(), json!("13px"));
    styles.insert("vscode-editor-font-family".into(), json!(font("fontFamily").unwrap_or("Menlo, Monaco, 'Courier New', monospace".into())));
    styles.insert("vscode-editor-font-weight".into(), json!(font("fontWeight").unwrap_or("normal".into())));
    let font_size = editor["fontSize"].as_f64().filter(|size| *size != 0.).unwrap_or(12.);
    styles.insert("vscode-editor-font-size".into(), json!(format!("{font_size}px")));
    styles.insert("text-link-decoration".into(), json!(if underline_links { "underline" } else { "none" }));
    for id in include_str!("webview/color_ids.txt").lines() {
        if let Some(color) = theme.color(id) {
            // colorUtils.ts `asCssVariableName`: every dot.
            styles.insert(format!("vscode-{}", id.replace('.', "-")), json!(css_color(color)));
        }
    }
    for (id, value) in SIZES {
        styles.insert(format!("vscode-{}", id.replace('.', "-")), json!(value));
    }
    styles.insert("vscode-editor-font-feature-settings".into(), json!(font_ligatures(&editor["fontLigatures"])));
    let active_theme = match theme.kind {
        ThemeKind::Light => "vscode-light",
        ThemeKind::Dark => "vscode-dark",
        ThemeKind::HighContrastDark => "vscode-high-contrast",
        ThemeKind::HighContrastLight => "vscode-high-contrast-light",
    };
    json!({ "styles": styles, "activeTheme": active_theme, "themeId": theme.settings_id, "themeLabel": theme_label, "reduceMotion": reduce_motion, "screenReader": false })
}

/// editorOptions.ts `EditorFontLigatures.validate`.
fn font_ligatures(value: &Value) -> String {
    match value {
        Value::String(text) if text == "false" => "\"liga\" off, \"calt\" off".into(),
        Value::String(text) if text == "true" => "\"liga\" on, \"calt\" on".into(),
        Value::String(text) => text.clone(),
        Value::Bool(true) => "\"liga\" on, \"calt\" on".into(),
        _ => "\"liga\" off, \"calt\" off".into(),
    }
}

/// color.ts `Color.Format.CSS.format`: `#rrggbb` when opaque, else `rgba(…)` with the alpha to 2 decimals.
pub fn css_color(color: gpui::Rgba) -> String {
    let byte = |value: f32| (value * 255.).round() as u8;
    let (r, g, b) = (byte(color.r), byte(color.g), byte(color.b));
    if color.a >= 1. {
        return format!("#{r:02x}{g:02x}{b:02x}");
    }
    let alpha = (f64::from(color.a) * 100.).round() / 100.;
    format!("rgba({r}, {g}, {b}, {alpha})")
}

/// The size registry (platform/theme/common/sizes): every size is the same for all themes.
const SIZES: [(&str, &str); 49] = [
    ("bodyFontSize", "13px"),
    ("bodyFontSize.small", "12px"),
    ("bodyFontSize.xSmall", "11px"),
    ("fontSize.heading1", "26px"),
    ("fontSize.heading2", "18px"),
    ("fontSize.heading3", "13px"),
    ("fontSize.body1", "13px"),
    ("fontSize.body2", "11px"),
    ("fontSize.label1", "12px"),
    ("fontSize.label2", "11px"),
    ("fontSize.label3", "10px"),
    ("fontWeight.regular", "400"),
    ("fontWeight.semiBold", "600"),
    ("codiconFontSize", "16px"),
    ("codiconFontSize.compact", "12px"),
    ("cornerRadius.medium", "6px"),
    ("cornerRadius.xSmall", "2px"),
    ("cornerRadius.small", "4px"),
    ("cornerRadius.large", "8px"),
    ("cornerRadius.xLarge", "12px"),
    ("cornerRadius.circle", "9999px"),
    ("strokeThickness", "1px"),
    ("spacing.sizeNone", "0px"),
    ("spacing.size20", "2px"),
    ("spacing.size40", "4px"),
    ("spacing.size60", "6px"),
    ("spacing.size80", "8px"),
    ("spacing.size100", "10px"),
    ("spacing.size120", "12px"),
    ("spacing.size160", "16px"),
    ("spacing.size200", "20px"),
    ("spacing.size240", "24px"),
    ("spacing.size280", "28px"),
    ("spacing.size320", "32px"),
    ("spacing.size360", "36px"),
    ("spacing.size400", "40px"),
    ("panels.cornerRadius", "8px"),
    ("agentsWindow.panels.cornerRadius", "8px"),
    ("toolsPanel.cornerRadius", "8px"),
    ("primarySideBar.cornerRadius", "8px"),
    ("secondarySideBar.cornerRadius", "8px"),
    ("editorArea.cornerRadius", "8px"),
    ("activityBar.cornerRadius", "8px"),
    ("agentsWindow.chatPanels.cornerRadius", "8px"),
    ("agentsWindow.editorArea.cornerRadius", "8px"),
    ("agentsWindow.toolsPanel.cornerRadius", "8px"),
    ("agentsWindow.secondarySideBar.cornerRadius", "8px"),
    ("panels.spacing", "4px"),
    ("agentsWindow.panels.spacing", "4px"),
];

/// Runs before index.html's own script, which captures `window.parent.postMessage` (the top window here) to post
/// `webview-ready` with its port. The port's messages then reach the native handler as JSON.
/// Extension messages travel as extHostWebviewMessaging.ts serializes them: JSON text with
/// `$$vscode_array_buffer_reference$$` objects, the ArrayBuffers beside it as base64.
const BRIDGE_SCRIPT: &str = r#"(() => {
  const native = window.webkit.messageHandlers.vscodeWebviewHost;
  const viewTypes = [, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array];
  const toBase64 = buffer => {
    const bytes = new Uint8Array(buffer);
    let text = '';
    for (let i = 0; i < bytes.length; i += 0x8000) {
      text += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
    }
    return btoa(text);
  };
  const fromBase64 = text => Uint8Array.from(atob(text), c => c.charCodeAt(0)).buffer;
  const serialize = message => {
    const buffers = [];
    const add = buffer => {
      const index = buffers.indexOf(buffer);
      return index >= 0 ? index : buffers.push(buffer) - 1;
    };
    const text = JSON.stringify(message, (_key, value) => {
      if (value instanceof ArrayBuffer) {
        return { $$vscode_array_buffer_reference$$: true, index: add(value) };
      }
      const type = ArrayBuffer.isView(value) ? viewTypes.indexOf(value.constructor) : -1;
      if (type > 0) {
        return { $$vscode_array_buffer_reference$$: true, index: add(value.buffer), view: { type, byteLength: value.byteLength, byteOffset: value.byteOffset } };
      }
      return value;
    });
    return { message: text, buffers: buffers.map(toBase64) };
  };
  const deserialize = ({ message, buffers }) => {
    const transfer = buffers.map(fromBase64);
    const revive = (_key, value) => {
      if (!value || typeof value !== 'object' || !value.$$vscode_array_buffer_reference$$) {
        return value;
      }
      const buffer = transfer[value.index];
      const type = value.view && viewTypes[value.view.type];
      return type ? new type(buffer, value.view.byteOffset, value.view.byteLength / type.BYTES_PER_ELEMENT) : buffer;
    };
    return { message: JSON.parse(message, transfer.length ? revive : undefined), transfer };
  };
  let port;
  window.postMessage = (message, _origin, transfer) => {
    if (port || !message || message.channel !== 'webview-ready' || !transfer || !transfer[0]) {
      return;
    }
    port = transfer[0];
    port.onmessage = e => {
      const { channel, data } = e.data;
      native.postMessage(JSON.stringify({ channel, data: channel === 'onmessage' ? serialize(data.message) : data }));
    };
    native.postMessage(JSON.stringify({ channel: 'webview-ready', data: message.data }));
  };
  globalThis.__vscodeWebviewHost = {
    post: (channel, args) => {
      if (channel !== 'message') {
        port.postMessage({ channel, args });
        return;
      }
      const data = deserialize(args);
      port.postMessage({ channel, args: data }, data.transfer);
    },
  };
})();"#;

/// webviewFindWidget.ts (a SimpleFindWidget without toggles or result count) in the host page, over its content
/// frame: GPUI cannot draw over the native view, so the widget is upstream's markup and simpleFindWidget.css, the
/// input box styles of defaultInputBoxStyles. Electron's `findInFrame` becomes the content window's `find`, which
/// selects the match instead of highlighting every one. Called with the theme data and the three icons; answers
/// `globalThis.__vscodeFind`, made once per host page.
const FIND_SCRIPT: &str = r#"(theme, icons) => {
  const setTheme = element => {
    for (const [variable, value] of Object.entries(theme.styles)) {
      element.style.setProperty(`--${variable}`, value);
    }
  };
  if (globalThis.__vscodeFind) {
    setTheme(globalThis.__vscodeFind.wrapper);
    return globalThis.__vscodeFind;
  }
  const native = window.webkit.messageHandlers.vscodeWebviewHost;
  const post = (channel, data) => native.postMessage(JSON.stringify({ channel, data }));
  const style = document.createElement('style');
  style.textContent = `
    .simple-find-part-wrapper { overflow: hidden; z-index: 10; position: absolute; top: 0; right: 18px; max-width: calc(100% - 28px - 28px - 8px); pointer-events: none; padding: 0 10px 10px; font-family: -apple-system, BlinkMacSystemFont, sans-serif; }
    .simple-find-part { visibility: hidden; z-index: 10; position: relative; top: -45px; display: flex; padding: 4px; align-items: center; pointer-events: all; transition: top 200ms linear; background-color: var(--vscode-editorWidget-background); color: var(--vscode-editorWidget-foreground); box-shadow: 0 0 8px 2px var(--vscode-widget-shadow); border: 1px solid var(--vscode-widget-border, transparent); border-top: none; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; font-size: 12px; }
    .simple-find-part.visible { visibility: visible; }
    .simple-find-part.visible-transition { top: 0; }
    .simple-find-part .monaco-findInput { position: relative; flex: 1; }
    .monaco-inputbox { position: relative; display: block; padding: 0; box-sizing: border-box; border-radius: 4px; font-size: 13px; width: 100%; background-color: var(--vscode-input-background); color: var(--vscode-input-foreground); border: 1px solid var(--vscode-input-border, transparent); }
    .monaco-inputbox:focus-within { outline: 1px solid var(--vscode-focusBorder); outline-offset: -1px; }
    .monaco-inputbox > .ibwrapper { position: relative; width: 100%; }
    .monaco-inputbox > .ibwrapper > input { display: inline-block; box-sizing: border-box; width: 100%; height: 100%; padding: 4px 6px; line-height: inherit; border: none; outline: none; font-family: inherit; font-size: inherit; color: inherit; background: transparent; text-overflow: clip; }
    .monaco-inputbox > .ibwrapper > input::placeholder { color: var(--vscode-input-placeholderForeground); }
    .simple-find-part .button { min-width: 20px; width: 20px; height: 20px; line-height: 20px; display: flex; flex: initial; justify-content: center; align-items: center; margin-left: 3px; cursor: pointer; border-radius: 5px; color: var(--vscode-icon-foreground); }
    .simple-find-part .button.disabled { opacity: 0.3; cursor: default; }
    .simple-find-part .button:hover:not(.disabled) { background-color: var(--vscode-toolbar-hoverBackground); outline: 1px dashed var(--vscode-toolbar-hoverOutline); outline-offset: -1px; }
    .simple-find-part .button svg { width: 16px; height: 16px; }
  `;
  document.head.appendChild(style);
  const element = (tag, className) => {
    const node = document.createElement(tag);
    node.className = className;
    return node;
  };
  const wrapper = element('div', 'simple-find-part-wrapper');
  const part = element('div', 'simple-find-part');
  const findInput = element('div', 'monaco-findInput');
  const inputBox = element('div', 'monaco-inputbox');
  const ibwrapper = element('div', 'ibwrapper');
  const input = element('input', 'input');
  input.placeholder = 'Find';
  input.setAttribute('aria-label', 'Find');
  input.spellcheck = false;
  ibwrapper.appendChild(input);
  inputBox.appendChild(ibwrapper);
  findInput.appendChild(inputBox);
  part.appendChild(findInput);
  const button = (label, icon, run) => {
    const node = element('div', 'button');
    node.title = label;
    node.setAttribute('role', 'button');
    node.setAttribute('aria-label', label);
    node.innerHTML = icon;
    node.addEventListener('click', e => {
      e.preventDefault();
      if (!node.classList.contains('disabled')) {
        run();
      }
    });
    part.appendChild(node);
    return node;
  };
  let started = false;
  const frame = () => document.getElementById('active-frame')?.contentWindow;
  const updateButtons = found => {
    prev.classList.toggle('disabled', !found);
    next.classList.toggle('disabled', !found);
  };
  // webviewElement.ts `updateFind` starts a search from the top of the page, `find` continues it.
  const search = previous => {
    const target = frame();
    if (!target || !input.value) {
      return;
    }
    if (!started) {
      target.getSelection()?.removeAllRanges();
      started = true;
    }
    const found = target.find(input.value, false, previous, true, false, true, false);
    updateButtons(found);
    input.focus();
  };
  const find = {
    wrapper,
    show() {
      part.classList.add('visible');
      requestAnimationFrame(() => part.classList.add('visible-transition'));
      input.select();
      input.focus();
    },
    hide() {
      if (!part.classList.contains('visible')) {
        return;
      }
      part.classList.remove('visible-transition');
      setTimeout(() => part.classList.contains('visible-transition') || part.classList.remove('visible'), 200);
      started = false;
      post('find-hidden', null);
    },
    find(previous) {
      search(previous);
    },
  };
  const prev = button('Previous Match', icons[0], () => search(true));
  const next = button('Next Match', icons[1], () => search(false));
  button('Close', icons[2], () => find.hide());
  updateButtons(false);
  wrapper.appendChild(part);
  document.body.appendChild(wrapper);
  setTheme(wrapper);
  input.addEventListener('input', () => {
    started = false;
    if (input.value) {
      search(false);
    } else {
      frame()?.getSelection()?.removeAllRanges();
      updateButtons(false);
    }
  });
  part.addEventListener('focusin', () => post('find-focus', { focused: true }));
  part.addEventListener('focusout', () => post('find-focus', { focused: false }));
  // Runs before index.html's keydown listener: the widget's own keys stay in the page; the others go on to the
  // workbench as the host page forwards them.
  window.addEventListener('keydown', e => {
    if (!part.contains(e.target)) {
      return;
    }
    const plain = !e.metaKey && !e.ctrlKey && !e.altKey;
    const editKey = e.metaKey && !e.altKey && !e.ctrlKey && ['a', 'c', 'v', 'x', 'z'].includes(e.key.toLowerCase());
    if (e.key === 'Enter' && plain) {
      e.preventDefault();
      search(e.shiftKey);
    } else if (e.key === 'Escape') {
      e.preventDefault();
      find.hide();
    } else if (!plain && !editKey) {
      return;
    }
    e.stopImmediatePropagation();
  }, true);
  globalThis.__vscodeFind = find;
  return find;
}"#;

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

    #[test]
    fn hashes_the_parent_origin_as_index_html_checks_it() {
        // index.html's inlined `parentOriginHash` run under Bun with the same arguments.
        assert_eq!(parent_origin_hash(PARENT_ORIGIN, "abc"), "003bfr8fddskskjr7sckuom7b7mci25b6n20ugb6ls6e92cu23f0");
    }

    #[test]
    fn maps_resource_urls_to_resources_inside_the_roots() {
        let resource = |scheme: &str, authority: &str, path: &str| files::Resource { scheme: scheme.into(), authority: authority.into(), path: path.into(), query: String::new() };
        assert_eq!(resource_uri("file+.vscode-resource.vscode-cdn.net", "/w/a b.png", ""), Some(resource("file", "", "/w/a b.png")));
        // webview.ts `encodeAuthority` of `wsl+x` and of `my-host`.
        assert_eq!(resource_uri("vscode-remote+wsl-002bx.vscode-resource.vscode-cdn.net", "/a", ""), Some(resource("vscode-remote", "wsl+x", "/a")));
        assert_eq!(resource_uri("memfs+my-002dhost.vscode-resource.vscode-cdn.net", "/a.png", "v=1").map(|uri| (uri.authority, uri.query)), Some(("my-host".into(), "v=1".into())));
        assert_eq!(resource_uri("example.com", "/a", ""), None);
        let roots = [resource("file", "", "/nonexistent-root/media"), resource("memfs", "", "/media")];
        assert!(is_contained(&resource("file", "", "/nonexistent-root/media/a.png"), &roots));
        assert!(!is_contained(&resource("file", "", "/nonexistent-root/mediaX/a.png"), &roots));
        assert!(!is_contained(&resource("file", "", "/nonexistent-root/media/../secret"), &roots));
        assert!(is_contained(&resource("memfs", "", "/media/a.png"), &roots));
        assert!(!is_contained(&resource("memfs", "", "/nonexistent-root/media/a.png"), &roots), "a root holds only its own scheme");
        assert!(!is_contained(&resource("memfs", "other", "/media/a.png"), &roots), "nor another authority");
        assert!(!is_contained(&resource("vscode-remote", "wsl+x", "/media/a.png"), &[resource("vscode-remote", "wsl+x", "/media")]));
        // On Windows: URI.file of `C:\w\media` keeps the drive's case, asWebviewUri's toString lowercases it.
        let roots = [resource("file", "", "/C:/nonexistent-root/Media")];
        assert!(is_contained_on(&resource("file", "", "/c:/nonexistent-root/media/a.png"), &roots, true));
        assert!(!is_contained_on(&resource("file", "", "/c:/nonexistent-root/media/a.png"), &roots, false));
        assert!(!is_contained_on(&resource("file", "", "/c:/nonexistent-root/mediaX/a.png"), &roots, true));
        assert!(!is_contained_on(&resource("file", "", "/c:/nonexistent-root/media/..\\secret"), &roots, true));
        assert!(!is_contained_on(&resource("file", "", "//host/share/a.png"), &roots, true));
    }

    #[test]
    fn serves_only_files_inside_pre_dir_and_the_roots() {
        let dir = std::env::temp_dir().join(format!("vsrustium-webview-serve-{}", std::process::id()));
        let (pre_dir, root, outside) = (dir.join("pre"), dir.join("root"), dir.join("outside"));
        for folder in [&pre_dir, &root, &outside] {
            std::fs::create_dir_all(folder).unwrap();
        }
        std::fs::write(pre_dir.join("index.html"), "host").unwrap();
        std::fs::write(pre_dir.join("a..b.js"), "dots").unwrap();
        std::fs::write(root.join("a.png"), "inside").unwrap();
        std::fs::write(outside.join("secret"), "secret").unwrap();
        #[cfg(unix)]
        std::os::unix::fs::symlink(outside.join("secret"), root.join("link")).unwrap();
        let (events, _receiver) = futures::channel::mpsc::unbounded();
        let resources = Resources { id: "1".into(), pre_dir, roots: RefCell::new(file_roots(std::slice::from_ref(&root))), events };
        let status = |host: &str, path: &str| {
            let answer = Rc::new(RefCell::new(None));
            let sink = answer.clone();
            let served = resources.serve(host, path, "", None, move |(status, _, body): Response| *sink.borrow_mut() = Some((status, String::from_utf8(body).unwrap())));
            served.then(|| answer.take().expect("a synchronous answer"))
        };
        let host = format!("x.{HOST_SITE}");
        assert_eq!(status(&host, "/index.html"), Some((200, "host".into())));
        assert_eq!(status(&host, "/a..b.js"), Some((200, "dots".into())), "a name with dots is no parent component");
        // NSURL, the proxy and `https_url_parts` percent-decode first, so `%2e%2e%2f` arrives as `../`.
        assert_eq!(status(&host, "/../outside/secret").map(|(status, _)| status), Some(404));
        assert_eq!(status(&host, &format!("/{}", outside.join("secret").display())).map(|(status, _)| status), Some(404));
        let resource_host = format!("file+.{RESOURCE_AUTHORITY}");
        let root_path = root.to_string_lossy().replace('\\', "/");
        assert_eq!(status(&resource_host, &format!("/{}/a.png", root_path.trim_start_matches('/'))), Some((200, "inside".into())));
        assert_eq!(status(&resource_host, &format!("/{}/../outside/secret", root_path.trim_start_matches('/'))).map(|(status, _)| status), Some(401));
        assert_eq!(status(&resource_host, &format!("/{}", outside.join("secret").to_string_lossy().replace('\\', "/").trim_start_matches('/'))).map(|(status, _)| status), Some(401));
        #[cfg(unix)]
        assert_eq!(status(&resource_host, &format!("/{}/link", root_path.trim_start_matches('/'))).map(|(status, _)| status), Some(401), "a link out of the root resolves outside it");
        assert_eq!(status("example.com", "/a"), None, "another host goes to the network");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn splits_https_urls_as_nsurl_does() {
        let parts = |url: &str| https_url_parts(url).map(|(host, path, query)| [host, path, query]);
        assert_eq!(parts("https://File+.VSCODE-resource.vscode-cdn.net/c%3A/a%20b.png?v=%31#top"), Some(["file+.vscode-resource.vscode-cdn.net".into(), "/c:/a b.png".into(), "v=1".into()]));
        assert_eq!(parts("https://x.vscode-webview.vscode-cdn.net?id=1"), Some(["x.vscode-webview.vscode-cdn.net".into(), "/".into(), "id=1".into()]));
        // A wildcard filter matches this URL; its host is example.com.
        assert_eq!(parts("https://example.com/.vscode-resource.vscode-cdn.net/a").map(|[host, ..]| host), Some("example.com".into()));
        assert_eq!(parts("http://x.vscode-webview.vscode-cdn.net/"), None);
    }

    #[test]
    fn answers_byte_ranges_and_mime_types() {
        assert_eq!(byte_range("bytes=0-", 10), Some((0, 9)));
        assert_eq!(byte_range("bytes=2-4", 10), Some((2, 4)));
        assert_eq!(byte_range("bytes=2-40", 10), Some((2, 9)));
        assert_eq!(byte_range("bytes=12-", 10), None);
        assert_eq!(mime_type(Path::new("a.JS")), "application/javascript");
        assert_eq!(mime_type(Path::new("a.png")), "image/png");
        assert_eq!(mime_type(Path::new("a")), "application/unknown");
    }

    #[test]
    fn formats_colors_as_css_does() {
        assert_eq!(css_color(gpui::Rgba { r: 1., g: 0., b: 0.5, a: 1. }), "#ff0080");
        assert_eq!(css_color(gpui::Rgba { r: 1., g: 1., b: 1., a: 0.333 }), "rgba(255, 255, 255, 0.33)");
        assert_eq!(font_ligatures(&json!(false)), "\"liga\" off, \"calt\" off");
    }
}