1mod image_info;
2mod image_viewer_settings;
3
4use std::path::Path;
5
6use anyhow::Context as _;
7use editor::{EditorSettings, items::entry_git_aware_label_color};
8use file_icons::FileIcons;
9#[cfg(any(target_os = "linux", target_os = "macos"))]
10use gpui::PinchEvent;
11use gpui::{
12 AnyElement, App, Bounds, Context, DispatchPhase, Element, ElementId, Entity, EventEmitter,
13 FocusHandle, Focusable, GlobalElementId, InspectorElementId, InteractiveElement, IntoElement,
14 LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels,
15 Point, Render, ScrollDelta, ScrollWheelEvent, Style, Styled, Task, WeakEntity, Window, actions,
16 checkerboard, div, img, point, px, size,
17};
18use language::File as _;
19use persistence::IMAGE_VIEWER;
20use project::{ImageItem, Project, ProjectPath, image_store::ImageItemEvent};
21use settings::Settings;
22use theme::ThemeSettings;
23use ui::{Tooltip, prelude::*};
24use util::paths::PathExt;
25use workspace::{
26 ItemId, ItemSettings, Pane, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, Workspace,
27 WorkspaceId, delete_unloaded_items,
28 invalid_item_view::InvalidItemView,
29 item::{BreadcrumbText, Item, ItemHandle, ProjectItem, SerializableItem, TabContentParams},
30};
31
32pub use crate::image_info::*;
33pub use crate::image_viewer_settings::*;
34
35actions!(
36 image_viewer,
37 [
38 /// Zoom in the image.
39 ZoomIn,
40 /// Zoom out the image.
41 ZoomOut,
42 /// Reset zoom to 100%.
43 ResetZoom,
44 /// Fit the image to view.
45 FitToView,
46 /// Zoom to actual size (100%).
47 ZoomToActualSize
48 ]
49);
50
51const MIN_ZOOM: f32 = 0.1;
52const MAX_ZOOM: f32 = 20.0;
53const ZOOM_STEP: f32 = 1.1;
54const SCROLL_LINE_MULTIPLIER: f32 = 20.0;
55const BASE_SQUARE_SIZE: f32 = 32.0;
56
57pub struct ImageView {
58 image_item: Entity<ImageItem>,
59 project: Entity<Project>,
60 focus_handle: FocusHandle,
61 zoom_level: f32,
62 pan_offset: Point<Pixels>,
63 last_mouse_position: Option<Point<Pixels>>,
64 container_bounds: Option<Bounds<Pixels>>,
65 image_size: Option<(u32, u32)>,
66}
67
68impl ImageView {
69 fn is_dragging(&self) -> bool {
70 self.last_mouse_position.is_some()
71 }
72
73 pub fn new(
74 image_item: Entity<ImageItem>,
75 project: Entity<Project>,
76 window: &mut Window,
77 cx: &mut Context<Self>,
78 ) -> Self {
79 // Start loading the image to render in the background to prevent the view
80 // from flickering in most cases.
81 let _ = image_item.update(cx, |image, cx| {
82 image.image.clone().get_render_image(window, cx)
83 });
84
85 cx.subscribe(&image_item, Self::on_image_event).detach();
86 cx.on_release_in(window, |this, window, cx| {
87 let image_data = this.image_item.read(cx).image.clone();
88 if let Some(image) = image_data.clone().get_render_image(window, cx) {
89 cx.drop_image(image, None);
90 }
91 image_data.remove_asset(cx);
92 })
93 .detach();
94
95 let image_size = image_item
96 .read(cx)
97 .image_metadata
98 .map(|m| (m.width, m.height));
99
100 Self {
101 image_item,
102 project,
103 focus_handle: cx.focus_handle(),
104 zoom_level: 1.0,
105 pan_offset: Point::default(),
106 last_mouse_position: None,
107 container_bounds: None,
108 image_size,
109 }
110 }
111
112 fn on_image_event(
113 &mut self,
114 _: Entity<ImageItem>,
115 event: &ImageItemEvent,
116 cx: &mut Context<Self>,
117 ) {
118 match event {
119 ImageItemEvent::MetadataUpdated
120 | ImageItemEvent::FileHandleChanged
121 | ImageItemEvent::Reloaded => {
122 self.image_size = self
123 .image_item
124 .read(cx)
125 .image_metadata
126 .map(|m| (m.width, m.height));
127 cx.emit(ImageViewEvent::TitleChanged);
128 cx.notify();
129 }
130 ImageItemEvent::ReloadNeeded => {}
131 }
132 }
133
134 fn zoom_in(&mut self, _: &ZoomIn, _window: &mut Window, cx: &mut Context<Self>) {
135 self.set_zoom(self.zoom_level * ZOOM_STEP, None, cx);
136 }
137
138 fn zoom_out(&mut self, _: &ZoomOut, _window: &mut Window, cx: &mut Context<Self>) {
139 self.set_zoom(self.zoom_level / ZOOM_STEP, None, cx);
140 }
141
142 fn reset_zoom(&mut self, _: &ResetZoom, _window: &mut Window, cx: &mut Context<Self>) {
143 self.zoom_level = 1.0;
144 self.pan_offset = Point::default();
145 cx.notify();
146 }
147
148 fn fit_to_view(&mut self, _: &FitToView, _window: &mut Window, cx: &mut Context<Self>) {
149 if let Some((bounds, image_size)) = self.container_bounds.zip(self.image_size) {
150 self.zoom_level = ImageView::compute_fit_to_view_zoom(bounds, image_size);
151 self.pan_offset = Point::default();
152 cx.notify();
153 }
154 }
155
156 fn compute_fit_to_view_zoom(container_bounds: Bounds<Pixels>, image_size: (u32, u32)) -> f32 {
157 let (image_width, image_height) = image_size;
158 let container_width: f32 = container_bounds.size.width.into();
159 let container_height: f32 = container_bounds.size.height.into();
160 let scale_x = container_width / image_width as f32;
161 let scale_y = container_height / image_height as f32;
162 scale_x.min(scale_y).min(1.0)
163 }
164
165 fn zoom_to_actual_size(
166 &mut self,
167 _: &ZoomToActualSize,
168 _window: &mut Window,
169 cx: &mut Context<Self>,
170 ) {
171 self.zoom_level = 1.0;
172 self.pan_offset = Point::default();
173 cx.notify();
174 }
175
176 fn set_zoom(
177 &mut self,
178 new_zoom: f32,
179 zoom_center: Option<Point<Pixels>>,
180 cx: &mut Context<Self>,
181 ) {
182 let old_zoom = self.zoom_level;
183 self.zoom_level = new_zoom.clamp(MIN_ZOOM, MAX_ZOOM);
184
185 if let Some((center, bounds)) = zoom_center.zip(self.container_bounds) {
186 let relative_center = point(
187 center.x - bounds.origin.x - bounds.size.width / 2.0,
188 center.y - bounds.origin.y - bounds.size.height / 2.0,
189 );
190
191 let mouse_offset_from_image = relative_center - self.pan_offset;
192
193 let zoom_ratio = self.zoom_level / old_zoom;
194
195 self.pan_offset += mouse_offset_from_image * (1.0 - zoom_ratio);
196 }
197
198 cx.notify();
199 }
200
201 fn handle_scroll_wheel(
202 &mut self,
203 event: &ScrollWheelEvent,
204 _window: &mut Window,
205 cx: &mut Context<Self>,
206 ) {
207 if event.modifiers.control || event.modifiers.platform {
208 let delta: f32 = match event.delta {
209 ScrollDelta::Pixels(pixels) => pixels.y.into(),
210 ScrollDelta::Lines(lines) => lines.y * SCROLL_LINE_MULTIPLIER,
211 };
212 let zoom_factor = if delta > 0.0 {
213 1.0 + delta.abs() * 0.01
214 } else {
215 1.0 / (1.0 + delta.abs() * 0.01)
216 };
217 self.set_zoom(self.zoom_level * zoom_factor, Some(event.position), cx);
218 } else {
219 let delta = match event.delta {
220 ScrollDelta::Pixels(pixels) => pixels,
221 ScrollDelta::Lines(lines) => lines.map(|d| px(d * SCROLL_LINE_MULTIPLIER)),
222 };
223 self.pan_offset += delta;
224 cx.notify();
225 }
226 }
227
228 fn handle_mouse_down(
229 &mut self,
230 event: &MouseDownEvent,
231 _window: &mut Window,
232 cx: &mut Context<Self>,
233 ) {
234 if event.button == MouseButton::Left || event.button == MouseButton::Middle {
235 self.last_mouse_position = Some(event.position);
236 cx.notify();
237 }
238 }
239
240 fn handle_mouse_up(
241 &mut self,
242 _event: &MouseUpEvent,
243 _window: &mut Window,
244 cx: &mut Context<Self>,
245 ) {
246 self.last_mouse_position = None;
247 cx.notify();
248 }
249
250 fn handle_mouse_move(
251 &mut self,
252 event: &MouseMoveEvent,
253 _window: &mut Window,
254 cx: &mut Context<Self>,
255 ) {
256 if self.is_dragging() {
257 if let Some(last_pos) = self.last_mouse_position {
258 let delta = event.position - last_pos;
259 self.pan_offset += delta;
260 }
261 self.last_mouse_position = Some(event.position);
262 cx.notify();
263 }
264 }
265
266 #[cfg(any(target_os = "linux", target_os = "macos"))]
267 fn handle_pinch(&mut self, event: &PinchEvent, _window: &mut Window, cx: &mut Context<Self>) {
268 let zoom_factor = 1.0 + event.delta;
269 self.set_zoom(self.zoom_level * zoom_factor, Some(event.position), cx);
270 }
271}
272
273struct ImageContentElement {
274 image_view: Entity<ImageView>,
275}
276
277impl ImageContentElement {
278 fn new(image_view: Entity<ImageView>) -> Self {
279 Self { image_view }
280 }
281}
282
283impl IntoElement for ImageContentElement {
284 type Element = Self;
285
286 fn into_element(self) -> Self::Element {
287 self
288 }
289}
290
291impl Element for ImageContentElement {
292 type RequestLayoutState = ();
293 type PrepaintState = Option<(AnyElement, bool)>;
294
295 fn id(&self) -> Option<ElementId> {
296 None
297 }
298
299 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
300 None
301 }
302
303 fn request_layout(
304 &mut self,
305 _id: Option<&GlobalElementId>,
306 _inspector_id: Option<&InspectorElementId>,
307 window: &mut Window,
308 cx: &mut App,
309 ) -> (LayoutId, Self::RequestLayoutState) {
310 (
311 window.request_layout(
312 Style {
313 size: size(relative(1.).into(), relative(1.).into()),
314 ..Default::default()
315 },
316 [],
317 cx,
318 ),
319 (),
320 )
321 }
322
323 fn prepaint(
324 &mut self,
325 _id: Option<&GlobalElementId>,
326 _inspector_id: Option<&InspectorElementId>,
327 bounds: Bounds<Pixels>,
328 _request_layout: &mut Self::RequestLayoutState,
329 window: &mut Window,
330 cx: &mut App,
331 ) -> Self::PrepaintState {
332 let image_view = self.image_view.read(cx);
333 let image = image_view.image_item.read(cx).image.clone();
334
335 let first_layout = image_view.container_bounds.is_none();
336
337 let initial_zoom_level = first_layout
338 .then(|| {
339 image_view
340 .image_size
341 .map(|image_size| ImageView::compute_fit_to_view_zoom(bounds, image_size))
342 })
343 .flatten();
344
345 let zoom_level = initial_zoom_level.unwrap_or(image_view.zoom_level);
346
347 let pan_offset = image_view.pan_offset;
348 let border_color = cx.theme().colors().border;
349
350 let is_dragging = image_view.is_dragging();
351
352 let scaled_size = image_view
353 .image_size
354 .map(|(w, h)| (px(w as f32 * zoom_level), px(h as f32 * zoom_level)));
355
356 let (mut left, mut top) = (px(0.0), px(0.0));
357 let mut scaled_width = px(0.0);
358 let mut scaled_height = px(0.0);
359
360 if let Some((width, height)) = scaled_size {
361 scaled_width = width;
362 scaled_height = height;
363
364 let center_x = bounds.size.width / 2.0;
365 let center_y = bounds.size.height / 2.0;
366
367 left = center_x - (scaled_width / 2.0) + pan_offset.x;
368 top = center_y - (scaled_height / 2.0) + pan_offset.y;
369 }
370
371 self.image_view.update(cx, |this, _| {
372 this.container_bounds = Some(bounds);
373 if let Some(initial_zoom_level) = initial_zoom_level {
374 this.zoom_level = initial_zoom_level;
375 }
376 });
377
378 let mut image_content = div()
379 .relative()
380 .size_full()
381 .child(
382 div()
383 .absolute()
384 .left(left)
385 .top(top)
386 .w(scaled_width)
387 .h(scaled_height)
388 .child(
389 div()
390 .size_full()
391 .absolute()
392 .top_0()
393 .left_0()
394 .child(div().size_full().bg(checkerboard(
395 cx.theme().colors().panel_background,
396 BASE_SQUARE_SIZE * zoom_level,
397 )))
398 .border_1()
399 .border_color(border_color),
400 )
401 .child({
402 img(image)
403 .id(("image-viewer-image", self.image_view.entity_id()))
404 .size_full()
405 }),
406 )
407 .into_any_element();
408
409 image_content.prepaint_as_root(bounds.origin, bounds.size.into(), window, cx);
410 Some((image_content, is_dragging))
411 }
412
413 fn paint(
414 &mut self,
415 _id: Option<&GlobalElementId>,
416 _inspector_id: Option<&InspectorElementId>,
417 _bounds: Bounds<Pixels>,
418 _request_layout: &mut Self::RequestLayoutState,
419 prepaint: &mut Self::PrepaintState,
420 window: &mut Window,
421 cx: &mut App,
422 ) {
423 let Some((mut element, is_dragging)) = prepaint.take() else {
424 return;
425 };
426
427 if is_dragging {
428 let image_view = self.image_view.downgrade();
429 window.on_mouse_event(move |_event: &MouseUpEvent, phase, _window, cx| {
430 if phase == DispatchPhase::Bubble
431 && let Some(entity) = image_view.upgrade()
432 {
433 entity.update(cx, |this, cx| {
434 this.last_mouse_position = None;
435 cx.notify();
436 });
437 }
438 });
439 }
440
441 element.paint(window, cx);
442 }
443}
444
445pub enum ImageViewEvent {
446 TitleChanged,
447}
448
449impl EventEmitter<ImageViewEvent> for ImageView {}
450
451impl Item for ImageView {
452 type Event = ImageViewEvent;
453
454 fn to_item_events(event: &Self::Event, f: &mut dyn FnMut(workspace::item::ItemEvent)) {
455 match event {
456 ImageViewEvent::TitleChanged => {
457 f(workspace::item::ItemEvent::UpdateTab);
458 f(workspace::item::ItemEvent::UpdateBreadcrumbs);
459 }
460 }
461 }
462
463 fn for_each_project_item(
464 &self,
465 cx: &App,
466 f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
467 ) {
468 f(self.image_item.entity_id(), self.image_item.read(cx))
469 }
470
471 fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
472 let abs_path = self.image_item.read(cx).abs_path(cx)?;
473 let file_path = abs_path.compact().to_string_lossy().into_owned();
474 Some(file_path.into())
475 }
476
477 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
478 let project_path = self.image_item.read(cx).project_path(cx);
479
480 let label_color = if ItemSettings::get_global(cx).git_status {
481 let git_status = self
482 .project
483 .read(cx)
484 .project_path_git_status(&project_path, cx)
485 .map(|status| status.summary())
486 .unwrap_or_default();
487
488 self.project
489 .read(cx)
490 .entry_for_path(&project_path, cx)
491 .map(|entry| {
492 entry_git_aware_label_color(git_status, entry.is_ignored, params.selected)
493 })
494 .unwrap_or_else(|| params.text_color())
495 } else {
496 params.text_color()
497 };
498
499 Label::new(self.tab_content_text(params.detail.unwrap_or_default(), cx))
500 .single_line()
501 .color(label_color)
502 .when(params.preview, |this| this.italic())
503 .into_any_element()
504 }
505
506 fn tab_content_text(&self, _: usize, cx: &App) -> SharedString {
507 self.image_item
508 .read(cx)
509 .file
510 .file_name(cx)
511 .to_string()
512 .into()
513 }
514
515 fn tab_icon(&self, _: &Window, cx: &App) -> Option<Icon> {
516 let path = self.image_item.read(cx).abs_path(cx)?;
517 ItemSettings::get_global(cx)
518 .file_icons
519 .then(|| FileIcons::get_icon(&path, cx))
520 .flatten()
521 .map(Icon::from_path)
522 }
523
524 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
525 let show_breadcrumb = EditorSettings::get_global(cx).toolbar.breadcrumbs;
526 if show_breadcrumb {
527 ToolbarItemLocation::PrimaryLeft
528 } else {
529 ToolbarItemLocation::Hidden
530 }
531 }
532
533 fn breadcrumbs(&self, cx: &App) -> Option<Vec<BreadcrumbText>> {
534 let text = breadcrumbs_text_for_image(self.project.read(cx), self.image_item.read(cx), cx);
535 let settings = ThemeSettings::get_global(cx);
536
537 Some(vec![BreadcrumbText {
538 text,
539 highlights: None,
540 font: Some(settings.buffer_font.clone()),
541 }])
542 }
543
544 fn can_split(&self) -> bool {
545 true
546 }
547
548 fn clone_on_split(
549 &self,
550 _workspace_id: Option<WorkspaceId>,
551 _: &mut Window,
552 cx: &mut Context<Self>,
553 ) -> Task<Option<Entity<Self>>>
554 where
555 Self: Sized,
556 {
557 Task::ready(Some(cx.new(|cx| Self {
558 image_item: self.image_item.clone(),
559 project: self.project.clone(),
560 focus_handle: cx.focus_handle(),
561 zoom_level: self.zoom_level,
562 pan_offset: self.pan_offset,
563 last_mouse_position: None,
564 container_bounds: None,
565 image_size: self.image_size,
566 })))
567 }
568
569 fn has_deleted_file(&self, cx: &App) -> bool {
570 self.image_item.read(cx).file.disk_state().is_deleted()
571 }
572 fn buffer_kind(&self, _: &App) -> workspace::item::ItemBufferKind {
573 workspace::item::ItemBufferKind::Singleton
574 }
575}
576
577fn breadcrumbs_text_for_image(project: &Project, image: &ImageItem, cx: &App) -> String {
578 let mut path = image.file.path().clone();
579 if project.visible_worktrees(cx).count() > 1
580 && let Some(worktree) = project.worktree_for_id(image.project_path(cx).worktree_id, cx)
581 {
582 path = worktree.read(cx).root_name().join(&path);
583 }
584
585 path.display(project.path_style(cx)).to_string()
586}
587
588impl SerializableItem for ImageView {
589 fn serialized_item_kind() -> &'static str {
590 "ImageView"
591 }
592
593 fn deserialize(
594 project: Entity<Project>,
595 _workspace: WeakEntity<Workspace>,
596 workspace_id: WorkspaceId,
597 item_id: ItemId,
598 window: &mut Window,
599 cx: &mut App,
600 ) -> Task<anyhow::Result<Entity<Self>>> {
601 window.spawn(cx, async move |cx| {
602 let image_path = IMAGE_VIEWER
603 .get_image_path(item_id, workspace_id)?
604 .context("No image path found")?;
605
606 let (worktree, relative_path) = project
607 .update(cx, |project, cx| {
608 project.find_or_create_worktree(image_path.clone(), false, cx)
609 })
610 .await
611 .context("Path not found")?;
612 let worktree_id = worktree.update(cx, |worktree, _cx| worktree.id());
613
614 let project_path = ProjectPath {
615 worktree_id,
616 path: relative_path,
617 };
618
619 let image_item = project
620 .update(cx, |project, cx| project.open_image(project_path, cx))
621 .await?;
622
623 cx.update(
624 |window, cx| Ok(cx.new(|cx| ImageView::new(image_item, project, window, cx))),
625 )?
626 })
627 }
628
629 fn cleanup(
630 workspace_id: WorkspaceId,
631 alive_items: Vec<ItemId>,
632 _window: &mut Window,
633 cx: &mut App,
634 ) -> Task<anyhow::Result<()>> {
635 delete_unloaded_items(
636 alive_items,
637 workspace_id,
638 "image_viewers",
639 &IMAGE_VIEWER,
640 cx,
641 )
642 }
643
644 fn serialize(
645 &mut self,
646 workspace: &mut Workspace,
647 item_id: ItemId,
648 _closing: bool,
649 _window: &mut Window,
650 cx: &mut Context<Self>,
651 ) -> Option<Task<anyhow::Result<()>>> {
652 let workspace_id = workspace.database_id()?;
653 let image_path = self.image_item.read(cx).abs_path(cx)?;
654
655 Some(cx.background_spawn({
656 async move {
657 log::debug!("Saving image at path {image_path:?}");
658 IMAGE_VIEWER
659 .save_image_path(item_id, workspace_id, image_path)
660 .await
661 }
662 }))
663 }
664
665 fn should_serialize(&self, _event: &Self::Event) -> bool {
666 false
667 }
668}
669
670impl EventEmitter<()> for ImageView {}
671impl Focusable for ImageView {
672 fn focus_handle(&self, _cx: &App) -> FocusHandle {
673 self.focus_handle.clone()
674 }
675}
676
677impl Render for ImageView {
678 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
679 div()
680 .track_focus(&self.focus_handle(cx))
681 .key_context("ImageViewer")
682 .on_action(cx.listener(Self::zoom_in))
683 .on_action(cx.listener(Self::zoom_out))
684 .on_action(cx.listener(Self::reset_zoom))
685 .on_action(cx.listener(Self::fit_to_view))
686 .on_action(cx.listener(Self::zoom_to_actual_size))
687 .size_full()
688 .relative()
689 .bg(cx.theme().colors().editor_background)
690 .child({
691 #[cfg(any(target_os = "linux", target_os = "macos"))]
692 let container = div()
693 .id("image-container")
694 .size_full()
695 .overflow_hidden()
696 .cursor(if self.is_dragging() {
697 gpui::CursorStyle::ClosedHand
698 } else {
699 gpui::CursorStyle::OpenHand
700 })
701 .on_scroll_wheel(cx.listener(Self::handle_scroll_wheel))
702 .on_pinch(cx.listener(Self::handle_pinch))
703 .on_mouse_down(MouseButton::Left, cx.listener(Self::handle_mouse_down))
704 .on_mouse_down(MouseButton::Middle, cx.listener(Self::handle_mouse_down))
705 .on_mouse_up(MouseButton::Left, cx.listener(Self::handle_mouse_up))
706 .on_mouse_up(MouseButton::Middle, cx.listener(Self::handle_mouse_up))
707 .on_mouse_move(cx.listener(Self::handle_mouse_move))
708 .child(ImageContentElement::new(cx.entity()));
709
710 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
711 let container = div()
712 .id("image-container")
713 .size_full()
714 .overflow_hidden()
715 .cursor(if self.is_dragging() {
716 gpui::CursorStyle::ClosedHand
717 } else {
718 gpui::CursorStyle::OpenHand
719 })
720 .on_scroll_wheel(cx.listener(Self::handle_scroll_wheel))
721 .on_mouse_down(MouseButton::Left, cx.listener(Self::handle_mouse_down))
722 .on_mouse_down(MouseButton::Middle, cx.listener(Self::handle_mouse_down))
723 .on_mouse_up(MouseButton::Left, cx.listener(Self::handle_mouse_up))
724 .on_mouse_up(MouseButton::Middle, cx.listener(Self::handle_mouse_up))
725 .on_mouse_move(cx.listener(Self::handle_mouse_move))
726 .child(ImageContentElement::new(cx.entity()));
727
728 container
729 })
730 }
731}
732
733impl ProjectItem for ImageView {
734 type Item = ImageItem;
735
736 fn for_project_item(
737 project: Entity<Project>,
738 _: Option<&Pane>,
739 item: Entity<Self::Item>,
740 window: &mut Window,
741 cx: &mut Context<Self>,
742 ) -> Self
743 where
744 Self: Sized,
745 {
746 Self::new(item, project, window, cx)
747 }
748
749 fn for_broken_project_item(
750 abs_path: &Path,
751 is_local: bool,
752 e: &anyhow::Error,
753 window: &mut Window,
754 cx: &mut App,
755 ) -> Option<InvalidItemView>
756 where
757 Self: Sized,
758 {
759 Some(InvalidItemView::new(abs_path, is_local, e, window, cx))
760 }
761}
762
763pub struct ImageViewToolbarControls {
764 image_view: Option<WeakEntity<ImageView>>,
765 _subscription: Option<gpui::Subscription>,
766}
767
768impl ImageViewToolbarControls {
769 pub fn new() -> Self {
770 Self {
771 image_view: None,
772 _subscription: None,
773 }
774 }
775}
776
777impl Render for ImageViewToolbarControls {
778 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
779 let Some(image_view) = self.image_view.as_ref().and_then(|v| v.upgrade()) else {
780 return div().into_any_element();
781 };
782
783 let zoom_level = image_view.read(cx).zoom_level;
784 let zoom_percentage = format!("{}%", (zoom_level * 100.0).round() as i32);
785
786 h_flex()
787 .gap_1()
788 .child(
789 IconButton::new("zoom-out", IconName::Dash)
790 .icon_size(IconSize::Small)
791 .tooltip(|_window, cx| Tooltip::for_action("Zoom Out", &ZoomOut, cx))
792 .on_click({
793 let image_view = image_view.downgrade();
794 move |_, window, cx| {
795 if let Some(view) = image_view.upgrade() {
796 view.update(cx, |this, cx| {
797 this.zoom_out(&ZoomOut, window, cx);
798 });
799 }
800 }
801 }),
802 )
803 .child(
804 Button::new("zoom-level", zoom_percentage)
805 .label_size(LabelSize::Small)
806 .tooltip(|_window, cx| Tooltip::for_action("Reset Zoom", &ResetZoom, cx))
807 .on_click({
808 let image_view = image_view.downgrade();
809 move |_, window, cx| {
810 if let Some(view) = image_view.upgrade() {
811 view.update(cx, |this, cx| {
812 this.reset_zoom(&ResetZoom, window, cx);
813 });
814 }
815 }
816 }),
817 )
818 .child(
819 IconButton::new("zoom-in", IconName::Plus)
820 .icon_size(IconSize::Small)
821 .tooltip(|_window, cx| Tooltip::for_action("Zoom In", &ZoomIn, cx))
822 .on_click({
823 let image_view = image_view.downgrade();
824 move |_, window, cx| {
825 if let Some(view) = image_view.upgrade() {
826 view.update(cx, |this, cx| {
827 this.zoom_in(&ZoomIn, window, cx);
828 });
829 }
830 }
831 }),
832 )
833 .child(
834 IconButton::new("fit-to-view", IconName::Maximize)
835 .icon_size(IconSize::Small)
836 .tooltip(|_window, cx| Tooltip::for_action("Fit to View", &FitToView, cx))
837 .on_click({
838 let image_view = image_view.downgrade();
839 move |_, window, cx| {
840 if let Some(view) = image_view.upgrade() {
841 view.update(cx, |this, cx| {
842 this.fit_to_view(&FitToView, window, cx);
843 });
844 }
845 }
846 }),
847 )
848 .into_any_element()
849 }
850}
851
852impl EventEmitter<ToolbarItemEvent> for ImageViewToolbarControls {}
853
854impl ToolbarItemView for ImageViewToolbarControls {
855 fn set_active_pane_item(
856 &mut self,
857 active_pane_item: Option<&dyn ItemHandle>,
858 _window: &mut Window,
859 cx: &mut Context<Self>,
860 ) -> ToolbarItemLocation {
861 self.image_view = None;
862 self._subscription = None;
863
864 if let Some(item) = active_pane_item.and_then(|i| i.downcast::<ImageView>()) {
865 self._subscription = Some(cx.observe(&item, |_, _, cx| {
866 cx.notify();
867 }));
868 self.image_view = Some(item.downgrade());
869 cx.notify();
870 return ToolbarItemLocation::PrimaryRight;
871 }
872
873 ToolbarItemLocation::Hidden
874 }
875}
876
877pub fn init(cx: &mut App) {
878 workspace::register_project_item::<ImageView>(cx);
879 workspace::register_serializable_item::<ImageView>(cx);
880}
881
882mod persistence {
883 use std::path::PathBuf;
884
885 use db::{
886 query,
887 sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
888 sqlez_macros::sql,
889 };
890 use workspace::{ItemId, WorkspaceDb, WorkspaceId};
891
892 pub struct ImageViewerDb(ThreadSafeConnection);
893
894 impl Domain for ImageViewerDb {
895 const NAME: &str = stringify!(ImageViewerDb);
896
897 const MIGRATIONS: &[&str] = &[sql!(
898 CREATE TABLE image_viewers (
899 workspace_id INTEGER,
900 item_id INTEGER UNIQUE,
901
902 image_path BLOB,
903
904 PRIMARY KEY(workspace_id, item_id),
905 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
906 ON DELETE CASCADE
907 ) STRICT;
908 )];
909 }
910
911 db::static_connection!(IMAGE_VIEWER, ImageViewerDb, [WorkspaceDb]);
912
913 impl ImageViewerDb {
914 query! {
915 pub async fn save_image_path(
916 item_id: ItemId,
917 workspace_id: WorkspaceId,
918 image_path: PathBuf
919 ) -> Result<()> {
920 INSERT OR REPLACE INTO image_viewers(item_id, workspace_id, image_path)
921 VALUES (?, ?, ?)
922 }
923 }
924
925 query! {
926 pub fn get_image_path(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<PathBuf>> {
927 SELECT image_path
928 FROM image_viewers
929 WHERE item_id = ? AND workspace_id = ?
930 }
931 }
932 }
933}