image_viewer.rs

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