Skip to content

Visual Studio Code, rebuilt in Rust

Rust

feat(media-preview): preview resources of extension file systems

rokartur9edb25498b6d
diff --git a/README.md b/README.md
index 4740b8c2b5d..cd98490be4f 100644
--- a/README.md
+++ b/README.md
@@ -11,8 +11,8 @@ Coverage of VS Code 1.147.0, from [port/ledger.md](port/ledger.md) (584 rows). V
```mermaid
pie showData
- "verified" : 408
- "ported" : 22
+ "verified" : 409
+ "ported" : 21
"removed" : 126
"n/a" : 28
```
@@ -20,7 +20,7 @@ pie showData
| area | verified | ported | removed | n/a | verified of in scope |
|---|---:|---:|---:|---:|---|
| src/vs/platform | 68 | 1 | 30 | 13 | `████████████████████ 99%` |
-| workbench contribution | 59 | 9 | 30 | 3 | `█████████████████░░░ 87%` |
+| workbench contribution | 60 | 8 | 30 | 3 | `██████████████████░░ 88%` |
| built-in extension | 88 | 1 | 6 | 0 | `████████████████████ 99%` |
| MainThread* shape (Rust side) | 59 | 0 | 30 | 0 | `████████████████████ 100%` |
| workbench service | 58 | 7 | 23 | 7 | `██████████████████░░ 89%` |
@@ -31,7 +31,7 @@ pie showData
| src/vs/editor | 0 | 2 | 1 | 1 | `░░░░░░░░░░░░░░░░░░░░ 0%` |
| src/vs/base | 0 | 0 | 2 | 3 | `████████████████████ 100%` |
| port feature | 1 | 0 | 0 | 0 | `████████████████████ 100%` |
-| **all** | **408** | **22** | **126** | **28** | `███████████████████░ 95%` |
+| **all** | **409** | **21** | **126** | **28** | `███████████████████░ 95%` |
<!-- coverage:end -->
`removed` are parts left out by decision: AI features, Microsoft services, telemetry, remote and tunnels ([port/notes.md](port/notes.md)). `n/a` are upstream test infrastructure and the Electron process, IPC and DOM layers the native architecture replaces.
diff --git a/native/crates/app/src/host_sync.rs b/native/crates/app/src/host_sync.rs
index 4dc812246f4..38f7c45ee2f 100644
--- a/native/crates/app/src/host_sync.rs
+++ b/native/crates/app/src/host_sync.rs
@@ -55,6 +55,7 @@ pub enum FileJob {
Reverse(FileUndo),
Write(files::Resource, Vec<u8>),
Read(files::Resource, oneshot::Sender<files::Result<Vec<u8>>>),
+ Stat(files::Resource, oneshot::Sender<files::Result<files::Stat>>),
}
pub struct FileWork {
@@ -79,6 +80,10 @@ impl FileWork {
let _ = bytes.send(files::read_file(fs, &resource));
Ok(FileUndo::default())
}
+ FileJob::Stat(resource, stat) => {
+ let _ = stat.send(files::stat(fs, &resource));
+ Ok(FileUndo::default())
+ }
};
let _ = self.reply.send(result);
}
@@ -532,6 +537,13 @@ impl HostSync {
receiver
}
+ /// `fileService.stat` on the host thread.
+ pub fn stat_file(&self, resource: files::Resource) -> oneshot::Receiver<files::Result<files::Stat>> {
+ let (reply, receiver) = oneshot::channel();
+ drop(self.run_files(FileJob::Stat(resource, reply)));
+ receiver
+ }
+
/// Reads the activation events of the extensions the host runs.
pub fn set_running_extensions(&mut self, extensions: &[ScannedExtension]) {
self.activation_events = extensions.iter().flat_map(|extension| exthost::activation_events::read_activation_events(&extension.id, &extension.description)).collect();
diff --git a/native/crates/app/src/workbench/media_preview.rs b/native/crates/app/src/workbench/media_preview.rs
index 8fc7462b714..608f02f294f 100644
--- a/native/crates/app/src/workbench/media_preview.rs
+++ b/native/crates/app/src/workbench/media_preview.rs
@@ -32,6 +32,11 @@ 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];
@@ -45,8 +50,10 @@ pub(super) enum MediaKind {
/// What the status bar shows of a preview (mediaPreviewStatusBar.ts), and an image's view state.
pub(super) struct MediaPreview {
kind: MediaKind,
- pub(super) path: PathBuf,
+ 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)>,
@@ -98,11 +105,6 @@ impl Workbench {
/// 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 {
- let path = PathBuf::from(resource["path"].as_str().unwrap_or_default());
- if resource["scheme"] != "file" {
- // shortcut: previews read `file` resources only; other file systems wait for MainThreadFileSystem reads.
- return Outcome::error(format!("Unable to preview {}", path.display()));
- }
// 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));
@@ -113,17 +115,18 @@ impl Workbench {
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 title = path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
- let roots = json!({ "enableScripts": true, "localResourceRoots": [{ "scheme": "file", "path": path.parent().unwrap_or(Path::new("/")) }] });
+ 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 });
let mut panel = WebviewPanel::new(handle.clone(), WEBVIEW_PANEL_SCHEME.into(), placeholder, view_type, title, &Value::Null, roots, retain, custom);
- let file_size = std::fs::metadata(&path).ok().map(|metadata| metadata.len());
- let media = MediaPreview { kind, path, file_size, scale: Value::Null, dimensions: None, view_state: Value::Null };
- panel.html = media.page(&self.setting("mediaPreview.video.autoPlay"), &self.setting("mediaPreview.video.loop"));
+ 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
@@ -141,6 +144,32 @@ impl Workbench {
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>) {
@@ -156,15 +185,21 @@ impl Workbench {
cx.notify();
}
request @ ("get-codecs" | "get-webm-type") => {
- let (request, kind, path, handle) = (request.to_owned(), media.kind, media.path.clone(), handle.to_owned());
+ 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 = cx.background_executor().spawn({
- let path = path.clone();
- async move { codecs::read_file_media_info(&path) }
- })
- .await;
+ 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, &path, info),
+ "get-codecs" => codecs_message(kind, &resource, info),
_ => Some(webm_type_message(info)),
};
let _ = workbench.update(cx, |workbench, _| {
@@ -178,8 +213,8 @@ impl Workbench {
.detach();
}
"reopen-as-text" => drop(self.reopen_active_editor_with(Some("default".into()), window, cx)),
- "open-externally" if can_open_externally(&media.path) => {
- let path = media.path.clone();
+ "open-externally" if can_open_externally(&media.resource) => {
+ let path = PathBuf::from(&media.resource.path);
cx.open_with_system(&path);
}
_ => {}
@@ -245,19 +280,26 @@ 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.path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
- // `asWebviewUri`, with mediaPlayerEditorInput.ts' `version` query against the cache.
- let src = format!("https://file+.vscode-resource.vscode-cdn.net{}?version={}", encode_path(&self.path), nanos() / 1_000_000);
+ 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 => {
- // The Git LFS pointer messages are for `git` resources only, which the previews do not read.
+ // 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!("An error occurred while loading the image.").to_string())
+ .replace("{{load_error}}", &json!(load_error).to_string())
}
MediaKind::Audio | MediaKind::Video => {
let audio = self.kind == MediaKind::Audio;
@@ -269,11 +311,16 @@ impl MediaPreview {
format!("<video src=\"{}\" controls playsinline{auto_play}{looped}></video>", escape(&src))
}
};
- let error = match audio {
- true => "An error occurred while loading the audio file.",
- false => "An error occurred while loading the video file.",
+ 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())
@@ -285,10 +332,10 @@ impl MediaPreview {
/// 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, path: &Path, info: Option<codecs::MediaInfo>) -> Option<Value> {
+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(path) {
+ let open_externally: Vec<Value> = match can_open_externally(resource) {
true => vec![json!({ "label": "Open File", "message": "open-externally" })],
false => Vec::new(),
};
@@ -338,9 +385,9 @@ fn webm_type_message(info: Option<codecs::MediaInfo>) -> Value {
}
/// mediaPlayerEditorInput.ts `_canOpenExternally`: only files with a media extension, never ones the OS would run.
-fn can_open_externally(path: &Path) -> bool {
- let mime_type = crate::webview::mime_type(path);
- mime_type.starts_with("audio/") || mime_type.starts_with("video/")
+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`.
@@ -381,6 +428,25 @@ pub(super) fn encode_path(path: &Path) -> String {
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()
}
@@ -400,20 +466,32 @@ mod tests {
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 message = codecs_message(MediaKind::Video, Path::new("/w/a.webm"), info()).unwrap();
+ 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, Path::new("/w/a.wav"), Some(codecs::MediaInfo { container: "wav", tracks: vec![track("audio", "17", None)] })).unwrap();
+ 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, Path::new("/w/a.mp4"), Some(codecs::MediaInfo { container: "mp4", tracks: vec![] })), None);
+ 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);
}
@@ -421,10 +499,12 @@ mod tests {
#[test]
fn fills_every_placeholder_of_the_pages() {
for kind in [MediaKind::Image, MediaKind::Video, MediaKind::Audio] {
- let media = MediaPreview { kind, path: PathBuf::from("/w/a.png"), file_size: None, 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}");
+ 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}");
+ }
}
}
@@ -440,6 +520,94 @@ mod tests {
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) {
diff --git a/native/crates/app/src/workbench/media_preview/player.html b/native/crates/app/src/workbench/media_preview/player.html
index 47e9b410657..ae6254df874 100644
--- a/native/crates/app/src/workbench/media_preview/player.html
+++ b/native/crates/app/src/workbench/media_preview/player.html
@@ -89,7 +89,7 @@
}
</style>
</head>
-<body data-vscode-context='{ "preventDefaultContextMenuItems": true }'>
+<body{{body_class}} data-vscode-context='{ "preventDefaultContextMenuItems": true }'>
<div class="codec-warning">
<div class="codec-warning-message" role="status"></div>
<div class="codec-warning-actions"></div>
diff --git a/native/crates/app/src/workbench/webview_panels.rs b/native/crates/app/src/workbench/webview_panels.rs
index 08fdd139bf5..08f4877a05a 100644
--- a/native/crates/app/src/workbench/webview_panels.rs
+++ b/native/crates/app/src/workbench/webview_panels.rs
@@ -716,9 +716,6 @@ impl Workbench {
/// The file a custom editor or media preview panel shows.
pub(super) fn webview_resource(&self, path: &Path) -> Option<PathBuf> {
let panel = self.webview_panel(path)?;
- if let Some(media) = &panel.media {
- return Some(media.path.clone());
- }
let resource = &panel.custom.as_ref()?.resource;
(resource["scheme"] == "file").then(|| PathBuf::from(resource["path"].as_str().unwrap_or_default()))
}
diff --git a/port/ledger.md b/port/ledger.md
index 9d483a3a0af..6343e4d2693 100644
--- a/port/ledger.md
+++ b/port/ledger.md
@@ -508,7 +508,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston
| workbench/contrib/markdown | workbench contribution | M17 | verified | | workbench/markdown_document.rs renderMarkdownDocument (extension editor, walkthroughs): heading ids, per-caller link protocols, relative images; cargo test -p app markdown_document (markdownDocumentRenderer.test.ts both cases); `MarkedHighlight` code blocks: a fenced block's language by its name or its info string's first word, tokenized by textToHtmlTokenizer.ts `tokenizeToString` into `mtk` spans with the token colors CSS in the extension editor, walkthrough and release notes pages (editor/clipboard.rs `tokenize_to_string`: cargo test -p app fenced_code_blocks_are_tokenized_in_their_language). pulldown-cmark parses the markdown in marked's place (a Rust port has no JavaScript parser) |
| workbench/contrib/markers | workbench contribution | M13 | verified | | markersTreeViewer.ts `MarkerViewModel`: each marker keeps its quick fixes, asked once, until its resource's markers change (cargo test -p app each_problems_marker_keeps_its_quick_fixes). Indent guides and the focused row's outline apart from the selection (cargo test -p app the_focus_outline_follows). status bar problems entry and tooltip from markers (workbench/diagnostics.rs), its click toggles the Problems view; the Problems panel view (workbench/problems_view.rs: resources by worst severity then path, markers by severity then position, count badges, the tab badge, open on click, Collapse All, `workbench.actions.view.problems` and `toggleProblems`): cargo test -p app problems_view the_debug_console_and_test_results_are_panel_views, ui-pair port/results/problems.md; MarkersFileDecorations (count letter, error/warning color, bubbling, weight over other providers, `problems.decorations.enabled`) on Explorer rows and tabs (workbench/file_decorations.rs): cargo test -p app problems_decorate_the_file; filter box (workbench/view_filter.rs in the panel title at the panel's filter width, markers_filter.rs: markersFilterOptions.test.ts cases; text, `!`, globs, `@source:`, severity, active file and excluded files toggles, filter history, memento), filters menu, related information and multi-line rows, View as Table with column sashes (workbench/problems_table.rs), quick fixes on hovered rows (workbench/problems_quick_fix.rs): cargo test -p app markers_filter problems_view problems_table; ui-pair port/fixtures/problems/steps-filter.json and steps-table.json (port/results/problems.md); the selected row (first marker on focus, Up/Down, Enter and Cmd+Down open, `problems.action.copy`/`copyMessage`/`copyRelatedInformationMessage`, Cmd+. on the selected marker, `problemFocus`/`relatedInformationFocus`): cargo test -p app problems; ui-pair .vscode/settings.json and e.ts quick fix (port/results/language-features.md JSON settings, Problems quick fix). Multi-selection in the tree (`multipleSelectionSupport`: Shift+Up/Down, Cmd+click toggles, Shift+click ranges from the anchor, Copy over `getFocusedSelectedElements`) and open to the side (`problems.action.openToSide` on Ctrl+Enter, Ctrl/Cmd/Alt+click as listService.ts `sideBySide`, into `SIDE_GROUP`): cargo test -p app markers_select_together_and_open_to_the_side. Resource row: name 30px in, count badge 19px round 10px after the label at the line's bottom (cargo test -p app the_resource_name_sits_after_the_twistie_at_its_exact_line_height; ui-pair problems: chevron, icon x, name, description and badge box at the reference's device pixels, the file icon and the badge digit 1 device px low); a hovered marker without a model gets its quick fixes once its file opens (markersTreeViewer.ts `getModel(waitForModel)`; cargo test -p app a_problems_marker_gets_its_quick_fixes_once_its_file_opens) |
| workbench/contrib/mcp | workbench contribution | | removed | | no sign-in/AI by decision (port/notes.md); not ported |
-| workbench/contrib/mediaPreview | workbench contribution | M17 | ported | [3 M] media_preview.rs:103: non-file resources (stat, Git LFS pointers, whole-file codec reads) | An image or media file previewed in another group gets a preview of its own in the active group (mediaPreview.contribution.ts registers without `singlePerResource`: cargo test -p app an_image_previewed_in_another_group_gets_a_preview_in_the_active_one); image, video and audio previews as built-in editors (workbench/media_preview.rs, pages in media_preview/*.html), resolver priority builtin, zoom commands and Select Zoom Level picker, zoom, dimensions and file size status entries, Reopen as Source Text / Image Preview, the file's tab icon and Explorer reveal; `FIXTURE=media-preview-tests port/tools/webview-check` 6/6 on both apps; cargo test -p app media_preview; ui-pair image, video and audio, the breadcrumbs bar with the editor type control and its Reopen/Set Default menu (editor-type-reopen.json; port/results/webviews.md); cargo test -p app lists_the_editor_types; the focus outline at open (ui-pair media-preview-focus.json, background and foreground); cargo test -p app opens_a_startup_image. Not done: Copy image, legacy `media-preview` editor migration. The player page's codec warnings and WebM type (mediaCodecs.ts as media_preview/codecs.rs, mediaPlayerEditorInput.ts `_postCodecs`, `_postWebmType`): cargo test -p app media_preview::codecs, answers_the_player_page_with_the_file_s_codecs |
+| workbench/contrib/mediaPreview | workbench contribution | M17 | verified | | Resources of extension file systems: the file service's stat for the size, their parent as the webview's resource root, codecs read from the whole file up to mediaCodecs.ts' limit, and a `git` Git LFS pointer as the preview's message (mediaPreview.ts `isGitLfsPointer`; cargo test -p app previews_read_git_resources_and_show_git_lfs_pointers_as_a_message); An image or media file previewed in another group gets a preview of its own in the active group (mediaPreview.contribution.ts registers without `singlePerResource`: cargo test -p app an_image_previewed_in_another_group_gets_a_preview_in_the_active_one); image, video and audio previews as built-in editors (workbench/media_preview.rs, pages in media_preview/*.html), resolver priority builtin, zoom commands and Select Zoom Level picker, zoom, dimensions and file size status entries, Reopen as Source Text / Image Preview, the file's tab icon and Explorer reveal; `FIXTURE=media-preview-tests port/tools/webview-check` 6/6 on both apps; cargo test -p app media_preview; ui-pair image, video and audio, the breadcrumbs bar with the editor type control and its Reopen/Set Default menu (editor-type-reopen.json; port/results/webviews.md); cargo test -p app lists_the_editor_types; the focus outline at open (ui-pair media-preview-focus.json, background and foreground); cargo test -p app opens_a_startup_image. Not done: Copy image, legacy `media-preview` editor migration. The player page's codec warnings and WebM type (mediaCodecs.ts as media_preview/codecs.rs, mediaPlayerEditorInput.ts `_postCodecs`, `_postWebmType`): cargo test -p app media_preview::codecs, answers_the_player_page_with_the_file_s_codecs |
| workbench/contrib/mergeEditor | workbench contribution | M14 | ported | [3 L] merge_editor_view.rs:5: no base-to-result diff backgrounds in the result, no "Comparing with" highlights in base <br> [3 L] merge_editor_view.rs:962: the inputs are not code editors: a press places a steady cursor, with no selection, cursor keys or blink | merge_editor.rs model (mapping, conflict states, accept/combine) and workbench/editor_view/merge_editor_view.rs (input 1/2, result, base view, layouts, gutter checkboxes, `_open.mergeEditor`, dev commands, the inputs' keyboard focus and Toggle Between Inputs, the active range in the last focused input or the result): cargo test -p app merge |
| workbench/contrib/meteredConnection | workbench contribution | M19 | verified | | the metered warning status entry and Configure Metered Connection (workbench/power.rs); port/tools/shell-check (port/fixtures/extensions/shell-tests, 6/6); cargo test -p app metered_connection |
| workbench/contrib/modernUI | workbench contribution | M11 | verified | | the modern layout only: the classic layout (`workbench.experimental.modernUI: false`) is removed by Artur's decision (port/notes.md Modern UI); `window.density.layout` compact and the Manage menu's Layout Density (cargo test -p app -- compact_density layout_density; ui-pair m11/layout-density.json in both densities with SETTINGS `{"window.density.layout": "compact"}`, port/results/layout-density.md) |