image_viewer.rs

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