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