image_viewer.rs

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