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, delete_unloaded_items,
 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        delete_unloaded_items(
248            alive_items,
249            workspace_id,
250            "image_viewers",
251            &IMAGE_VIEWER,
252            cx,
253        )
254    }
255
256    fn serialize(
257        &mut self,
258        workspace: &mut Workspace,
259        item_id: ItemId,
260        _closing: bool,
261        _window: &mut Window,
262        cx: &mut Context<Self>,
263    ) -> Option<Task<gpui::Result<()>>> {
264        let workspace_id = workspace.database_id()?;
265        let image_path = self.image_item.read(cx).file.as_local()?.abs_path(cx);
266
267        Some(cx.background_spawn({
268            async move {
269                log::debug!("Saving image at path {image_path:?}");
270                IMAGE_VIEWER
271                    .save_image_path(item_id, workspace_id, image_path)
272                    .await
273            }
274        }))
275    }
276
277    fn should_serialize(&self, _event: &Self::Event) -> bool {
278        false
279    }
280}
281
282impl EventEmitter<()> for ImageView {}
283impl Focusable for ImageView {
284    fn focus_handle(&self, _cx: &App) -> FocusHandle {
285        self.focus_handle.clone()
286    }
287}
288
289impl Render for ImageView {
290    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
291        let image = self.image_item.read(cx).image.clone();
292        let checkered_background = |bounds: Bounds<Pixels>,
293                                    _,
294                                    window: &mut Window,
295                                    _cx: &mut App| {
296            let square_size = 32.0;
297
298            let start_y = bounds.origin.y.0;
299            let height = bounds.size.height.0;
300            let start_x = bounds.origin.x.0;
301            let width = bounds.size.width.0;
302
303            let mut y = start_y;
304            let mut x = start_x;
305            let mut color_swapper = true;
306            // draw checkerboard pattern
307            while y <= start_y + height {
308                // Keeping track of the grid in order to be resilient to resizing
309                let start_swap = color_swapper;
310                while x <= start_x + width {
311                    let rect =
312                        Bounds::new(point(px(x), px(y)), size(px(square_size), px(square_size)));
313
314                    let color = if color_swapper {
315                        opaque_grey(0.6, 0.4)
316                    } else {
317                        opaque_grey(0.7, 0.4)
318                    };
319
320                    window.paint_quad(fill(rect, color));
321                    color_swapper = !color_swapper;
322                    x += square_size;
323                }
324                x = start_x;
325                color_swapper = !start_swap;
326                y += square_size;
327            }
328        };
329
330        let checkered_background = canvas(|_, _, _| (), checkered_background)
331            .border_2()
332            .border_color(cx.theme().styles.colors.border)
333            .size_full()
334            .absolute()
335            .top_0()
336            .left_0();
337
338        div()
339            .track_focus(&self.focus_handle(cx))
340            .size_full()
341            .child(checkered_background)
342            .child(
343                div()
344                    .flex()
345                    .justify_center()
346                    .items_center()
347                    .w_full()
348                    // TODO: In browser based Tailwind & Flex this would be h-screen and we'd use w-full
349                    .h_full()
350                    .child(
351                        img(image)
352                            .object_fit(ObjectFit::ScaleDown)
353                            .max_w_full()
354                            .max_h_full()
355                            .id("img"),
356                    ),
357            )
358    }
359}
360
361impl ProjectItem for ImageView {
362    type Item = ImageItem;
363
364    fn for_project_item(
365        project: Entity<Project>,
366        _: &Pane,
367        item: Entity<Self::Item>,
368        _: &mut Window,
369        cx: &mut Context<Self>,
370    ) -> Self
371    where
372        Self: Sized,
373    {
374        Self::new(item, project, cx)
375    }
376}
377
378pub fn init(cx: &mut App) {
379    ImageViewerSettings::register(cx);
380    workspace::register_project_item::<ImageView>(cx);
381    workspace::register_serializable_item::<ImageView>(cx);
382}
383
384mod persistence {
385    use std::path::PathBuf;
386
387    use db::{define_connection, query, sqlez_macros::sql};
388    use workspace::{ItemId, WorkspaceDb, WorkspaceId};
389
390    define_connection! {
391        pub static ref IMAGE_VIEWER: ImageViewerDb<WorkspaceDb> =
392            &[sql!(
393                CREATE TABLE image_viewers (
394                    workspace_id INTEGER,
395                    item_id INTEGER UNIQUE,
396
397                    image_path BLOB,
398
399                    PRIMARY KEY(workspace_id, item_id),
400                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
401                    ON DELETE CASCADE
402                ) STRICT;
403            )];
404    }
405
406    impl ImageViewerDb {
407        query! {
408            pub async fn save_image_path(
409                item_id: ItemId,
410                workspace_id: WorkspaceId,
411                image_path: PathBuf
412            ) -> Result<()> {
413                INSERT OR REPLACE INTO image_viewers(item_id, workspace_id, image_path)
414                VALUES (?, ?, ?)
415            }
416        }
417
418        query! {
419            pub fn get_image_path(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<PathBuf>> {
420                SELECT image_path
421                FROM image_viewers
422                WHERE item_id = ? AND workspace_id = ?
423            }
424        }
425    }
426}