image_viewer.rs

  1mod image_info;
  2mod image_viewer_settings;
  3
  4use std::path::PathBuf;
  5
  6use anyhow::Context as _;
  7use editor::items::entry_git_aware_label_color;
  8use file_icons::FileIcons;
  9use gpui::{
 10    canvas, div, fill, img, opaque_grey, point, size, AnyElement, App, Bounds, Context, Entity,
 11    EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement, ObjectFit,
 12    ParentElement, Render, Styled, Task, WeakEntity, Window,
 13};
 14use persistence::IMAGE_VIEWER;
 15use project::{image_store::ImageItemEvent, ImageItem, Project, ProjectPath};
 16use settings::Settings;
 17use theme::Theme;
 18use ui::prelude::*;
 19use util::paths::PathExt;
 20use workspace::{
 21    item::{BreadcrumbText, Item, ProjectItem, SerializableItem, TabContentParams},
 22    ItemId, ItemSettings, ToolbarItemLocation, Workspace, WorkspaceId,
 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, _: &App) -> ToolbarItemLocation {
148        ToolbarItemLocation::PrimaryLeft
149    }
150
151    fn breadcrumbs(&self, _theme: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
152        let text = breadcrumbs_text_for_image(self.project.read(cx), self.image_item.read(cx), cx);
153        Some(vec![BreadcrumbText {
154            text,
155            highlights: None,
156            font: None,
157        }])
158    }
159
160    fn clone_on_split(
161        &self,
162        _workspace_id: Option<WorkspaceId>,
163        _: &mut Window,
164        cx: &mut Context<Self>,
165    ) -> Option<Entity<Self>>
166    where
167        Self: Sized,
168    {
169        Some(cx.new(|cx| Self {
170            image_item: self.image_item.clone(),
171            project: self.project.clone(),
172            focus_handle: cx.focus_handle(),
173        }))
174    }
175}
176
177fn breadcrumbs_text_for_image(project: &Project, image: &ImageItem, cx: &App) -> String {
178    let path = image.file.file_name(cx);
179    if project.visible_worktrees(cx).count() <= 1 {
180        return path.to_string_lossy().to_string();
181    }
182
183    project
184        .worktree_for_id(image.project_path(cx).worktree_id, cx)
185        .map(|worktree| {
186            PathBuf::from(worktree.read(cx).root_name())
187                .join(path)
188                .to_string_lossy()
189                .to_string()
190        })
191        .unwrap_or_else(|| path.to_string_lossy().to_string())
192}
193
194impl SerializableItem for ImageView {
195    fn serialized_item_kind() -> &'static str {
196        "ImageView"
197    }
198
199    fn deserialize(
200        project: Entity<Project>,
201        _workspace: WeakEntity<Workspace>,
202        workspace_id: WorkspaceId,
203        item_id: ItemId,
204        window: &mut Window,
205        cx: &mut App,
206    ) -> Task<gpui::Result<Entity<Self>>> {
207        window.spawn(cx, |mut cx| async move {
208            let image_path = IMAGE_VIEWER
209                .get_image_path(item_id, workspace_id)?
210                .ok_or_else(|| anyhow::anyhow!("No image path found"))?;
211
212            let (worktree, relative_path) = project
213                .update(&mut cx, |project, cx| {
214                    project.find_or_create_worktree(image_path.clone(), false, cx)
215                })?
216                .await
217                .context("Path not found")?;
218            let worktree_id = worktree.update(&mut cx, |worktree, _cx| worktree.id())?;
219
220            let project_path = ProjectPath {
221                worktree_id,
222                path: relative_path.into(),
223            };
224
225            let image_item = project
226                .update(&mut cx, |project, cx| project.open_image(project_path, cx))?
227                .await?;
228
229            cx.update(|_, cx| Ok(cx.new(|cx| ImageView::new(image_item, project, cx))))?
230        })
231    }
232
233    fn cleanup(
234        workspace_id: WorkspaceId,
235        alive_items: Vec<ItemId>,
236        window: &mut Window,
237        cx: &mut App,
238    ) -> Task<gpui::Result<()>> {
239        window.spawn(cx, |_| {
240            IMAGE_VIEWER.delete_unloaded_items(workspace_id, alive_items)
241        })
242    }
243
244    fn serialize(
245        &mut self,
246        workspace: &mut Workspace,
247        item_id: ItemId,
248        _closing: bool,
249        _window: &mut Window,
250        cx: &mut Context<Self>,
251    ) -> Option<Task<gpui::Result<()>>> {
252        let workspace_id = workspace.database_id()?;
253        let image_path = self.image_item.read(cx).file.as_local()?.abs_path(cx);
254
255        Some(cx.background_spawn({
256            async move {
257                IMAGE_VIEWER
258                    .save_image_path(item_id, workspace_id, image_path)
259                    .await
260            }
261        }))
262    }
263
264    fn should_serialize(&self, _event: &Self::Event) -> bool {
265        false
266    }
267}
268
269impl EventEmitter<()> for ImageView {}
270impl Focusable for ImageView {
271    fn focus_handle(&self, _cx: &App) -> FocusHandle {
272        self.focus_handle.clone()
273    }
274}
275
276impl Render for ImageView {
277    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
278        let image = self.image_item.read(cx).image.clone();
279        let checkered_background = |bounds: Bounds<Pixels>,
280                                    _,
281                                    window: &mut Window,
282                                    _cx: &mut App| {
283            let square_size = 32.0;
284
285            let start_y = bounds.origin.y.0;
286            let height = bounds.size.height.0;
287            let start_x = bounds.origin.x.0;
288            let width = bounds.size.width.0;
289
290            let mut y = start_y;
291            let mut x = start_x;
292            let mut color_swapper = true;
293            // draw checkerboard pattern
294            while y <= start_y + height {
295                // Keeping track of the grid in order to be resilient to resizing
296                let start_swap = color_swapper;
297                while x <= start_x + width {
298                    let rect =
299                        Bounds::new(point(px(x), px(y)), size(px(square_size), px(square_size)));
300
301                    let color = if color_swapper {
302                        opaque_grey(0.6, 0.4)
303                    } else {
304                        opaque_grey(0.7, 0.4)
305                    };
306
307                    window.paint_quad(fill(rect, color));
308                    color_swapper = !color_swapper;
309                    x += square_size;
310                }
311                x = start_x;
312                color_swapper = !start_swap;
313                y += square_size;
314            }
315        };
316
317        let checkered_background = canvas(|_, _, _| (), checkered_background)
318            .border_2()
319            .border_color(cx.theme().styles.colors.border)
320            .size_full()
321            .absolute()
322            .top_0()
323            .left_0();
324
325        div()
326            .track_focus(&self.focus_handle(cx))
327            .size_full()
328            .child(checkered_background)
329            .child(
330                div()
331                    .flex()
332                    .justify_center()
333                    .items_center()
334                    .w_full()
335                    // TODO: In browser based Tailwind & Flex this would be h-screen and we'd use w-full
336                    .h_full()
337                    .child(
338                        img(image)
339                            .object_fit(ObjectFit::ScaleDown)
340                            .max_w_full()
341                            .max_h_full()
342                            .id("img"),
343                    ),
344            )
345    }
346}
347
348impl ProjectItem for ImageView {
349    type Item = ImageItem;
350
351    fn for_project_item(
352        project: Entity<Project>,
353        item: Entity<Self::Item>,
354        _: &mut Window,
355        cx: &mut Context<Self>,
356    ) -> Self
357    where
358        Self: Sized,
359    {
360        Self::new(item, project, cx)
361    }
362}
363
364pub fn init(cx: &mut App) {
365    ImageViewerSettings::register(cx);
366    workspace::register_project_item::<ImageView>(cx);
367    workspace::register_serializable_item::<ImageView>(cx);
368}
369
370mod persistence {
371    use anyhow::Result;
372    use std::path::PathBuf;
373
374    use db::{define_connection, query, sqlez::statement::Statement, sqlez_macros::sql};
375    use workspace::{ItemId, WorkspaceDb, WorkspaceId};
376
377    define_connection! {
378        pub static ref IMAGE_VIEWER: ImageViewerDb<WorkspaceDb> =
379            &[sql!(
380                CREATE TABLE image_viewers (
381                    workspace_id INTEGER,
382                    item_id INTEGER UNIQUE,
383
384                    image_path BLOB,
385
386                    PRIMARY KEY(workspace_id, item_id),
387                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
388                    ON DELETE CASCADE
389                ) STRICT;
390            )];
391    }
392
393    impl ImageViewerDb {
394        query! {
395           pub async fn update_workspace_id(
396                new_id: WorkspaceId,
397                old_id: WorkspaceId,
398                item_id: ItemId
399            ) -> Result<()> {
400                UPDATE image_viewers
401                SET workspace_id = ?
402                WHERE workspace_id = ? AND item_id = ?
403            }
404        }
405
406        query! {
407            pub async fn save_image_path(
408                item_id: ItemId,
409                workspace_id: WorkspaceId,
410                image_path: PathBuf
411            ) -> Result<()> {
412                INSERT OR REPLACE INTO image_viewers(item_id, workspace_id, image_path)
413                VALUES (?, ?, ?)
414            }
415        }
416
417        query! {
418            pub fn get_image_path(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<PathBuf>> {
419                SELECT image_path
420                FROM image_viewers
421                WHERE item_id = ? AND workspace_id = ?
422            }
423        }
424
425        pub async fn delete_unloaded_items(
426            &self,
427            workspace: WorkspaceId,
428            alive_items: Vec<ItemId>,
429        ) -> Result<()> {
430            let placeholders = alive_items
431                .iter()
432                .map(|_| "?")
433                .collect::<Vec<&str>>()
434                .join(", ");
435
436            let query = format!("DELETE FROM image_viewers WHERE workspace_id = ? AND item_id NOT IN ({placeholders})");
437
438            self.write(move |conn| {
439                let mut statement = Statement::prepare(conn, query)?;
440                let mut next_index = statement.bind(&workspace, 1)?;
441                for id in alive_items {
442                    next_index = statement.bind(&id, next_index)?;
443                }
444                statement.exec()
445            })
446            .await
447        }
448    }
449}