image_viewer.rs

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