image_viewer.rs

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