Skip to content

Visual Studio Code, rebuilt in Rust

Rust
38.9 KB
Raw Blame
//! workbench/contrib/mediaPreview: the built-in image, video and audio previews, which open image and media files
//! in place of the text editor. Each draws its page in a webview panel without an extension.

use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

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

mod codecs;

use super::Workbench;
use super::custom_editors::{Contribution, CustomEditor, RANK_BUILTIN};
use super::webview_panels::{WEBVIEW_PANEL_SCHEME, WebviewPanel};
use crate::commands::Outcome;
use crate::editor::TextDocument;
use crate::main_thread_quick_open::Owner;
use crate::quick_input::{Entry, Event, Item, Kind, QuickInput};

/// mediaPreview.ts: the editor ids keep the view types of the custom editors the `media-preview` extension had.
pub const IMAGE_PREVIEW_EDITOR_ID: &str = "imagePreview.previewEditor";
const VIDEO_PREVIEW_EDITOR_ID: &str = "vscode.videoPreview";
const AUDIO_PREVIEW_EDITOR_ID: &str = "vscode.audioPreview";
const IMAGE_PREVIEW_FILE_PATTERN: &str = "*.{jpg,jpe,jpeg,png,bmp,gif,ico,webp,avif,svg}";
const VIDEO_PREVIEW_FILE_PATTERN: &str = "*.{mp4,webm}";
const AUDIO_PREVIEW_FILE_PATTERN: &str = "*.{mp3,wav,ogg,oga}";
const SELECT_IMAGE_ZOOM_LEVEL_COMMAND_ID: &str = "imagePreview.selectZoomLevel";
/// `webviewGenericCspSource`.
const CSP_SOURCE: &str = "'self' https://*.vscode-cdn.net";
const OPEN_IN_TEXT_EDITOR: &str = "Open in Text Editor";
const IMAGE_PAGE: &str = include_str!("media_preview/image.html");
const PLAYER_PAGE: &str = include_str!("media_preview/player.html");
/// mediaPlayerEditorInput.ts `maxMediaSourceSize`.
const MAX_MEDIA_SOURCE_SIZE: u64 = 200 * 1024 * 1024;
/// mediaCodecs.ts `defaultMaxWholeFileSize`: the largest file read whole for its codecs.
const MAX_WHOLE_FILE_SIZE: u64 = 64 * 1024 * 1024;
/// mediaPreview.ts `gitLfsPointerPrefix` and `gitLfsPointerMaxSize`.
const GIT_LFS_POINTER_PREFIX: &[u8] = b"version https://git-lfs.github.com/spec/v1";
const GIT_LFS_POINTER_MAX_SIZE: u64 = 1024;
/// mediaPreviewActions.ts `SelectImageZoomLevelAction`, `fit` as None.
const ZOOM_LEVEL_PICKS: [Option<f64>; 7] = [Some(10.), Some(5.), Some(2.), Some(1.), Some(0.5), Some(0.2), None];

#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum MediaKind {
    Image,
    Video,
    Audio,
}

/// What the status bar shows of a preview (mediaPreviewStatusBar.ts), and an image's view state.
pub(super) struct MediaPreview {
    kind: MediaKind,
    pub(super) resource: files::Resource,
    file_size: Option<u64>,
    /// mediaPreview.ts `isGitLfsPointer`: the page shows a message in place of the media.
    git_lfs: bool,
    /// `ImageViewerScale`: a number or `"fit"`, Null while no image shows.
    scale: Value,
    dimensions: Option<(u64, u64)>,
    view_state: Value,
}

/// The built-in previews as the editor resolver ranks them (`RegisteredEditorPriority.builtin`).
pub(super) fn media_preview_contributions() -> Vec<Contribution> {
    let contribution = |view_type: &str, display_name: &str, pattern: &str| Contribution {
        view_type: view_type.to_owned(),
        display_name: display_name.to_owned(),
        provider: "Built-in".to_owned(),
        patterns: vec![pattern.to_owned()],
        rank: RANK_BUILTIN,
        diff_rank: RANK_BUILTIN,
    };
    vec![
        contribution(IMAGE_PREVIEW_EDITOR_ID, "Image Preview", IMAGE_PREVIEW_FILE_PATTERN),
        contribution(VIDEO_PREVIEW_EDITOR_ID, "Video Preview", VIDEO_PREVIEW_FILE_PATTERN),
        contribution(AUDIO_PREVIEW_EDITOR_ID, "Audio Preview", AUDIO_PREVIEW_FILE_PATTERN),
    ]
}

