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