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