pub(super) fn media_kind(editor_id: &str) -> Option<MediaKind> {
    match editor_id {
        IMAGE_PREVIEW_EDITOR_ID => Some(MediaKind::Image),
        VIDEO_PREVIEW_EDITOR_ID => Some(MediaKind::Video),
        AUDIO_PREVIEW_EDITOR_ID => Some(MediaKind::Audio),
        _ => None,
    }
}

impl Workbench {
    pub(super) fn register_media_preview_commands(&mut self) {
        self.commands.register("imagePreview.zoomIn", |workbench, _, _, _| workbench.post_to_active_image(json!({ "type": "zoom-in" })));
        self.commands.register("imagePreview.zoomOut", |workbench, _, _, _| workbench.post_to_active_image(json!({ "type": "zoom-out" })));
        self.commands.register(SELECT_IMAGE_ZOOM_LEVEL_COMMAND_ID, |workbench, _, window, cx| {
            if workbench.active_media_preview().is_some_and(|media| media.kind == MediaKind::Image) {
                workbench.show_zoom_level_picker(window, cx);
            }
            Outcome::done()
        });
        // mediaPreviewActions.ts: reopening as text or as preview are offered for SVG files.
        self.commands.register("imagePreview.reopenAsText", |workbench, _, window, cx| workbench.reopen_active_editor_with(Some("default".into()), window, cx));
        self.commands.register("imagePreview.reopenAsPreview", |workbench, _, window, cx| {
            workbench.reopen_active_editor_with(Some(IMAGE_PREVIEW_EDITOR_ID.into()), window, cx)
        });
    }

    /// mediaPreview.contribution.ts `createEditorInput`: one preview per file and editor, opened in the active group.
    pub(super) fn open_media_preview(&mut self, kind: MediaKind, view_type: &str, resource: &Value, options: &Value, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        // mediaPreview.contribution.ts registers without `singlePerResource`: a preview in another group stays, the
        // active group gets its own.
        let in_active_group = |panel: &WebviewPanel| self.editors.editors.iter().any(|editor| panel.shows(editor));
        let shows = |panel: &WebviewPanel| panel.view_type == view_type && panel.custom.as_ref().is_some_and(|custom| custom.resource == *resource) && in_active_group(panel);
        let handle = match self.webview_panels.panels.iter().find(|panel| shows(panel)) {
            Some(panel) => panel.handle.clone(),
            None => {
                let handle = format!("media-preview-{}", self.webview_panels.panels.len() + self.editors.editors.len() + nanos() as usize);
                let placeholder = PathBuf::from(format!("webview-panel/webview-{view_type}-{handle}"));
                let document = TextDocument::from_text(WEBVIEW_PANEL_SCHEME, &placeholder, "", "utf8".into(), None, &self.languages, &self.settings.lock().unwrap());
                let media_resource = exthost::main_thread_files::resource(resource);
                let title = media_resource.basename().to_owned();
                let root = media_resource.dirname();
                let roots = json!({ "enableScripts": true, "localResourceRoots": [{ "scheme": root.scheme, "authority": root.authority, "path": root.path }] });
                // mediaPlayerEditorInput.ts keeps the webview while hidden, so playback goes on.
                let retain = kind != MediaKind::Image;
                let custom = Some(CustomEditor { resource: resource.clone(), resolved: true, backup_id: None, navigation: super::custom_editors::Navigation::None, diff: None });
                let mut panel = WebviewPanel::new(handle.clone(), WEBVIEW_PANEL_SCHEME.into(), placeholder, view_type, title, &Value::Null, roots, retain, custom);
                let media = MediaPreview { kind, resource: media_resource.clone(), file_size: None, git_lfs: false, scale: Value::Null, dimensions: None, view_state: Value::Null };
                panel.media = Some(media);
                self.webview_panels.panels.push(panel);
                self.resolve_media_preview(handle.clone(), media_resource, cx);
                self.leave_locked_group(WEBVIEW_PANEL_SCHEME, &document.path);
                self.editors.open(document, options["pinned"] != true);
                handle
            }
        };
        let (_, index) = self.webview_editor_group(&handle).expect("the preview's editor is open");
        self.editors.activate(index);
        if options["pinned"] == true {
            self.editors.pin(index);
        }
        self.editors_changed(cx);
        if options["preserveFocus"] != true {
            self.focus_webview_panel(&handle, window, cx);
        }
        Outcome::done()
    }

