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        self.path
 80            .file_name()
 81            .unwrap_or_else(|| self.path.as_os_str())
 82            .to_string_lossy()
 83            .to_string()
 84            .into_any_element()
 85    }
 86
 87    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 88        let item_id = cx.entity_id().as_u64();
 89        let workspace_id = workspace.database_id();
 90        let image_path = self.path.clone();
 91
 92        cx.background_executor()
 93            .spawn({
 94                let image_path = image_path.clone();
 95                async move {
 96                    IMAGE_VIEWER
 97                        .save_image_path(item_id, workspace_id, image_path)
 98                        .await
 99                        .log_err();
100                }
101            })
102            .detach();
103    }
104
105    fn serialized_item_kind() -> Option<&'static str> {
106        Some(IMAGE_VIEWER_KIND)
107    }
108
109    fn deserialize(
110        _project: Model<Project>,
111        _workspace: WeakView<Workspace>,
112        workspace_id: WorkspaceId,
113        item_id: ItemId,
114        cx: &mut ViewContext<Pane>,
115    ) -> Task<anyhow::Result<View<Self>>> {
116        cx.spawn(|_pane, mut cx| async move {
117            let image_path = IMAGE_VIEWER
118                .get_image_path(item_id, workspace_id)?
119                .ok_or_else(|| anyhow::anyhow!("No image path found"))?;
120
121            cx.new_view(|cx| ImageView {
122                path: image_path,
123                focus_handle: cx.focus_handle(),
124            })
125        })
126    }
127
128    fn clone_on_split(
129        &self,
130        _workspace_id: WorkspaceId,
131        cx: &mut ViewContext<Self>,
132    ) -> Option<View<Self>>
133    where
134        Self: Sized,
135    {
136        Some(cx.new_view(|cx| Self {
137            path: self.path.clone(),
138            focus_handle: cx.focus_handle(),
139        }))
140    }
141}
142
143impl EventEmitter<()> for ImageView {}
144impl FocusableView for ImageView {
145    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
146        self.focus_handle.clone()
147    }
148}
149
150impl Render for ImageView {
151    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
152        let im = img(self.path.clone()).into_any();
153
154        div()
155            .track_focus(&self.focus_handle)
156            .size_full()
157            .child(
158                // Checkered background behind the image
159                canvas(
160                    |_, _| (),
161                    |bounds, _, cx| {
162                        let square_size = 32.0;
163
164                        let start_y = bounds.origin.y.0;
165                        let height = bounds.size.height.0;
166                        let start_x = bounds.origin.x.0;
167                        let width = bounds.size.width.0;
168
169                        let mut y = start_y;
170                        let mut x = start_x;
171                        let mut color_swapper = true;
172                        // draw checkerboard pattern
173                        while y <= start_y + height {
174                            // Keeping track of the grid in order to be resilient to resizing
175                            let start_swap = color_swapper;
176                            while x <= start_x + width {
177                                let rect = Bounds::new(
178                                    point(px(x), px(y)),
179                                    size(px(square_size), px(square_size)),
180                                );
181
182                                let color = if color_swapper {
183                                    opaque_grey(0.6, 0.4)
184                                } else {
185                                    opaque_grey(0.7, 0.4)
186                                };
187
188                                cx.paint_quad(fill(rect, color));
189                                color_swapper = !color_swapper;
190                                x += square_size;
191                            }
192                            x = start_x;
193                            color_swapper = !start_swap;
194                            y += square_size;
195                        }
196                    },
197                )
198                .border_2()
199                .border_color(cx.theme().styles.colors.border)
200                .size_full()
201                .absolute()
202                .top_0()
203                .left_0(),
204            )
205            .child(
206                v_flex()
207                    .h_full()
208                    .justify_around()
209                    .child(h_flex().w_full().justify_around().child(im)),
210            )
211    }
212}
213
214impl ProjectItem for ImageView {
215    type Item = ImageItem;
216
217    fn for_project_item(
218        _project: Model<Project>,
219        item: Model<Self::Item>,
220        cx: &mut ViewContext<Self>,
221    ) -> Self
222    where
223        Self: Sized,
224    {
225        Self {
226            path: item.read(cx).path.clone(),
227            focus_handle: cx.focus_handle(),
228        }
229    }
230}
231
232pub fn init(cx: &mut AppContext) {
233    workspace::register_project_item::<ImageView>(cx);
234    workspace::register_deserializable_item::<ImageView>(cx)
235}
236
237mod persistence {
238    use std::path::PathBuf;
239
240    use db::{define_connection, query, sqlez_macros::sql};
241    use workspace::{ItemId, WorkspaceDb, WorkspaceId};
242
243    define_connection! {
244        pub static ref IMAGE_VIEWER: ImageViewerDb<WorkspaceDb> =
245            &[sql!(
246                CREATE TABLE image_viewers (
247                    workspace_id INTEGER,
248                    item_id INTEGER UNIQUE,
249
250                    image_path BLOB,
251
252                    PRIMARY KEY(workspace_id, item_id),
253                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
254                    ON DELETE CASCADE
255                ) STRICT;
256            )];
257    }
258
259    impl ImageViewerDb {
260        query! {
261           pub async fn update_workspace_id(
262                new_id: WorkspaceId,
263                old_id: WorkspaceId,
264                item_id: ItemId
265            ) -> Result<()> {
266                UPDATE image_viewers
267                SET workspace_id = ?
268                WHERE workspace_id = ? AND item_id = ?
269            }
270        }
271
272        query! {
273            pub async fn save_image_path(
274                item_id: ItemId,
275                workspace_id: WorkspaceId,
276                image_path: PathBuf
277            ) -> Result<()> {
278                INSERT OR REPLACE INTO image_viewers(item_id, workspace_id, image_path)
279                VALUES (?, ?, ?)
280            }
281        }
282
283        query! {
284            pub fn get_image_path(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<PathBuf>> {
285                SELECT image_path
286                FROM image_viewers
287                WHERE item_id = ? AND workspace_id = ?
288            }
289        }
290    }
291}