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: &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        Label::new(self.tab_content_text(params.detail.unwrap_or_default(), cx))
125            .single_line()
126            .color(label_color)
127            .when(params.preview, |this| this.italic())
128            .into_any_element()
129    }
130
131    fn tab_content_text(&self, _: usize, cx: &App) -> SharedString {
132        self.image_item
133            .read(cx)
134            .file
135            .file_name(cx)
136            .to_string_lossy()
137            .to_string()
138            .into()
139    }
140
141    fn tab_icon(&self, _: &Window, cx: &App) -> Option<Icon> {
142        let path = self.image_item.read(cx).path();
143        ItemSettings::get_global(cx)
144            .file_icons
145            .then(|| FileIcons::get_icon(path, cx))
146            .flatten()
147            .map(Icon::from_path)
148    }
149
150    fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
151        let show_breadcrumb = EditorSettings::get_global(cx).toolbar.breadcrumbs;
152        if show_breadcrumb {
153            ToolbarItemLocation::PrimaryLeft
154        } else {
155            ToolbarItemLocation::Hidden
156        }
157    }
158
159    fn breadcrumbs(&self, _theme: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
160        let text = breadcrumbs_text_for_image(self.project.read(cx), self.image_item.read(cx), cx);
161        Some(vec![BreadcrumbText {
162            text,
163            highlights: None,
164            font: None,
165        }])
166    }
167
168    fn clone_on_split(
169        &self,
170        _workspace_id: Option<WorkspaceId>,
171        _: &mut Window,
172        cx: &mut Context<Self>,
173    ) -> Option<Entity<Self>>
174    where
175        Self: Sized,
176    {
177        Some(cx.new(|cx| Self {
178            image_item: self.image_item.clone(),
179            project: self.project.clone(),
180            focus_handle: cx.focus_handle(),
181        }))
182    }
183}
184
185fn breadcrumbs_text_for_image(project: &Project, image: &ImageItem, cx: &App) -> String {
186    let path = image.file.file_name(cx);
187    if project.visible_worktrees(cx).count() <= 1 {
188        return path.to_string_lossy().to_string();
189    }
190
191    project
192        .worktree_for_id(image.project_path(cx).worktree_id, cx)
193        .map(|worktree| {
194            PathBuf::from(worktree.read(cx).root_name())
195                .join(path)
196                .to_string_lossy()
197                .to_string()
198        })
199        .unwrap_or_else(|| path.to_string_lossy().to_string())
200}
201
202impl SerializableItem for ImageView {
203    fn serialized_item_kind() -> &'static str {
204        "ImageView"
205    }
206
207    fn deserialize(
208        project: Entity<Project>,
209        _workspace: WeakEntity<Workspace>,
210        workspace_id: WorkspaceId,
211        item_id: ItemId,
212        window: &mut Window,
213        cx: &mut App,
214    ) -> Task<gpui::Result<Entity<Self>>> {
215        window.spawn(cx, async move |cx| {
216            let image_path = IMAGE_VIEWER
217                .get_image_path(item_id, workspace_id)?
218                .ok_or_else(|| anyhow::anyhow!("No image path found"))?;
219
220            let (worktree, relative_path) = project
221                .update(cx, |project, cx| {
222                    project.find_or_create_worktree(image_path.clone(), false, cx)
223                })?
224                .await
225                .context("Path not found")?;
226            let worktree_id = worktree.update(cx, |worktree, _cx| worktree.id())?;
227
228            let project_path = ProjectPath {
229                worktree_id,
230                path: relative_path.into(),
231            };
232
233            let image_item = project
234                .update(cx, |project, cx| project.open_image(project_path, cx))?
235                .await?;
236
237            cx.update(|_, cx| Ok(cx.new(|cx| ImageView::new(image_item, project, cx))))?
238        })
239    }
240
241    fn cleanup(
242        workspace_id: WorkspaceId,
243        alive_items: Vec<ItemId>,
244        window: &mut Window,
245        cx: &mut App,
246    ) -> Task<gpui::Result<()>> {
247        window.spawn(cx, async move |_| {
248            IMAGE_VIEWER
249                .delete_unloaded_items(workspace_id, alive_items)
250                .await
251        })
252    }
253
254    fn serialize(
255        &mut self,
256        workspace: &mut Workspace,
257        item_id: ItemId,
258        _closing: bool,
259        _window: &mut Window,
260        cx: &mut Context<Self>,
261    ) -> Option<Task<gpui::Result<()>>> {
262        let workspace_id = workspace.database_id()?;
263        let image_path = self.image_item.read(cx).file.as_local()?.abs_path(cx);
264
265        Some(cx.background_spawn({
266            async move {
267                log::debug!("Saving image at path {image_path:?}");
268                IMAGE_VIEWER
269                    .save_image_path(item_id, workspace_id, image_path)
270                    .await
271            }
272        }))
273    }
274
275    fn should_serialize(&self, _event: &Self::Event) -> bool {
276        false
277    }
278}
279
280impl EventEmitter<()> for ImageView {}
281impl Focusable for ImageView {
282    fn focus_handle(&self, _cx: &App) -> FocusHandle {
283        self.focus_handle.clone()
284    }
285}
286
287impl Render for ImageView {
288    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
289        let image = self.image_item.read(cx).image.clone();
290        let checkered_background = |bounds: Bounds<Pixels>,
291                                    _,
292                                    window: &mut Window,
293                                    _cx: &mut App| {
294            let square_size = 32.0;
295
296            let start_y = bounds.origin.y.0;
297            let height = bounds.size.height.0;
298            let start_x = bounds.origin.x.0;
299            let width = bounds.size.width.0;
300
301            let mut y = start_y;
302            let mut x = start_x;
303            let mut color_swapper = true;
304            // draw checkerboard pattern
305            while y <= start_y + height {
306                // Keeping track of the grid in order to be resilient to resizing
307                let start_swap = color_swapper;
308                while x <= start_x + width {
309                    let rect =
310                        Bounds::new(point(px(x), px(y)), size(px(square_size), px(square_size)));
311
312                    let color = if color_swapper {
313                        opaque_grey(0.6, 0.4)
314                    } else {
315                        opaque_grey(0.7, 0.4)
316                    };
317
318                    window.paint_quad(fill(rect, color));
319                    color_swapper = !color_swapper;
320                    x += square_size;
321                }
322                x = start_x;
323                color_swapper = !start_swap;
324                y += square_size;
325            }
326        };
327
328        let checkered_background = canvas(|_, _, _| (), checkered_background)
329            .border_2()
330            .border_color(cx.theme().styles.colors.border)
331            .size_full()
332            .absolute()
333            .top_0()
334            .left_0();
335
336        div()
337            .track_focus(&self.focus_handle(cx))
338            .size_full()
339            .child(checkered_background)
340            .child(
341                div()
342                    .flex()
343                    .justify_center()
344                    .items_center()
345                    .w_full()
346                    // TODO: In browser based Tailwind & Flex this would be h-screen and we'd use w-full
347                    .h_full()
348                    .child(
349                        img(image)
350                            .object_fit(ObjectFit::ScaleDown)
351                            .max_w_full()
352                            .max_h_full()
353                            .id("img"),
354                    ),
355            )
356    }
357}
358
359impl ProjectItem for ImageView {
360    type Item = ImageItem;
361
362    fn for_project_item(
363        project: Entity<Project>,
364        _: &Pane,
365        item: Entity<Self::Item>,
366        _: &mut Window,
367        cx: &mut Context<Self>,
368    ) -> Self
369    where
370        Self: Sized,
371    {
372        Self::new(item, project, cx)
373    }
374}
375
376pub fn init(cx: &mut App) {
377    ImageViewerSettings::register(cx);
378    workspace::register_project_item::<ImageView>(cx);
379    workspace::register_serializable_item::<ImageView>(cx);
380}
381
382mod persistence {
383    use anyhow::Result;
384    use std::path::PathBuf;
385
386    use db::{define_connection, query, sqlez::statement::Statement, sqlez_macros::sql};
387    use workspace::{ItemId, WorkspaceDb, WorkspaceId};
388
389    define_connection! {
390        pub static ref IMAGE_VIEWER: ImageViewerDb<WorkspaceDb> =
391            &[sql!(
392                CREATE TABLE image_viewers (
393                    workspace_id INTEGER,
394                    item_id INTEGER UNIQUE,
395
396                    image_path BLOB,
397
398                    PRIMARY KEY(workspace_id, item_id),
399                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
400                    ON DELETE CASCADE
401                ) STRICT;
402            )];
403    }
404
405    impl ImageViewerDb {
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!(
437                "DELETE FROM image_viewers WHERE workspace_id = ? AND item_id NOT IN ({placeholders})"
438            );
439
440            self.write(move |conn| {
441                let mut statement = Statement::prepare(conn, query)?;
442                let mut next_index = statement.bind(&workspace, 1)?;
443                for id in alive_items {
444                    next_index = statement.bind(&id, next_index)?;
445                }
446                statement.exec()
447            })
448            .await
449        }
450    }
451}