    /// mediaPlayerEditorInput.ts `_render` and `_updateFileSize`: the file service's stat and Git LFS check, then the page.
    fn resolve_media_preview(&mut self, handle: String, resource: files::Resource, cx: &mut Context<Self>) {
        let stat = self.host.stat_file(resource.clone());
        cx.spawn(async move |workbench, cx| {
            let file_size = stat.await.ok().and_then(Result::ok).map(|stat| stat.size);
            let git_lfs = match file_size {
                Some(1..=GIT_LFS_POINTER_MAX_SIZE) if resource.scheme == "git" => {
                    let Ok(read) = workbench.update(cx, |workbench, _| workbench.host.read_file(resource)) else { return };
                    read.await.ok().and_then(Result::ok).is_some_and(|bytes| bytes.starts_with(GIT_LFS_POINTER_PREFIX))
                }
                _ => false,
            };
            let _ = workbench.update(cx, |workbench, cx| {
                let (auto_play, looped) = (workbench.setting("mediaPreview.video.autoPlay"), workbench.setting("mediaPreview.video.loop"));
                let Some(panel) = workbench.webview_panel_mut(&handle) else { return };
                let Some(media) = &mut panel.media else { return };
                media.file_size = file_size;
                media.git_lfs = git_lfs;
                panel.html = media.page(&auto_play, &looped);
                panel.update_content();
                cx.notify();
            });
        })
        .detach();
    }

    /// A message a preview's page posted: mediaPlayerEditorInput.ts `webview.onMessage`, and the image viewer's
    /// `onDidChangeScale` with the dimensions it decoded.
    pub(super) fn handle_media_preview_message(&mut self, handle: &str, message: &Value, window: &mut Window, cx: &mut Context<Self>) {
        let Some(panel) = self.webview_panel_mut(handle) else { return };
        let Some(media) = &mut panel.media else { return };
        match message["type"].as_str().unwrap_or_default() {
            "image-info" => {
                media.scale = message["scale"].clone();
                media.dimensions = message["width"].as_u64().zip(message["height"].as_u64());
                media.view_state = message["viewState"].clone();
                let page = media.page(&Value::Null, &Value::Null);
                panel.html = page;
                cx.notify();
            }
            request @ ("get-codecs" | "get-webm-type") => {
                let (request, kind, resource, handle) = (request.to_owned(), media.kind, media.resource.clone(), handle.to_owned());
                // mediaCodecs.ts `createReader`: a provider without range reads is read whole, up to a limit.
                let limit = if request == "get-codecs" { MAX_WHOLE_FILE_SIZE } else { MAX_MEDIA_SOURCE_SIZE };
                let whole_file = (resource.scheme != "file" && media.file_size.is_some_and(|size| size <= limit)).then(|| self.host.read_file(resource.clone()));
                cx.spawn(async move |workbench, cx| {
                    let info = match whole_file {
                        Some(read) => read.await.ok().and_then(Result::ok).and_then(|bytes| codecs::read_media_info(bytes.len() as u64, |position, length| Ok(bytes[position as usize..][..length as usize].to_vec()))),
                        None if resource.scheme != "file" => None,
                        None => {
                            let path = PathBuf::from(&resource.path);
                            cx.background_executor().spawn(async move { codecs::read_file_media_info(&path) }).await
                        }
                    };
                    let message = match request.as_str() {
                        "get-codecs" => codecs_message(kind, &resource, info),
                        _ => Some(webm_type_message(info)),
                    };
                    let _ = workbench.update(cx, |workbench, _| {
                        if let Some(message) = message
                            && let Some(webview) = workbench.webview_panel_mut(&handle).and_then(|panel| panel.webview.as_mut())
                        {
                            webview.send("message", json!({ "message": message, "buffers": [] }));
                        }
                    });
                })
                .detach();
            }
            "reopen-as-text" => drop(self.reopen_active_editor_with(Some("default".into()), window, cx)),
            "open-externally" if can_open_externally(&media.resource) => {
                let path = PathBuf::from(&media.resource.path);
                cx.open_with_system(&path);
            }
            _ => {}
        }
    }

    /// mediaPreviewStatusBar.ts: the zoom (Select Zoom Level), dimensions and file size entries of the active preview.
    pub(super) fn media_preview_status_entries(&self) -> Vec<(String, &'static str, &'static str, &'static str)> {
        let Some(media) = self.active_media_preview() else { return Vec::new() };
        let mut entries = Vec::new();
        if !media.scale.is_null() {
            entries.push((zoom_label(media.scale.as_f64()), "Select Zoom Level", SELECT_IMAGE_ZOOM_LEVEL_COMMAND_ID, "status.imagePreview.zoom"));
        }
        if let Some((width, height)) = media.dimensions {
            entries.push((format!("{width}x{height}"), "", "", "status.imagePreview.dimensions"));
        }
        if let Some(size) = media.file_size {
            entries.push((format_size(size), "", "", "status.mediaPreview.fileSize"));
        }
        entries
    }

