image_viewer.rs

  1use gpui::{
  2    canvas, div, fill, img, opaque_grey, point, size, AnyElement, AppContext, Bounds, Context,
  3    Element, EventEmitter, FocusHandle, FocusableView, InteractiveElement, IntoElement, Model,
  4    ParentElement, Render, Styled, Task, View, ViewContext, VisualContext, WeakView, WindowContext,
  5};
  6use persistence::IMAGE_VIEWER;
  7use ui::{h_flex, prelude::*};
  8
  9use project::{Project, ProjectEntryId, ProjectPath};
 10use std::{ffi::OsStr, path::PathBuf};
 11use util::ResultExt;
 12use workspace::{
 13    item::{Item, ProjectItem},
 14    ItemId, Pane, Workspace, WorkspaceId,
 15};
 16
 17const IMAGE_VIEWER_KIND: &str = "ImageView";
 18
 19pub struct ImageItem {
 20    path: PathBuf,
 21    project_path: ProjectPath,
 22}
 23
 24impl project::Item for ImageItem {
 25    fn try_open(
 26        project: &Model<Project>,
 27        path: &ProjectPath,
 28        cx: &mut AppContext,
 29    ) -> Option<Task<gpui::Result<Model<Self>>>> {
 30        let path = path.clone();
 31        let project = project.clone();
 32
 33        let ext = path
 34            .path
 35            .extension()
 36            .and_then(OsStr::to_str)
 37            .unwrap_or_default();
 38
 39        let format = gpui::ImageFormat::from_extension(ext);
 40        if format.is_some() {
 41            Some(cx.spawn(|mut cx| async move {
 42                let abs_path = project
 43                    .read_with(&cx, |project, cx| project.absolute_path(&path, cx))?
 44                    .ok_or_else(|| anyhow::anyhow!("Failed to find the absolute path"))?;
 45
 46                cx.new_model(|_| ImageItem {
 47                    path: abs_path,
 48                    project_path: path,
 49                })
 50            }))
 51        } else {
 52            None
 53        }
 54    }
 55
 56    fn entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
 57        None
 58    }
 59
 60    fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
 61        Some(self.project_path.clone())
 62    }
 63}
 64
 65pub struct ImageView {
 66    path: PathBuf,
 67    focus_handle: FocusHandle,
 68}
 69
 70impl Item for ImageView {
 71    type Event = ();
 72
 73    fn tab_content(
 74        &self,
 75        _detail: Option<usize>,
 76        selected: bool,
 77        _cx: &WindowContext,
 78    ) -> AnyElement {
 79        let title = self
 80            .path
 81            .file_name()
 82            .unwrap_or_else(|| self.path.as_os_str())
 83            .to_string_lossy()
 84            .to_string();
 85        Label::new(title)
 86            .color(if selected {
 87                Color::Default
 88            } else {
 89                Color::Muted
 90            })
 91            .into_any_element()
 92    }
 93
 94    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 95        let item_id = cx.entity_id().as_u64();
 96        let workspace_id = workspace.database_id();
 97        let image_path = self.path.clone();
 98
 99        cx.background_executor()
100            .spawn({
101                let image_path = image_path.clone();
102                async move {
103                    IMAGE_VIEWER
104                        .save_image_path(item_id, workspace_id, image_path)
105                        .await
106                        .log_err();
107                }
108            })
109            .detach();
110    }
111
112    fn serialized_item_kind() -> Option<&'static str> {
113        Some(IMAGE_VIEWER_KIND)
114    }
115
116    fn deserialize(
117        _project: Model<Project>,
118        _workspace: WeakView<Workspace>,
119        workspace_id: WorkspaceId,
120        item_id: ItemId,
121        cx: &mut ViewContext<Pane>,
122    ) -> Task<anyhow::Result<View<Self>>> {
123        cx.spawn(|_pane, mut cx| async move {
124            let image_path = IMAGE_VIEWER
125                .get_image_path(item_id, workspace_id)?
126                .ok_or_else(|| anyhow::anyhow!("No image path found"))?;
127
128            cx.new_view(|cx| ImageView {
129                path: image_path,
130                focus_handle: cx.focus_handle(),
131            })
132        })
133    }
134
135    fn clone_on_split(
136        &self,
137        _workspace_id: WorkspaceId,
138        cx: &mut ViewContext<Self>,
139    ) -> Option<View<Self>>
140    where
141        Self: Sized,
142    {
143        Some(cx.new_view(|cx| Self {
144            path: self.path.clone(),
145            focus_handle: cx.focus_handle(),
146        }))
147    }
148}
149
150impl EventEmitter<()> for ImageView {}
151impl FocusableView for ImageView {
152    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
153        self.focus_handle.clone()
154    }
155}
156
157impl Render for ImageView {
158    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
159        let im = img(self.path.clone()).into_any();
160
161        div()
162            .track_focus(&self.focus_handle)
163            .size_full()
164            .child(
165                // Checkered background behind the image
166                canvas(
167                    |_, _| (),
168                    |bounds, _, cx| {
169                        let square_size = 32.0;
170
171                        let start_y = bounds.origin.y.0;
172                        let height = bounds.size.height.0;
173                        let start_x = bounds.origin.x.0;
174                        let width = bounds.size.width.0;
175
176                        let mut y = start_y;
177                        let mut x = start_x;
178                        let mut color_swapper = true;
179                        // draw checkerboard pattern
180                        while y <= start_y + height {
181                            // Keeping track of the grid in order to be resilient to resizing
182                            let start_swap = color_swapper;
183                            while x <= start_x + width {
184                                let rect = Bounds::new(
185                                    point(px(x), px(y)),
186                                    size(px(square_size), px(square_size)),
187                                );
188
189                                let color = if color_swapper {
190                                    opaque_grey(0.6, 0.4)
191                                } else {
192                                    opaque_grey(0.7, 0.4)
193                                };
194
195                                cx.paint_quad(fill(rect, color));
196                                color_swapper = !color_swapper;
197                                x += square_size;
198                            }
199                            x = start_x;
200                            color_swapper = !start_swap;
201                            y += square_size;
202                        }
203                    },
204                )
205                .border_2()
206                .border_color(cx.theme().styles.colors.border)
207                .size_full()
208                .absolute()
209                .top_0()
210                .left_0(),
211            )
212            .child(
213                v_flex()
214                    .h_full()
215                    .justify_around()
216                    .child(h_flex().w_full().justify_around().child(im)),
217            )
218    }
219}
220
221impl ProjectItem for ImageView {
222    type Item = ImageItem;
223
224    fn for_project_item(
225        _project: Model<Project>,
226        item: Model<Self::Item>,
227        cx: &mut ViewContext<Self>,
228    ) -> Self
229    where
230        Self: Sized,
231    {
232        Self {
233            path: item.read(cx).path.clone(),
234            focus_handle: cx.focus_handle(),
235        }
236    }
237}
238
239pub fn init(cx: &mut AppContext) {
240    workspace::register_project_item::<ImageView>(cx);
241    workspace::register_deserializable_item::<ImageView>(cx)
242}
243
244mod persistence {
245    use std::path::PathBuf;
246
247    use db::{define_connection, query, sqlez_macros::sql};
248    use workspace::{ItemId, WorkspaceDb, WorkspaceId};
249
250    define_connection! {
251        pub static ref IMAGE_VIEWER: ImageViewerDb<WorkspaceDb> =
252            &[sql!(
253                CREATE TABLE image_viewers (
254                    workspace_id INTEGER,
255                    item_id INTEGER UNIQUE,
256
257                    image_path BLOB,
258
259                    PRIMARY KEY(workspace_id, item_id),
260                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
261                    ON DELETE CASCADE
262                ) STRICT;
263            )];
264    }
265
266    impl ImageViewerDb {
267        query! {
268           pub async fn update_workspace_id(
269                new_id: WorkspaceId,
270                old_id: WorkspaceId,
271                item_id: ItemId
272            ) -> Result<()> {
273                UPDATE image_viewers
274                SET workspace_id = ?
275                WHERE workspace_id = ? AND item_id = ?
276            }
277        }
278
279        query! {
280            pub async fn save_image_path(
281                item_id: ItemId,
282                workspace_id: WorkspaceId,
283                image_path: PathBuf
284            ) -> Result<()> {
285                INSERT OR REPLACE INTO image_viewers(item_id, workspace_id, image_path)
286                VALUES (?, ?, ?)
287            }
288        }
289
290        query! {
291            pub fn get_image_path(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<PathBuf>> {
292                SELECT image_path
293                FROM image_viewers
294                WHERE item_id = ? AND workspace_id = ?
295            }
296        }
297    }
298}