image_viewer.rs

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