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 can_split(&self) -> bool {
178        true
179    }
180
181    fn clone_on_split(
182        &self,
183        _workspace_id: Option<WorkspaceId>,
184        _: &mut Window,
185        cx: &mut Context<Self>,
186    ) -> Task<Option<Entity<Self>>>
187    where
188        Self: Sized,
189    {
190        Task::ready(Some(cx.new(|cx| Self {
191            image_item: self.image_item.clone(),
192            project: self.project.clone(),
193            focus_handle: cx.focus_handle(),
194        })))
195    }
196
197    fn has_deleted_file(&self, cx: &App) -> bool {
198        self.image_item.read(cx).file.disk_state() == DiskState::Deleted
199    }
200    fn buffer_kind(&self, _: &App) -> workspace::item::ItemBufferKind {
201        workspace::item::ItemBufferKind::Singleton
202    }
203}
204
205fn breadcrumbs_text_for_image(project: &Project, image: &ImageItem, cx: &App) -> String {
206    let mut path = image.file.path().clone();
207    if project.visible_worktrees(cx).count() > 1
208        && let Some(worktree) = project.worktree_for_id(image.project_path(cx).worktree_id, cx)
209    {
210        path = worktree.read(cx).root_name().join(&path);
211    }
212
213    path.display(project.path_style(cx)).to_string()
214}
215
216impl SerializableItem for ImageView {
217    fn serialized_item_kind() -> &'static str {
218        "ImageView"
219    }
220
221    fn deserialize(
222        project: Entity<Project>,
223        _workspace: WeakEntity<Workspace>,
224        workspace_id: WorkspaceId,
225        item_id: ItemId,
226        window: &mut Window,
227        cx: &mut App,
228    ) -> Task<anyhow::Result<Entity<Self>>> {
229        window.spawn(cx, async move |cx| {
230            let image_path = IMAGE_VIEWER
231                .get_image_path(item_id, workspace_id)?
232                .context("No image path found")?;
233
234            let (worktree, relative_path) = project
235                .update(cx, |project, cx| {
236                    project.find_or_create_worktree(image_path.clone(), false, cx)
237                })?
238                .await
239                .context("Path not found")?;
240            let worktree_id = worktree.update(cx, |worktree, _cx| worktree.id())?;
241
242            let project_path = ProjectPath {
243                worktree_id,
244                path: relative_path,
245            };
246
247            let image_item = project
248                .update(cx, |project, cx| project.open_image(project_path, cx))?
249                .await?;
250
251            cx.update(
252                |window, cx| Ok(cx.new(|cx| ImageView::new(image_item, project, window, cx))),
253            )?
254        })
255    }
256
257    fn cleanup(
258        workspace_id: WorkspaceId,
259        alive_items: Vec<ItemId>,
260        _window: &mut Window,
261        cx: &mut App,
262    ) -> Task<anyhow::Result<()>> {
263        delete_unloaded_items(
264            alive_items,
265            workspace_id,
266            "image_viewers",
267            &IMAGE_VIEWER,
268            cx,
269        )
270    }
271
272    fn serialize(
273        &mut self,
274        workspace: &mut Workspace,
275        item_id: ItemId,
276        _closing: bool,
277        _window: &mut Window,
278        cx: &mut Context<Self>,
279    ) -> Option<Task<anyhow::Result<()>>> {
280        let workspace_id = workspace.database_id()?;
281        let image_path = self.image_item.read(cx).abs_path(cx)?;
282
283        Some(cx.background_spawn({
284            async move {
285                log::debug!("Saving image at path {image_path:?}");
286                IMAGE_VIEWER
287                    .save_image_path(item_id, workspace_id, image_path)
288                    .await
289            }
290        }))
291    }
292
293    fn should_serialize(&self, _event: &Self::Event) -> bool {
294        false
295    }
296}
297
298impl EventEmitter<()> for ImageView {}
299impl Focusable for ImageView {
300    fn focus_handle(&self, _cx: &App) -> FocusHandle {
301        self.focus_handle.clone()
302    }
303}
304
305impl Render for ImageView {
306    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
307        let image = self.image_item.read(cx).image.clone();
308        let checkered_background =
309            |bounds: Bounds<Pixels>, _, window: &mut Window, _cx: &mut App| {
310                let square_size: f32 = 32.0;
311
312                let start_y = bounds.origin.y.into();
313                let height: f32 = bounds.size.height.into();
314                let start_x = bounds.origin.x.into();
315                let width: f32 = bounds.size.width.into();
316
317                let mut y = start_y;
318                let mut x = start_x;
319                let mut color_swapper = true;
320                // draw checkerboard pattern
321                while y < start_y + height {
322                    // Keeping track of the grid in order to be resilient to resizing
323                    let start_swap = color_swapper;
324                    while x < start_x + width {
325                        // Clamp square dimensions to not exceed bounds
326                        let square_width = square_size.min(start_x + width - x);
327                        let square_height = square_size.min(start_y + height - y);
328
329                        let rect = Bounds::new(
330                            point(px(x), px(y)),
331                            size(px(square_width), px(square_height)),
332                        );
333
334                        let color = if color_swapper {
335                            opaque_grey(0.6, 0.4)
336                        } else {
337                            opaque_grey(0.7, 0.4)
338                        };
339
340                        window.paint_quad(fill(rect, color));
341                        color_swapper = !color_swapper;
342                        x += square_size;
343                    }
344                    x = start_x;
345                    color_swapper = !start_swap;
346                    y += square_size;
347                }
348            };
349
350        div().track_focus(&self.focus_handle(cx)).size_full().child(
351            div()
352                .flex()
353                .justify_center()
354                .items_center()
355                .w_full()
356                // TODO: In browser based Tailwind & Flex this would be h-screen and we'd use w-full
357                .h_full()
358                .child(
359                    div()
360                        .relative()
361                        .max_w_full()
362                        .max_h_full()
363                        .child(
364                            canvas(|_, _, _| (), checkered_background)
365                                .border_2()
366                                .border_color(cx.theme().styles.colors.border)
367                                .size_full()
368                                .absolute()
369                                .top_0()
370                                .left_0(),
371                        )
372                        .child(
373                            img(image)
374                                .object_fit(ObjectFit::ScaleDown)
375                                .max_w_full()
376                                .max_h_full()
377                                .id("img"),
378                        ),
379                ),
380        )
381    }
382}
383
384impl ProjectItem for ImageView {
385    type Item = ImageItem;
386
387    fn for_project_item(
388        project: Entity<Project>,
389        _: Option<&Pane>,
390        item: Entity<Self::Item>,
391        window: &mut Window,
392        cx: &mut Context<Self>,
393    ) -> Self
394    where
395        Self: Sized,
396    {
397        Self::new(item, project, window, cx)
398    }
399
400    fn for_broken_project_item(
401        abs_path: &Path,
402        is_local: bool,
403        e: &anyhow::Error,
404        window: &mut Window,
405        cx: &mut App,
406    ) -> Option<InvalidItemView>
407    where
408        Self: Sized,
409    {
410        Some(InvalidItemView::new(abs_path, is_local, e, window, cx))
411    }
412}
413
414pub fn init(cx: &mut App) {
415    ImageViewerSettings::register(cx);
416    workspace::register_project_item::<ImageView>(cx);
417    workspace::register_serializable_item::<ImageView>(cx);
418}
419
420mod persistence {
421    use std::path::PathBuf;
422
423    use db::{
424        query,
425        sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
426        sqlez_macros::sql,
427    };
428    use workspace::{ItemId, WorkspaceDb, WorkspaceId};
429
430    pub struct ImageViewerDb(ThreadSafeConnection);
431
432    impl Domain for ImageViewerDb {
433        const NAME: &str = stringify!(ImageViewerDb);
434
435        const MIGRATIONS: &[&str] = &[sql!(
436                CREATE TABLE image_viewers (
437                    workspace_id INTEGER,
438                    item_id INTEGER UNIQUE,
439
440                    image_path BLOB,
441
442                    PRIMARY KEY(workspace_id, item_id),
443                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
444                    ON DELETE CASCADE
445                ) STRICT;
446        )];
447    }
448
449    db::static_connection!(IMAGE_VIEWER, ImageViewerDb, [WorkspaceDb]);
450
451    impl ImageViewerDb {
452        query! {
453            pub async fn save_image_path(
454                item_id: ItemId,
455                workspace_id: WorkspaceId,
456                image_path: PathBuf
457            ) -> Result<()> {
458                INSERT OR REPLACE INTO image_viewers(item_id, workspace_id, image_path)
459                VALUES (?, ?, ?)
460            }
461        }
462
463        query! {
464            pub fn get_image_path(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<PathBuf>> {
465                SELECT image_path
466                FROM image_viewers
467                WHERE item_id = ? AND workspace_id = ?
468            }
469        }
470    }
471}