    fn active_media_preview(&self) -> Option<&MediaPreview> {
        let editor = self.editors.active()?;
        self.webview_panels.panels.iter().find(|panel| editor.document().is(&panel.scheme, &panel.path))?.media.as_ref()
    }

    fn post_to_active_image(&mut self, message: Value) -> Outcome {
        let Some(editor) = self.editors.active() else { return Outcome::done() };
        let (scheme, path) = (editor.document().scheme.clone(), editor.document().path.clone());
        let panel = self.webview_panels.panels.iter_mut().find(|panel| panel.scheme == scheme && panel.path == path);
        if let Some(webview) = panel.filter(|panel| panel.media.as_ref().is_some_and(|media| media.kind == MediaKind::Image)).and_then(|panel| panel.webview.as_mut()) {
            webview.send("message", json!({ "message": message, "buffers": [] }));
        }
        Outcome::done()
    }

    fn show_zoom_level_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let entries = ZOOM_LEVEL_PICKS.iter().enumerate().map(|(handle, scale)| Entry::Item(Item { handle: handle as i64, label: zoom_label(*scale), pickable: true, ..Item::default() })).collect();
        let mut input = QuickInput::new(0, Kind::QuickPick);
        input.placeholder = Some("Select zoom level".into());
        input.set_items(entries);
        let id = self.quick_inputs.add(input, Owner::ImageZoom);
        self.show_quick_input(id, window, cx);
        self.flush_quick_input_events(window, cx);
    }

    pub fn image_zoom_picker_event(&mut self, id: i64, event: Event, window: &mut Window, cx: &mut Context<Self>) {
        match event {
            Event::Accept(_) => {
                let Some(&handle) = self.quick_inputs.get(id).and_then(|input| input.selected_handles().first().copied()).as_ref() else { return };
                self.hide_quick_input_by_id(id, window, cx);
                let scale = ZOOM_LEVEL_PICKS[handle as usize].map_or(json!("fit"), |scale| json!(scale));
                self.post_to_active_image(json!({ "type": "set-scale", "scale": scale }));
            }
            Event::Hide => self.quick_inputs.remove(id),
            _ => {}
        }
    }
}

impl MediaPreview {
    /// The preview's page: imagePreviewEditor.ts and imageViewer.ts for images, mediaPlayerEditorInput.ts `_getHtml`
    /// for video and audio.
    fn page(&self, auto_play: &Value, looped: &Value) -> String {
        let name = self.resource.basename();
        // mediaPlayerEditorInput.ts' `version` query against the cache, unless the resource has a query.
        let mut src = as_webview_uri(&self.resource);
        if self.resource.query.is_empty() {
            src.push_str(&format!("?version={}", nanos() / 1_000_000));
        }
        let nonce = format!("{:032x}", nanos());
        let page = match self.kind {
            MediaKind::Image => {
                // A Git LFS pointer gets no source, so the page shows its message where a decode error goes.
                let (src, load_error) = match self.git_lfs {
                    true => (String::new(), "The image is stored with Git LFS and is not available for preview."),
                    false => (src, "An error occurred while loading the image."),
                };
                IMAGE_PAGE
                    .replace("{{aria_label}}", &escape(&format!("Image Preview: {name}")))
                    .replace("{{src}}", &json!(src).to_string())
                    // The view state comes back from the page: `<` escaped so a `</script>` in it stays a string.
                    .replace("{{view_state}}", &self.view_state.to_string().replace('<', "\\u003c"))
                    .replace("{{load_error}}", &json!(load_error).to_string())
            }
            MediaKind::Audio | MediaKind::Video => {
                let audio = self.kind == MediaKind::Audio;
                let media = match audio {
                    true => format!("<audio src=\"{}\" controls></audio>", escape(&src)),
                    false => {
                        let auto_play = if *auto_play == true { " autoplay muted" } else { "" };
                        let looped = if *looped == true { " loop" } else { "" };
                        format!("<video src=\"{}\" controls playsinline{auto_play}{looped}></video>", escape(&src))
                    }
                };
                let error = match (audio, self.git_lfs) {
                    (true, true) => "The audio file is stored with Git LFS and is not available for preview.",
                    (false, true) => "The video file is stored with Git LFS and is not available for preview.",
                    (true, false) => "An error occurred while loading the audio file.",
                    (false, false) => "An error occurred while loading the video file.",
                };
                // The file only holds a pointer to the media, so the page does not try to play it.
                let (media, body_class) = if self.git_lfs { (String::new(), " class=\"error\"") } else { (media, "") };
                PLAYER_PAGE
                    .replace("{{body_class}}", body_class)
                    .replace("{{media}}", &media)
                    .replace("{{error_message}}", &escape(error))
                    .replace("{{max_media_source_size}}", &MAX_MEDIA_SOURCE_SIZE.to_string())
            }
        };
        page.replace("{{csp_source}}", CSP_SOURCE).replace("{{nonce}}", &nonce).replace("{{open_in_text_editor}}", &escape(OPEN_IN_TEXT_EDITOR))
    }
}

