Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
project_panel: Add SVG preview context menu item (#65539)
Manoj skcb13b37a6d80
diff --git a/Cargo.lock b/Cargo.lockindex 39b99bf26e3..a8c87d3d831 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -13989,6 +13989,7 @@ dependencies = ["serde_json","settings","smallvec",+ "svg_preview","telemetry","tempfile","theme",@@ -17474,6 +17475,7 @@ dependencies = ["gpui","language","multi_buffer",+ "project","ui","workspace","zed_actions",diff --git a/crates/project_panel/Cargo.toml b/crates/project_panel/Cargo.tomlindex c0429da57b3..7dd40a2b7c3 100644--- a/crates/project_panel/Cargo.toml+++ b/crates/project_panel/Cargo.toml@@ -49,6 +49,7 @@ telemetry.workspace = truenotifications.workspace = truefs.workspace = truelog.workspace = true+svg_preview.workspace = true[dev-dependencies]client = { workspace = true, features = ["test-support"] }diff --git a/crates/project_panel/src/project_panel.rs b/crates/project_panel/src/project_panel.rsindex ecbf0bd90c4..f7bedca9993 100644--- a/crates/project_panel/src/project_panel.rs+++ b/crates/project_panel/src/project_panel.rs@@ -58,6 +58,7 @@ use std::{sync::Arc,time::{Duration, Instant},};+use svg_preview::svg_preview_view::SvgPreviewView;use theme_settings::ThemeSettings;use ui::{ContextMenu, DecoratedIcon, IconDecoration, IconDecorationKind, IndentGuideColors,@@ -449,6 +450,8 @@ actions!(OpenMarkdownPreview,/// Opens the context menu for the selected entry.OpenContextMenu,+ /// Opens an SVG preview for the selected file.+ OpenSvgPreview,]);@@ -1147,11 +1150,10 @@ impl ProjectPanel {let is_remote = project.is_remote();let is_collab = project.is_via_collab();let is_local = project.is_local() || project.is_via_wsl_with_host_interop(cx);- let is_markdown = !is_dir- && MarkdownPreviewView::is_markdown_path(- entry.path.as_std_path(),- project.languages(),- );+ let file_name = Path::new(entry_file_name(entry, worktree.root_name()));+ let is_markdown =+ !is_dir && MarkdownPreviewView::is_markdown_path(file_name, project.languages());+ let is_svg = !is_dir && SvgPreviewView::is_svg_path(file_name);let settings = ProjectPanelSettings::get_global(cx);let visible_worktrees_count = project.visible_worktrees(cx).count();@@ -1183,6 +1185,9 @@ impl ProjectPanel {menu.when(is_markdown, |menu| {menu.action("Open Markdown Preview", Box::new(OpenMarkdownPreview))})+ .when(is_svg, |menu| {+ menu.action("Open SVG Preview", Box::new(OpenSvgPreview))+ }).when(is_dir, |menu| {menu.action("Search Inside", Box::new(NewSearchInDirectory))})@@ -1203,6 +1208,9 @@ impl ProjectPanel {.when(is_markdown, |menu| {menu.action("Open Markdown Preview", Box::new(OpenMarkdownPreview))})+ .when(is_svg, |menu| {+ menu.action("Open SVG Preview", Box::new(OpenSvgPreview))+ }).when(is_dir, |menu| {menu.separator().action("Find in Folder…", Box::new(NewSearchInDirectory))@@ -1995,21 +2003,15 @@ impl ProjectPanel {window: &mut Window,cx: &mut Context<Self>,) {- let Some((worktree, entry)) = self.selected_entry(cx) else {+ let Some((project_path, file_name)) = self.selected_file(cx) else {return;};- if !entry.is_file()- || !MarkdownPreviewView::is_markdown_path(- entry.path.as_std_path(),- self.project.read(cx).languages(),- )- {+ if !MarkdownPreviewView::is_markdown_path(+ Path::new(file_name),+ self.project.read(cx).languages(),+ ) {return;}- let project_path = ProjectPath {- worktree_id: worktree.id(),- path: entry.path.clone(),- };self.workspace.update(cx, |workspace, cx| {MarkdownPreviewView::open_for_project_path(project_path, workspace, window, cx);@@ -2017,6 +2019,25 @@ impl ProjectPanel {.ok();}+ fn open_svg_preview(+ &mut self,+ _: &OpenSvgPreview,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ let Some((project_path, file_name)) = self.selected_file(cx) else {+ return;+ };+ if !SvgPreviewView::is_svg_path(Path::new(file_name)) {+ return;+ }+ self.workspace+ .update(cx, |workspace, cx| {+ SvgPreviewView::open_for_project_path(project_path, workspace, window, cx)+ })+ .ok();+ }+fn open_internal(&mut self,allow_preview: bool,@@ -4054,14 +4075,20 @@ impl ProjectPanel {}fn selected_file_project_path(&self, cx: &App) -> Option<ProjectPath> {+ self.selected_file(cx).map(|(project_path, _)| project_path)+ }++ fn selected_file<'a>(&self, cx: &'a App) -> Option<(ProjectPath, &'a str)> {let (worktree, entry) = self.selected_sub_entry(cx)?;if entry.is_dir() {return None;}- Some(ProjectPath {- worktree_id: worktree.read(cx).id(),+ let worktree = worktree.read(cx);+ let project_path = ProjectPath {+ worktree_id: worktree.id(),path: entry.path.clone(),- })+ };+ Some((project_path, entry_file_name(entry, worktree.root_name())))}fn reveal_in_finder(@@ -7082,11 +7109,7 @@ impl ProjectPanel {suffix.display(path_style).to_string()})} else {- entry- .path- .file_name()- .map(|name| name.to_string())- .unwrap_or_else(|| root_name.as_unix_str().to_string())+ entry_file_name(entry, root_name).to_string()};let selection = SelectedEntry {@@ -7440,6 +7463,14 @@ impl StickyCandidate for StickyProjectPanelCandidate {}}+/// A single-file worktree's root entry has an empty path, so its name is the worktree's root name.+fn entry_file_name<'a>(entry: &'a Entry, root_name: &'a RelPath) -> &'a str {+ entry+ .path+ .file_name()+ .unwrap_or_else(|| root_name.as_unix_str())+}+fn item_width_estimate(depth: usize, item_text_chars: usize, is_symlink: bool) -> usize {const ICON_SIZE_FACTOR: usize = 2;let mut item_width = depth * ICON_SIZE_FACTOR + item_text_chars;@@ -7606,6 +7637,7 @@ impl Render for ProjectPanel {.on_action(cx.listener(Self::open_split_vertical)).on_action(cx.listener(Self::open_split_horizontal)).on_action(cx.listener(Self::open_markdown_preview))+ .on_action(cx.listener(Self::open_svg_preview)).on_action(cx.listener(Self::confirm)).on_action(cx.listener(Self::cancel)).on_action(cx.listener(Self::copy_path))diff --git a/crates/project_panel/src/project_panel_tests.rs b/crates/project_panel/src/project_panel_tests.rsindex e51bb45c41a..815dfd55ea1 100644--- a/crates/project_panel/src/project_panel_tests.rs+++ b/crates/project_panel/src/project_panel_tests.rs@@ -2494,6 +2494,42 @@ async fn test_copy_and_cut_write_to_system_clipboard(cx: &mut gpui::TestAppConte);}+#[gpui::test]+async fn test_open_svg_preview_for_single_file_worktree(cx: &mut gpui::TestAppContext) {+ init_test(cx);++ let fs = FakeFs::new(cx.executor());+ fs.insert_tree(+ path!("/root"),+ json!({+ "icon.svg": "<svg xmlns=\"http://www.w3.org/2000/svg\"/>",+ }),+ )+ .await;++ let project = Project::test(fs.clone(), [path!("/root/icon.svg").as_ref()], cx).await;+ let window = cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));+ let workspace = window+ .read_with(cx, |mw, _| mw.workspace().clone())+ .unwrap();+ let cx = &mut VisualTestContext::from_window(window.into(), cx);+ let panel = workspace.update_in(cx, ProjectPanel::new);+ cx.run_until_parked();++ select_path(&panel, "icon.svg", cx);+ panel.update_in(cx, |panel, window, cx| {+ panel.open_svg_preview(&OpenSvgPreview, window, cx);+ });+ cx.run_until_parked();++ workspace.update(cx, |workspace, cx| {+ assert!(+ workspace.active_item_as::<SvgPreviewView>(cx).is_some(),+ "a file opened as its own worktree should open an SVG preview"+ );+ });+}+#[gpui::test]async fn test_remove_opened_file(cx: &mut gpui::TestAppContext) {init_test_with_editor(cx);diff --git a/crates/svg_preview/Cargo.toml b/crates/svg_preview/Cargo.tomlindex b206b616d97..265c5b4a333 100644--- a/crates/svg_preview/Cargo.toml+++ b/crates/svg_preview/Cargo.toml@@ -18,6 +18,7 @@ multi_buffer.workspace = truefile_icons.workspace = truegpui.workspace = truelanguage.workspace = true+project.workspace = trueui.workspace = trueworkspace.workspace = truezed_actions.workspace = truediff --git a/crates/svg_preview/src/svg_preview_view.rs b/crates/svg_preview/src/svg_preview_view.rsindex 8ab81b9ae9d..0d912b9dfb4 100644--- a/crates/svg_preview/src/svg_preview_view.rs+++ b/crates/svg_preview/src/svg_preview_view.rs@@ -1,4 +1,5 @@use std::mem;+use std::path::Path;use std::sync::Arc;use file_icons::FileIcons;@@ -8,8 +9,10 @@ use gpui::{};use language::{Buffer, BufferEvent};use multi_buffer::MultiBuffer;+use project::ProjectPath;use ui::prelude::*;use workspace::item::Item;+use workspace::notifications::NotifyResultExt;use workspace::{Pane, Workspace};use crate::{OpenFollowingPreview, OpenPreview, OpenPreviewToTheSide};@@ -124,6 +127,35 @@ impl SvgPreviewView {});}+ pub fn open_for_project_path(+ project_path: ProjectPath,+ workspace: &mut Workspace,+ window: &mut Window,+ cx: &mut Context<Workspace>,+ ) {+ let open_buffer = workspace+ .project()+ .update(cx, |project, cx| project.open_buffer(project_path, cx));++ cx.spawn_in(window, async move |workspace, cx| {+ let Some(buffer) = open_buffer+ .await+ .notify_workspace_async_err(workspace.clone(), cx)+ else {+ return;+ };++ workspace+ .update_in(cx, |workspace, window, cx| {+ let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));+ let pane = workspace.active_pane().clone();+ Self::open_preview_in_pane(workspace, buffer, pane, window, cx);+ })+ .ok();+ })+ .detach();+ }+fn set_current(&mut self,image: Option<Result<Arc<RenderImage>, SharedString>>,@@ -190,16 +222,17 @@ impl SvgPreviewView {)}+ pub fn is_svg_path(path: &Path) -> bool {+ path.extension()+ .is_some_and(|extension| extension.eq_ignore_ascii_case("svg"))+ }+pub fn is_svg_file(buffer: &Entity<MultiBuffer>, cx: &App) -> bool {buffer.read(cx).as_singleton().and_then(|buffer| buffer.read(cx).file())- .is_some_and(|file| {- std::path::Path::new(file.file_name(cx))- .extension()- .is_some_and(|ext| ext.eq_ignore_ascii_case("svg"))- })+ .is_some_and(|file| Self::is_svg_path(Path::new(file.file_name(cx))))}pub fn open_preview_in_pane(