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, Pane, 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::Item),
 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) -> 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 ViewContext<Pane>,
176    ) -> Task<gpui::Result<View<Self>>> {
177        cx.spawn(|_pane, 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                    ),
306            )
307    }
308}
309
310impl ProjectItem for ImageView {
311    type Item = ImageItem;
312
313    fn for_project_item(
314        project: Model<Project>,
315        item: Model<Self::Item>,
316        cx: &mut ViewContext<Self>,
317    ) -> Self
318    where
319        Self: Sized,
320    {
321        Self::new(item, project, cx)
322    }
323}
324
325pub fn init(cx: &mut AppContext) {
326    workspace::register_project_item::<ImageView>(cx);
327    workspace::register_serializable_item::<ImageView>(cx)
328}
329
330mod persistence {
331    use anyhow::Result;
332    use std::path::PathBuf;
333
334    use db::{define_connection, query, sqlez::statement::Statement, sqlez_macros::sql};
335    use workspace::{ItemId, WorkspaceDb, WorkspaceId};
336
337    define_connection! {
338        pub static ref IMAGE_VIEWER: ImageViewerDb<WorkspaceDb> =
339            &[sql!(
340                CREATE TABLE image_viewers (
341                    workspace_id INTEGER,
342                    item_id INTEGER UNIQUE,
343
344                    image_path BLOB,
345
346                    PRIMARY KEY(workspace_id, item_id),
347                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
348                    ON DELETE CASCADE
349                ) STRICT;
350            )];
351    }
352
353    impl ImageViewerDb {
354        query! {
355           pub async fn update_workspace_id(
356                new_id: WorkspaceId,
357                old_id: WorkspaceId,
358                item_id: ItemId
359            ) -> Result<()> {
360                UPDATE image_viewers
361                SET workspace_id = ?
362                WHERE workspace_id = ? AND item_id = ?
363            }
364        }
365
366        query! {
367            pub async fn save_image_path(
368                item_id: ItemId,
369                workspace_id: WorkspaceId,
370                image_path: PathBuf
371            ) -> Result<()> {
372                INSERT OR REPLACE INTO image_viewers(item_id, workspace_id, image_path)
373                VALUES (?, ?, ?)
374            }
375        }
376
377        query! {
378            pub fn get_image_path(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<PathBuf>> {
379                SELECT image_path
380                FROM image_viewers
381                WHERE item_id = ? AND workspace_id = ?
382            }
383        }
384
385        pub async fn delete_unloaded_items(
386            &self,
387            workspace: WorkspaceId,
388            alive_items: Vec<ItemId>,
389        ) -> Result<()> {
390            let placeholders = alive_items
391                .iter()
392                .map(|_| "?")
393                .collect::<Vec<&str>>()
394                .join(", ");
395
396            let query = format!("DELETE FROM image_viewers WHERE workspace_id = ? AND item_id NOT IN ({placeholders})");
397
398            self.write(move |conn| {
399                let mut statement = Statement::prepare(conn, query)?;
400                let mut next_index = statement.bind(&workspace, 1)?;
401                for id in alive_items {
402                    next_index = statement.bind(&id, next_index)?;
403                }
404                statement.exec()
405            })
406            .await
407        }
408    }
409}