/// mediaPlayerEditorInput.ts `_postCodecs`: the video (of a video preview) and audio codecs as MIME types, with the
/// warning the page shows when it can play none of a kind; None when the file has no such tracks.
fn codecs_message(kind: MediaKind, resource: &files::Resource, info: Option<codecs::MediaInfo>) -> Option<Value> {
    let info = info?;
    let preview_kind = if kind == MediaKind::Audio { "audio" } else { "video" };
    let open_externally: Vec<Value> = match can_open_externally(resource) {
        true => vec![json!({ "label": "Open File", "message": "open-externally" })],
        false => Vec::new(),
    };
    let codecs = |track_kind: &str| {
        let tracks: Vec<_> = info.tracks.iter().filter(|track| track.kind == track_kind).collect();
        let first = tracks.first()?;
        let mut actions = open_externally.clone();
        // Only a file whose own kind of track cannot play fails to load.
        if track_kind == preview_kind {
            actions.push(json!({ "label": OPEN_IN_TEXT_EDITOR, "message": "reopen-as-text" }));
        }
        let mime_types: Vec<String> = tracks.iter().map(|track| format!("{track_kind}/{}; codecs=\"{}\"", info.container, track.codec)).collect();
        Some(json!({ "mimeTypes": mime_types, "warning": unsupported_codec_warning(preview_kind, first), "actions": actions }))
    };
    let video = if kind == MediaKind::Video { codecs("video") } else { None };
    let audio = codecs("audio");
    if video.is_none() && audio.is_none() {
        return None;
    }
    Some(json!({ "type": "codecs", "video": video, "audio": audio }))
}

/// mediaPlayerEditorInput.ts `_getUnsupportedCodecWarning`.
fn unsupported_codec_warning(preview_kind: &str, track: &codecs::Track) -> String {
    let (named, unnamed) = match (track.kind, preview_kind) {
        ("video", _) => ("This video uses the {0} codec, which can't be played in the video preview.", "This video uses a codec that can't be played in the video preview."),
        (_, "audio") => ("This audio file uses the {0} codec, which can't be played in the audio preview.", "This audio file uses a codec that can't be played in the audio preview."),
        _ => ("This video's audio uses the {0} codec, which can't be played in the video preview.", "This video's audio uses a codec that can't be played in the video preview."),
    };
    match track.name {
        Some(name) => named.replace("{0}", name),
        None => unnamed.to_owned(),
    }
}

/// mediaPlayerEditorInput.ts `_postWebmType`: a WebM file's type with the codecs of all its tracks, for Media Source
/// Extensions.
fn webm_type_message(info: Option<codecs::MediaInfo>) -> Value {
    let mut codecs: Vec<String> = Vec::new();
    for track in info.iter().filter(|info| info.container == "webm").flat_map(|info| &info.tracks) {
        if !codecs.contains(&track.codec) {
            codecs.push(track.codec.clone());
        }
    }
    let mime_type = (!codecs.is_empty()).then(|| format!("video/webm; codecs=\"{}\"", codecs.join(",")));
    json!({ "type": "webm-type", "mimeType": mime_type })
}

/// mediaPlayerEditorInput.ts `_canOpenExternally`: only files with a media extension, never ones the OS would run.
fn can_open_externally(resource: &files::Resource) -> bool {
    let mime_type = crate::webview::mime_type(Path::new(&resource.path));
    resource.scheme == "file" && (mime_type.starts_with("audio/") || mime_type.starts_with("video/"))
}

/// mediaPreviewStatusBar.ts `getImageZoomLabel`, None for `fit`.
fn zoom_label(scale: Option<f64>) -> String {
    match scale {
        Some(scale) => format!("{}%", (scale * 100.).round()),
        None => "Whole Image".into(),
    }
}

/// files.ts `ByteSize.formatSize`.
pub(super) fn format_size(size: u64) -> String {
    const KB: f64 = 1024.;
    let size = size as f64;
    match size {
        size if size < KB => format!("{size}B"),
        size if size < KB * KB => format!("{:.2}KB", size / KB),
        size if size < KB * KB * KB => format!("{:.2}MB", size / KB / KB),
        size if size < KB * KB * KB * KB => format!("{:.2}GB", size / KB / KB / KB),
        size => format!("{:.2}TB", size / KB / KB / KB / KB),
    }
}

