1use gpui::{
2 canvas, div, fill, img, opaque_grey, point, size, AnyElement, AppContext, Bounds, Context,
3 EventEmitter, FocusHandle, FocusableView, Img, InteractiveElement, IntoElement, Model,
4 ObjectFit, ParentElement, Render, Styled, Task, View, ViewContext, VisualContext, WeakView,
5 WindowContext,
6};
7use persistence::IMAGE_VIEWER;
8use ui::prelude::*;
9
10use project::{Project, ProjectEntryId, ProjectPath};
11use std::{ffi::OsStr, path::PathBuf};
12use util::ResultExt;
13use workspace::{
14 item::{Item, ProjectItem},
15 ItemId, Pane, Workspace, WorkspaceId,
16};
17
18const IMAGE_VIEWER_KIND: &str = "ImageView";
19
20pub struct ImageItem {
21 path: PathBuf,
22 project_path: ProjectPath,
23}
24
25impl project::Item for ImageItem {
26 fn try_open(
27 project: &Model<Project>,
28 path: &ProjectPath,
29 cx: &mut AppContext,
30 ) -> Option<Task<gpui::Result<Model<Self>>>> {
31 let path = path.clone();
32 let project = project.clone();
33
34 let ext = path
35 .path
36 .extension()
37 .and_then(OsStr::to_str)
38 .unwrap_or_default();
39
40 if Img::extensions().contains(&ext) {
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 checkered_background = |bounds: Bounds<Pixels>, _, cx: &mut ElementContext| {
160 let square_size = 32.0;
161
162 let start_y = bounds.origin.y.0;
163 let height = bounds.size.height.0;
164 let start_x = bounds.origin.x.0;
165 let width = bounds.size.width.0;
166
167 let mut y = start_y;
168 let mut x = start_x;
169 let mut color_swapper = true;
170 // draw checkerboard pattern
171 while y <= start_y + height {
172 // Keeping track of the grid in order to be resilient to resizing
173 let start_swap = color_swapper;
174 while x <= start_x + width {
175 let rect =
176 Bounds::new(point(px(x), px(y)), size(px(square_size), px(square_size)));
177
178 let color = if color_swapper {
179 opaque_grey(0.6, 0.4)
180 } else {
181 opaque_grey(0.7, 0.4)
182 };
183
184 cx.paint_quad(fill(rect, color));
185 color_swapper = !color_swapper;
186 x += square_size;
187 }
188 x = start_x;
189 color_swapper = !start_swap;
190 y += square_size;
191 }
192 };
193
194 let checkered_background = canvas(|_, _| (), checkered_background)
195 .border_2()
196 .border_color(cx.theme().styles.colors.border)
197 .size_full()
198 .absolute()
199 .top_0()
200 .left_0();
201
202 div()
203 .track_focus(&self.focus_handle)
204 .size_full()
205 .child(checkered_background)
206 .child(
207 div()
208 .flex()
209 .justify_center()
210 .items_center()
211 .w_full()
212 // TODO: In browser based Tailwind & Flex this would be h-screen and we'd use w-full
213 .h_full()
214 .child(
215 img(self.path.clone())
216 .object_fit(ObjectFit::ScaleDown)
217 .max_w_full()
218 .max_h_full(),
219 ),
220 )
221 }
222}
223
224impl ProjectItem for ImageView {
225 type Item = ImageItem;
226
227 fn for_project_item(
228 _project: Model<Project>,
229 item: Model<Self::Item>,
230 cx: &mut ViewContext<Self>,
231 ) -> Self
232 where
233 Self: Sized,
234 {
235 Self {
236 path: item.read(cx).path.clone(),
237 focus_handle: cx.focus_handle(),
238 }
239 }
240}
241
242pub fn init(cx: &mut AppContext) {
243 workspace::register_project_item::<ImageView>(cx);
244 workspace::register_deserializable_item::<ImageView>(cx)
245}
246
247mod persistence {
248 use std::path::PathBuf;
249
250 use db::{define_connection, query, sqlez_macros::sql};
251 use workspace::{ItemId, WorkspaceDb, WorkspaceId};
252
253 define_connection! {
254 pub static ref IMAGE_VIEWER: ImageViewerDb<WorkspaceDb> =
255 &[sql!(
256 CREATE TABLE image_viewers (
257 workspace_id INTEGER,
258 item_id INTEGER UNIQUE,
259
260 image_path BLOB,
261
262 PRIMARY KEY(workspace_id, item_id),
263 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
264 ON DELETE CASCADE
265 ) STRICT;
266 )];
267 }
268
269 impl ImageViewerDb {
270 query! {
271 pub async fn update_workspace_id(
272 new_id: WorkspaceId,
273 old_id: WorkspaceId,
274 item_id: ItemId
275 ) -> Result<()> {
276 UPDATE image_viewers
277 SET workspace_id = ?
278 WHERE workspace_id = ? AND item_id = ?
279 }
280 }
281
282 query! {
283 pub async fn save_image_path(
284 item_id: ItemId,
285 workspace_id: WorkspaceId,
286 image_path: PathBuf
287 ) -> Result<()> {
288 INSERT OR REPLACE INTO image_viewers(item_id, workspace_id, image_path)
289 VALUES (?, ?, ?)
290 }
291 }
292
293 query! {
294 pub fn get_image_path(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<PathBuf>> {
295 SELECT image_path
296 FROM image_viewers
297 WHERE item_id = ? AND workspace_id = ?
298 }
299 }
300 }
301}