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 // Only open the item if it's a binary image (no SVGs, etc.)
41 // Since we do not have a way to toggle to an editor
42 if Img::extensions().contains(&ext) && !ext.contains("svg") {
43 Some(cx.spawn(|mut cx| async move {
44 let abs_path = project
45 .read_with(&cx, |project, cx| project.absolute_path(&path, cx))?
46 .ok_or_else(|| anyhow::anyhow!("Failed to find the absolute path"))?;
47
48 cx.new_model(|_| ImageItem {
49 path: abs_path,
50 project_path: path,
51 })
52 }))
53 } else {
54 None
55 }
56 }
57
58 fn entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
59 None
60 }
61
62 fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
63 Some(self.project_path.clone())
64 }
65}
66
67pub struct ImageView {
68 path: PathBuf,
69 focus_handle: FocusHandle,
70}
71
72impl Item for ImageView {
73 type Event = ();
74
75 fn tab_content(
76 &self,
77 _detail: Option<usize>,
78 selected: bool,
79 _cx: &WindowContext,
80 ) -> AnyElement {
81 let title = self
82 .path
83 .file_name()
84 .unwrap_or_else(|| self.path.as_os_str())
85 .to_string_lossy()
86 .to_string();
87 Label::new(title)
88 .single_line()
89 .color(if selected {
90 Color::Default
91 } else {
92 Color::Muted
93 })
94 .into_any_element()
95 }
96
97 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
98 let item_id = cx.entity_id().as_u64();
99 let workspace_id = workspace.database_id();
100 let image_path = self.path.clone();
101
102 cx.background_executor()
103 .spawn({
104 let image_path = image_path.clone();
105 async move {
106 IMAGE_VIEWER
107 .save_image_path(item_id, workspace_id, image_path)
108 .await
109 .log_err();
110 }
111 })
112 .detach();
113 }
114
115 fn serialized_item_kind() -> Option<&'static str> {
116 Some(IMAGE_VIEWER_KIND)
117 }
118
119 fn deserialize(
120 _project: Model<Project>,
121 _workspace: WeakView<Workspace>,
122 workspace_id: WorkspaceId,
123 item_id: ItemId,
124 cx: &mut ViewContext<Pane>,
125 ) -> Task<anyhow::Result<View<Self>>> {
126 cx.spawn(|_pane, mut cx| async move {
127 let image_path = IMAGE_VIEWER
128 .get_image_path(item_id, workspace_id)?
129 .ok_or_else(|| anyhow::anyhow!("No image path found"))?;
130
131 cx.new_view(|cx| ImageView {
132 path: image_path,
133 focus_handle: cx.focus_handle(),
134 })
135 })
136 }
137
138 fn clone_on_split(
139 &self,
140 _workspace_id: WorkspaceId,
141 cx: &mut ViewContext<Self>,
142 ) -> Option<View<Self>>
143 where
144 Self: Sized,
145 {
146 Some(cx.new_view(|cx| Self {
147 path: self.path.clone(),
148 focus_handle: cx.focus_handle(),
149 }))
150 }
151}
152
153impl EventEmitter<()> for ImageView {}
154impl FocusableView for ImageView {
155 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
156 self.focus_handle.clone()
157 }
158}
159
160impl Render for ImageView {
161 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
162 let checkered_background = |bounds: Bounds<Pixels>, _, cx: &mut ElementContext| {
163 let square_size = 32.0;
164
165 let start_y = bounds.origin.y.0;
166 let height = bounds.size.height.0;
167 let start_x = bounds.origin.x.0;
168 let width = bounds.size.width.0;
169
170 let mut y = start_y;
171 let mut x = start_x;
172 let mut color_swapper = true;
173 // draw checkerboard pattern
174 while y <= start_y + height {
175 // Keeping track of the grid in order to be resilient to resizing
176 let start_swap = color_swapper;
177 while x <= start_x + width {
178 let rect =
179 Bounds::new(point(px(x), px(y)), size(px(square_size), px(square_size)));
180
181 let color = if color_swapper {
182 opaque_grey(0.6, 0.4)
183 } else {
184 opaque_grey(0.7, 0.4)
185 };
186
187 cx.paint_quad(fill(rect, color));
188 color_swapper = !color_swapper;
189 x += square_size;
190 }
191 x = start_x;
192 color_swapper = !start_swap;
193 y += square_size;
194 }
195 };
196
197 let checkered_background = canvas(|_, _| (), checkered_background)
198 .border_2()
199 .border_color(cx.theme().styles.colors.border)
200 .size_full()
201 .absolute()
202 .top_0()
203 .left_0();
204
205 div()
206 .track_focus(&self.focus_handle)
207 .size_full()
208 .child(checkered_background)
209 .child(
210 div()
211 .flex()
212 .justify_center()
213 .items_center()
214 .w_full()
215 // TODO: In browser based Tailwind & Flex this would be h-screen and we'd use w-full
216 .h_full()
217 .child(
218 img(self.path.clone())
219 .object_fit(ObjectFit::ScaleDown)
220 .max_w_full()
221 .max_h_full(),
222 ),
223 )
224 }
225}
226
227impl ProjectItem for ImageView {
228 type Item = ImageItem;
229
230 fn for_project_item(
231 _project: Model<Project>,
232 item: Model<Self::Item>,
233 cx: &mut ViewContext<Self>,
234 ) -> Self
235 where
236 Self: Sized,
237 {
238 Self {
239 path: item.read(cx).path.clone(),
240 focus_handle: cx.focus_handle(),
241 }
242 }
243}
244
245pub fn init(cx: &mut AppContext) {
246 workspace::register_project_item::<ImageView>(cx);
247 workspace::register_deserializable_item::<ImageView>(cx)
248}
249
250mod persistence {
251 use std::path::PathBuf;
252
253 use db::{define_connection, query, sqlez_macros::sql};
254 use workspace::{ItemId, WorkspaceDb, WorkspaceId};
255
256 define_connection! {
257 pub static ref IMAGE_VIEWER: ImageViewerDb<WorkspaceDb> =
258 &[sql!(
259 CREATE TABLE image_viewers (
260 workspace_id INTEGER,
261 item_id INTEGER UNIQUE,
262
263 image_path BLOB,
264
265 PRIMARY KEY(workspace_id, item_id),
266 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
267 ON DELETE CASCADE
268 ) STRICT;
269 )];
270 }
271
272 impl ImageViewerDb {
273 query! {
274 pub async fn update_workspace_id(
275 new_id: WorkspaceId,
276 old_id: WorkspaceId,
277 item_id: ItemId
278 ) -> Result<()> {
279 UPDATE image_viewers
280 SET workspace_id = ?
281 WHERE workspace_id = ? AND item_id = ?
282 }
283 }
284
285 query! {
286 pub async fn save_image_path(
287 item_id: ItemId,
288 workspace_id: WorkspaceId,
289 image_path: PathBuf
290 ) -> Result<()> {
291 INSERT OR REPLACE INTO image_viewers(item_id, workspace_id, image_path)
292 VALUES (?, ?, ?)
293 }
294 }
295
296 query! {
297 pub fn get_image_path(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<PathBuf>> {
298 SELECT image_path
299 FROM image_viewers
300 WHERE item_id = ? AND workspace_id = ?
301 }
302 }
303 }
304}