/// strings.ts `escape`, then htmlContent.ts `escapeDoubleQuotes`.
fn escape(text: &str) -> String {
    text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}

/// `URI.toString` path encoding of a file path.
pub(super) fn encode_path(path: &Path) -> String {
    let mut encoded = String::new();
    for byte in path.to_string_lossy().bytes() {
        match byte {
            b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => encoded.push(byte as char),
            _ => encoded.push_str(&format!("%{byte:02X}")),
        }
    }
    encoded
}

/// webview.ts `asWebviewUri` without a remote, with `encodeAuthority`.
fn as_webview_uri(resource: &files::Resource) -> String {
    let mut authority = String::new();
    for character in resource.authority.chars() {
        if character.is_ascii_alphanumeric() {
            authority.push(character);
            continue;
        }
        for unit in character.encode_utf16(&mut [0; 2]) {
            authority.push_str(&format!("-{unit:04x}"));
        }
    }
    let mut uri = format!("https://{}+{authority}.vscode-resource.vscode-cdn.net{}", resource.scheme, encode_path(Path::new(&resource.path)));
    if !resource.query.is_empty() {
        uri.push_str(&format!("?{}", encode_path(Path::new(&resource.query))));
    }
    uri
}

fn nanos() -> u128 {
    SystemTime::now().duration_since(UNIX_EPOCH).expect("the clock is past 1970").as_nanos()
}

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

    #[test]
    fn formats_labels_as_the_status_bar_does() {
        assert_eq!(zoom_label(None), "Whole Image");
        assert_eq!(zoom_label(Some(0.5)), "50%");
        assert_eq!(zoom_label(Some(1.0 / 3.0)), "33%");
        assert_eq!(format_size(1000), "1000B");
        assert_eq!(format_size(1536), "1.50KB");
        assert_eq!(format_size(5 * 1024 * 1024), "5.00MB");
        assert_eq!(encode_path(Path::new("/a b/c#.png")), "/a%20b/c%23.png");
    }

    #[test]
    fn webview_uris_name_the_resource_back() {
        let resource = files::Resource { scheme: "git".into(), authority: "my-host".into(), path: "/w/a b.png".into(), query: r#"{"ref":"HEAD"}"#.into() };
        let uri = as_webview_uri(&resource);
        assert_eq!(uri, "https://git+my-002dhost.vscode-resource.vscode-cdn.net/w/a%20b.png?%7B%22ref%22%3A%22HEAD%22%7D");
        let (host, rest) = uri.strip_prefix("https://").unwrap().split_once('/').unwrap();
        let (path, query) = rest.split_once('?').unwrap();
        let named = crate::webview::resource_uri(host, &crate::uri::percent_decode(&format!("/{path}")), &crate::uri::percent_decode(query));
        assert_eq!(named, Some(resource));
    }

    /// mediaPlayerEditorInput.ts `_postCodecs` and `_postWebmType` over the tracks mediaCodecs.ts reads.
    #[test]
    fn answers_the_player_page_with_the_file_s_codecs() {
        let track = |kind, codec: &str, name| codecs::Track { kind, codec: codec.into(), name };
        let info = || Some(codecs::MediaInfo { container: "webm", tracks: vec![track("video", "vp9", Some("VP9")), track("audio", "opus", Some("Opus")), track("audio", "opus", Some("Opus"))] });
        let file = |path: &str| files::Resource::file(path);
        let message = codecs_message(MediaKind::Video, &file("/w/a.webm"), info()).unwrap();
        assert_eq!(message["video"]["mimeTypes"], json!(["video/webm; codecs=\"vp9\""]));
        assert_eq!(message["video"]["warning"], "This video uses the VP9 codec, which can't be played in the video preview.");
        assert_eq!(message["video"]["actions"], json!([{ "label": "Open File", "message": "open-externally" }, { "label": "Open in Text Editor", "message": "reopen-as-text" }]));
        assert_eq!(message["audio"]["warning"], "This video's audio uses the Opus codec, which can't be played in the video preview.");
        assert_eq!(message["audio"]["actions"], json!([{ "label": "Open File", "message": "open-externally" }]));
        let audio = codecs_message(MediaKind::Audio, &file("/w/a.wav"), Some(codecs::MediaInfo { container: "wav", tracks: vec![track("audio", "17", None)] })).unwrap();
        assert_eq!((audio["video"].clone(), audio["audio"]["warning"].clone()), (Value::Null, json!("This audio file uses a codec that can't be played in the audio preview.")));
        assert_eq!(codecs_message(MediaKind::Video, &file("/w/a.mp4"), Some(codecs::MediaInfo { container: "mp4", tracks: vec![] })), None);
        assert_eq!(webm_type_message(info())["mimeType"], "video/webm; codecs=\"vp9,opus\"");
        assert_eq!(webm_type_message(None)["mimeType"], Value::Null);
    }

    #[test]
    fn fills_every_placeholder_of_the_pages() {
        for kind in [MediaKind::Image, MediaKind::Video, MediaKind::Audio] {
            for git_lfs in [false, true] {
                let media = MediaPreview { kind, resource: files::Resource::file("/w/a.png"), file_size: None, git_lfs, scale: Value::Null, dimensions: None, view_state: json!({ "x": "</script>" }) };
                let page = media.page(&json!(true), &json!(false));
                assert!(!page.contains("{{"), "{page}");
                assert!(!page.contains("\"</script>"), "{page}");
            }
        }
    }

    #[gpui::test]
    fn opens_a_startup_image_in_its_preview_without_a_resolver_cache(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 (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 image = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../port/fixtures/webviews/image.png");
        workbench.update_in(cx, |workbench, window, cx| workbench.open_startup_file(image, &[], false, window, cx));
        let scheme = workbench.read_with(cx, |workbench, _| workbench.editors.active().map(|editor| editor.document().scheme.clone()));
        assert_eq!(scheme.as_deref(), Some(WEBVIEW_PANEL_SCHEME));
    }

    /// The `git` file system of the git extension, with a Git LFS pointer and an image.
    struct GitFiles;

    impl GitFiles {
        fn bytes(path: &str) -> Vec<u8> {
            match path {
                "/w/clip.mp4" => b"version https://git-lfs.github.com/spec/v1\noid sha256:4d7a\nsize 12345\n".to_vec(),
                _ => vec![0x89; 2048],
            }
        }
    }

    impl files::FileSystem for GitFiles {
        fn capabilities(&mut self, _scheme: &str) -> Option<u32> {
            Some(files::PROVIDER_READONLY)
        }
        fn stat(&mut self, resource: &files::Resource) -> files::Result<files::Stat> {
            Ok(files::Stat { file_type: files::FILE, ctime: 0, mtime: 0, size: Self::bytes(&resource.path).len() as u64, permissions: None })
        }
        fn read_file(&mut self, resource: &files::Resource) -> files::Result<Vec<u8>> {
            Ok(Self::bytes(&resource.path))
        }
        fn read_dir(&mut self, _: &files::Resource) -> files::Result<Vec<(String, u32)>> {
            unreachable!()
        }
        fn write_file(&mut self, _: &files::Resource, _: &[u8], _: bool, _: bool) -> files::Result<()> {
            unreachable!()
        }
        fn mkdir(&mut self, _: &files::Resource) -> files::Result<()> {
            unreachable!()
        }
        fn delete(&mut self, _: &files::Resource, _: bool, _: bool) -> files::Result<()> {
            unreachable!()
        }
        fn rename(&mut self, _: &files::Resource, _: &files::Resource, _: bool) -> files::Result<()> {
            unreachable!()
        }
        fn copy(&mut self, _: &files::Resource, _: &files::Resource, _: bool) -> files::Result<()> {
            unreachable!()
        }
    }

    impl files::operations::WorkingCopyFiles for GitFiles {
        fn participate(&mut self, _: files::operations::FileOperation, _: &[files::operations::SourceTarget], _: files::operations::UndoInfo) {}
        fn did_run(&mut self, _: files::operations::FileOperation, _: &[files::operations::SourceTarget]) {}
        fn enable_trash(&mut self) -> bool {
            false
        }
        fn empty_file(&mut self, _: &files::Resource) -> Vec<u8> {
            unreachable!()
        }
    }

    /// mediaPlayerEditorInput.ts `_render` and imagePreviewEditor.ts `_loadImage` of a `git` resource: read through
    /// the file service, a Git LFS pointer as a message.
    #[gpui::test]
    fn previews_read_git_resources_and_show_git_lfs_pointers_as_a_message(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 (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 answer_host = |cx: &mut gpui::VisualTestContext| {
            for _ in 0..3 {
                while let Ok(message) = host.try_recv() {
                    if let Some(work) = message.files {
                        work.run(&mut GitFiles);
                    }
                }
                cx.run_until_parked();
            }
        };
        let preview = |kind, view_type: &str, path: &str, cx: &mut gpui::VisualTestContext| {
            workbench.update_in(cx, |workbench, window, cx| drop(workbench.open_media_preview(kind, view_type, &crate::editor::uri_value("git", Path::new(path)), &json!({}), window, cx)));
            answer_host(cx);
            workbench.read_with(cx, |workbench, _| {
                let panel = workbench.webview_panels.panels.last().unwrap();
                (panel.html.clone(), panel.content_options["localResourceRoots"].clone(), workbench.media_preview_status_entries().into_iter().map(|entry| entry.0).collect::<Vec<_>>())
            })
        };
        let (html, roots, status) = preview(MediaKind::Video, VIDEO_PREVIEW_EDITOR_ID, "/w/clip.mp4", cx);
        assert!(html.contains("<body class=\"error\"") && html.contains("The video file is stored with Git LFS and is not available for preview.") && !html.contains("<video"), "{html}");
        assert_eq!((roots, status), (json!([{ "scheme": "git", "authority": "", "path": "/w" }]), vec!["70B".to_owned()]));
        let (html, _, status) = preview(MediaKind::Image, IMAGE_PREVIEW_EDITOR_ID, "/w/a.png", cx);
        assert!(html.contains("\"https://git+.vscode-resource.vscode-cdn.net/w/a.png?version=") && !html.contains("Git LFS"), "{html}");
        assert_eq!(status, ["2.00KB"]);
    }

    /// editorGroupView.ts `replaceEditors`: Reopen Editor With puts the replacement in the replaced editor's place.
    #[gpui::test]
    fn a_reopened_preview_keeps_its_tab_position(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 (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 image = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../port/fixtures/webviews/image.png");
        let text = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.open_file(image.clone(), true, window, cx);
            workbench.open_file(text.clone(), true, window, cx);
            workbench.open_file(image.clone(), true, window, cx);
        });
        cx.run_until_parked();
        workbench.update_in(cx, |workbench, window, cx| {
            drop(workbench.reopen_with(&crate::editor::uri_value("file", &image), IMAGE_PREVIEW_EDITOR_ID, super::super::custom_editors::TEXT_EDITOR_ID, false, window, cx));
        });
        cx.run_until_parked();
        let tabs = workbench.read_with(cx, |workbench, _| workbench.editors.editors.iter().map(|editor| (editor.document().scheme.clone(), editor.document().path.clone())).collect::<Vec<_>>());
        assert_eq!(tabs, [("file".to_owned(), image), ("file".to_owned(), text)]);
    }

    /// editorGroupView.ts `replaceEditors` closes the text editor an image preview replaces, as Reopen as Preview does.
    #[gpui::test]
    fn reopening_as_text_and_back_keeps_one_tab(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 (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 image = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../port/fixtures/webviews/image.png");
        workbench.update_in(cx, |workbench, window, cx| workbench.open_file(image.clone(), true, window, cx));
        cx.run_until_parked();
        let schemes = |cx: &mut gpui::VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.editors.editors.iter().map(|editor| editor.document().scheme.clone()).collect::<Vec<_>>());
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("imagePreview.reopenAsText", Vec::new(), window, cx)));
        cx.run_until_parked();
        assert_eq!(schemes(cx), ["file"]);
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("imagePreview.reopenAsPreview", Vec::new(), window, cx)));
        cx.run_until_parked();
        assert_eq!(schemes(cx), [WEBVIEW_PANEL_SCHEME]);
    }

    /// mediaPreview.contribution.ts registers without `singlePerResource`: opening an image previewed in another
    /// group gives the active group a preview of its own.
    #[gpui::test]
    fn an_image_previewed_in_another_group_gets_a_preview_in_the_active_one(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 (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 image = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../port/fixtures/webviews/image.png");
        let text = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.open_file(image.clone(), true, window, cx);
            workbench.open_file(text.clone(), true, window, cx);
            workbench.execute_command("workbench.action.splitEditorRight", Vec::new(), window, cx);
        });
        cx.run_until_parked();
        workbench.update_in(cx, |workbench, window, cx| workbench.open_file(image.clone(), true, window, cx));
        cx.run_until_parked();
        let (active, schemes) = workbench.read_with(cx, |workbench, _| {
            let groups = workbench.groups_in_grid_order();
            let schemes = |group| workbench.editors.group_tabs(group).0.iter().map(|editor| editor.document().scheme.clone()).collect::<Vec<_>>();
            (workbench.editors.id == groups[1], [schemes(groups[0]), schemes(groups[1])])
        });
        assert!(active, "the second group stays active");
        assert_eq!(schemes, [[WEBVIEW_PANEL_SCHEME, "file"], ["file", WEBVIEW_PANEL_SCHEME]]);
    }
}