1mod image_info;
2mod image_viewer_settings;
3
4use std::path::PathBuf;
5
6use anyhow::Context as _;
7use editor::{EditorSettings, items::entry_git_aware_label_color};
8use file_icons::FileIcons;
9use gpui::{
10 AnyElement, App, Bounds, Context, Entity, EventEmitter, FocusHandle, Focusable,
11 InteractiveElement, IntoElement, ObjectFit, ParentElement, Render, Styled, Task, WeakEntity,
12 Window, canvas, div, fill, img, opaque_grey, point, size,
13};
14use language::{DiskState, File as _};
15use persistence::IMAGE_VIEWER;
16use project::{ImageItem, Project, ProjectPath, image_store::ImageItemEvent};
17use settings::Settings;
18use theme::Theme;
19use ui::prelude::*;
20use util::paths::PathExt;
21use workspace::{
22 ItemId, ItemSettings, Pane, ToolbarItemLocation, Workspace, WorkspaceId, delete_unloaded_items,
23 item::{BreadcrumbText, Item, ProjectItem, SerializableItem, TabContentParams},
24};
25
26pub use crate::image_info::*;
27pub use crate::image_viewer_settings::*;
28
29pub struct ImageView {
30 image_item: Entity<ImageItem>,
31 project: Entity<Project>,
32 focus_handle: FocusHandle,
33}
34
35impl ImageView {
36 pub fn new(
37 image_item: Entity<ImageItem>,
38 project: Entity<Project>,
39 window: &mut Window,
40 cx: &mut Context<Self>,
41 ) -> Self {
42 cx.subscribe(&image_item, Self::on_image_event).detach();
43 cx.on_release_in(window, |this, window, cx| {
44 let image_data = this.image_item.read(cx).image.clone();
45 if let Some(image) = image_data.clone().get_render_image(window, cx) {
46 cx.drop_image(image, None);
47 }
48 image_data.remove_asset(cx);
49 })
50 .detach();
51
52 Self {
53 image_item,
54 project,
55 focus_handle: cx.focus_handle(),
56 }
57 }
58
59 fn on_image_event(
60 &mut self,
61 _: Entity<ImageItem>,
62 event: &ImageItemEvent,
63 cx: &mut Context<Self>,
64 ) {
65 match event {
66 ImageItemEvent::MetadataUpdated
67 | ImageItemEvent::FileHandleChanged
68 | ImageItemEvent::Reloaded => {
69 cx.emit(ImageViewEvent::TitleChanged);
70 cx.notify();
71 }
72 ImageItemEvent::ReloadNeeded => {}
73 }
74 }
75}
76
77pub enum ImageViewEvent {
78 TitleChanged,
79}
80
81impl EventEmitter<ImageViewEvent> for ImageView {}
82
83impl Item for ImageView {
84 type Event = ImageViewEvent;
85
86 fn to_item_events(event: &Self::Event, mut f: impl FnMut(workspace::item::ItemEvent)) {
87 match event {
88 ImageViewEvent::TitleChanged => {
89 f(workspace::item::ItemEvent::UpdateTab);
90 f(workspace::item::ItemEvent::UpdateBreadcrumbs);
91 }
92 }
93 }
94
95 fn for_each_project_item(
96 &self,
97 cx: &App,
98 f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
99 ) {
100 f(self.image_item.entity_id(), self.image_item.read(cx))
101 }
102
103 fn is_singleton(&self, _cx: &App) -> bool {
104 true
105 }
106
107 fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
108 let abs_path = self.image_item.read(cx).abs_path(cx)?;
109 let file_path = abs_path.compact().to_string_lossy().to_string();
110 Some(file_path.into())
111 }
112
113 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
114 let project_path = self.image_item.read(cx).project_path(cx);
115
116 let label_color = if ItemSettings::get_global(cx).git_status {
117 let git_status = self
118 .project
119 .read(cx)
120 .project_path_git_status(&project_path, cx)
121 .map(|status| status.summary())
122 .unwrap_or_default();
123
124 self.project
125 .read(cx)
126 .entry_for_path(&project_path, cx)
127 .map(|entry| {
128 entry_git_aware_label_color(git_status, entry.is_ignored, params.selected)
129 })
130 .unwrap_or_else(|| params.text_color())
131 } else {
132 params.text_color()
133 };
134
135 Label::new(self.tab_content_text(params.detail.unwrap_or_default(), cx))
136 .single_line()
137 .color(label_color)
138 .when(params.preview, |this| this.italic())
139 .into_any_element()
140 }
141
142 fn tab_content_text(&self, _: usize, cx: &App) -> SharedString {
143 self.image_item
144 .read(cx)
145 .file
146 .file_name(cx)
147 .to_string_lossy()
148 .to_string()
149 .into()
150 }
151
152 fn tab_icon(&self, _: &Window, cx: &App) -> Option<Icon> {
153 let path = self.image_item.read(cx).abs_path(cx)?;
154 ItemSettings::get_global(cx)
155 .file_icons
156 .then(|| FileIcons::get_icon(&path, cx))
157 .flatten()
158 .map(Icon::from_path)
159 }
160
161 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
162 let show_breadcrumb = EditorSettings::get_global(cx).toolbar.breadcrumbs;
163 if show_breadcrumb {
164 ToolbarItemLocation::PrimaryLeft
165 } else {
166 ToolbarItemLocation::Hidden
167 }
168 }
169
170 fn breadcrumbs(&self, _theme: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
171 let text = breadcrumbs_text_for_image(self.project.read(cx), self.image_item.read(cx), cx);
172 Some(vec![BreadcrumbText {
173 text,
174 highlights: None,
175 font: None,
176 }])
177 }
178
179 fn clone_on_split(
180 &self,
181 _workspace_id: Option<WorkspaceId>,
182 _: &mut Window,
183 cx: &mut Context<Self>,
184 ) -> Option<Entity<Self>>
185 where
186 Self: Sized,
187 {
188 Some(cx.new(|cx| Self {
189 image_item: self.image_item.clone(),
190 project: self.project.clone(),
191 focus_handle: cx.focus_handle(),
192 }))
193 }
194
195 fn has_deleted_file(&self, cx: &App) -> bool {
196 self.image_item.read(cx).file.disk_state() == DiskState::Deleted
197 }
198}
199
200fn breadcrumbs_text_for_image(project: &Project, image: &ImageItem, cx: &App) -> String {
201 let path = image.file.file_name(cx);
202 if project.visible_worktrees(cx).count() <= 1 {
203 return path.to_string_lossy().to_string();
204 }
205
206 project
207 .worktree_for_id(image.project_path(cx).worktree_id, cx)
208 .map(|worktree| {
209 PathBuf::from(worktree.read(cx).root_name())
210 .join(path)
211 .to_string_lossy()
212 .to_string()
213 })
214 .unwrap_or_else(|| path.to_string_lossy().to_string())
215}
216
217impl SerializableItem for ImageView {
218 fn serialized_item_kind() -> &'static str {
219 "ImageView"
220 }
221
222 fn deserialize(
223 project: Entity<Project>,
224 _workspace: WeakEntity<Workspace>,
225 workspace_id: WorkspaceId,
226 item_id: ItemId,
227 window: &mut Window,
228 cx: &mut App,
229 ) -> Task<anyhow::Result<Entity<Self>>> {
230 window.spawn(cx, async move |cx| {
231 let image_path = IMAGE_VIEWER
232 .get_image_path(item_id, workspace_id)?
233 .context("No image path found")?;
234
235 let (worktree, relative_path) = project
236 .update(cx, |project, cx| {
237 project.find_or_create_worktree(image_path.clone(), false, cx)
238 })?
239 .await
240 .context("Path not found")?;
241 let worktree_id = worktree.update(cx, |worktree, _cx| worktree.id())?;
242
243 let project_path = ProjectPath {
244 worktree_id,
245 path: relative_path.into(),
246 };
247
248 let image_item = project
249 .update(cx, |project, cx| project.open_image(project_path, cx))?
250 .await?;
251
252 cx.update(
253 |window, cx| Ok(cx.new(|cx| ImageView::new(image_item, project, window, cx))),
254 )?
255 })
256 }
257
258 fn cleanup(
259 workspace_id: WorkspaceId,
260 alive_items: Vec<ItemId>,
261 _window: &mut Window,
262 cx: &mut App,
263 ) -> Task<anyhow::Result<()>> {
264 delete_unloaded_items(
265 alive_items,
266 workspace_id,
267 "image_viewers",
268 &IMAGE_VIEWER,
269 cx,
270 )
271 }
272
273 fn serialize(
274 &mut self,
275 workspace: &mut Workspace,
276 item_id: ItemId,
277 _closing: bool,
278 _window: &mut Window,
279 cx: &mut Context<Self>,
280 ) -> Option<Task<anyhow::Result<()>>> {
281 let workspace_id = workspace.database_id()?;
282 let image_path = self.image_item.read(cx).abs_path(cx)?;
283
284 Some(cx.background_spawn({
285 async move {
286 log::debug!("Saving image at path {image_path:?}");
287 IMAGE_VIEWER
288 .save_image_path(item_id, workspace_id, image_path)
289 .await
290 }
291 }))
292 }
293
294 fn should_serialize(&self, _event: &Self::Event) -> bool {
295 false
296 }
297}
298
299impl EventEmitter<()> for ImageView {}
300impl Focusable for ImageView {
301 fn focus_handle(&self, _cx: &App) -> FocusHandle {
302 self.focus_handle.clone()
303 }
304}
305
306impl Render for ImageView {
307 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
308 let image = self.image_item.read(cx).image.clone();
309 let checkered_background = |bounds: Bounds<Pixels>,
310 _,
311 window: &mut Window,
312 _cx: &mut App| {
313 let square_size = 32.0;
314
315 let start_y = bounds.origin.y.0;
316 let height = bounds.size.height.0;
317 let start_x = bounds.origin.x.0;
318 let width = bounds.size.width.0;
319
320 let mut y = start_y;
321 let mut x = start_x;
322 let mut color_swapper = true;
323 // draw checkerboard pattern
324 while y <= start_y + height {
325 // Keeping track of the grid in order to be resilient to resizing
326 let start_swap = color_swapper;
327 while x <= start_x + width {
328 let rect =
329 Bounds::new(point(px(x), px(y)), size(px(square_size), px(square_size)));
330
331 let color = if color_swapper {
332 opaque_grey(0.6, 0.4)
333 } else {
334 opaque_grey(0.7, 0.4)
335 };
336
337 window.paint_quad(fill(rect, color));
338 color_swapper = !color_swapper;
339 x += square_size;
340 }
341 x = start_x;
342 color_swapper = !start_swap;
343 y += square_size;
344 }
345 };
346
347 let checkered_background = canvas(|_, _, _| (), checkered_background)
348 .border_2()
349 .border_color(cx.theme().styles.colors.border)
350 .size_full()
351 .absolute()
352 .top_0()
353 .left_0();
354
355 div()
356 .track_focus(&self.focus_handle(cx))
357 .size_full()
358 .child(checkered_background)
359 .child(
360 div()
361 .flex()
362 .justify_center()
363 .items_center()
364 .w_full()
365 // TODO: In browser based Tailwind & Flex this would be h-screen and we'd use w-full
366 .h_full()
367 .child(
368 img(image)
369 .object_fit(ObjectFit::ScaleDown)
370 .max_w_full()
371 .max_h_full()
372 .id("img"),
373 ),
374 )
375 }
376}
377
378impl ProjectItem for ImageView {
379 type Item = ImageItem;
380
381 fn for_project_item(
382 project: Entity<Project>,
383 _: Option<&Pane>,
384 item: Entity<Self::Item>,
385 window: &mut Window,
386 cx: &mut Context<Self>,
387 ) -> Self
388 where
389 Self: Sized,
390 {
391 Self::new(item, project, window, cx)
392 }
393}
394
395pub fn init(cx: &mut App) {
396 ImageViewerSettings::register(cx);
397 workspace::register_project_item::<ImageView>(cx);
398 workspace::register_serializable_item::<ImageView>(cx);
399}
400
401mod persistence {
402 use std::path::PathBuf;
403
404 use db::{
405 query,
406 sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
407 sqlez_macros::sql,
408 };
409 use workspace::{ItemId, WorkspaceDb, WorkspaceId};
410
411 pub struct ImageViewerDb(ThreadSafeConnection);
412
413 impl Domain for ImageViewerDb {
414 const NAME: &str = stringify!(ImageViewerDb);
415
416 const MIGRATIONS: &[&str] = &[sql!(
417 CREATE TABLE image_viewers (
418 workspace_id INTEGER,
419 item_id INTEGER UNIQUE,
420
421 image_path BLOB,
422
423 PRIMARY KEY(workspace_id, item_id),
424 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
425 ON DELETE CASCADE
426 ) STRICT;
427 )];
428 }
429
430 db::static_connection!(IMAGE_VIEWER, ImageViewerDb, [WorkspaceDb]);
431
432 impl ImageViewerDb {
433 query! {
434 pub async fn save_image_path(
435 item_id: ItemId,
436 workspace_id: WorkspaceId,
437 image_path: PathBuf
438 ) -> Result<()> {
439 INSERT OR REPLACE INTO image_viewers(item_id, workspace_id, image_path)
440 VALUES (?, ?, ?)
441 }
442 }
443
444 query! {
445 pub fn get_image_path(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<PathBuf>> {
446 SELECT image_path
447 FROM image_viewers
448 WHERE item_id = ? AND workspace_id = ?
449 }
450 }
451 }
452}