image_viewer.rs

  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, GlobalElementId, InspectorElementId, InteractiveElement, IntoElement,
 12    LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels,
 13    Point, Render, ScrollDelta, ScrollWheelEvent, Style, Styled, Task, WeakEntity, Window, actions,
 14    checkerboard, div, img, point, px, size,
 15};
 16use language::File as _;
 17use persistence::IMAGE_VIEWER;
 18use project::{ImageItem, Project, ProjectPath, image_store::ImageItemEvent};
 19use settings::Settings;
 20use theme::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::{BreadcrumbText, 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
265struct ImageContentElement {
266    image_view: Entity<ImageView>,
267}
268
269impl ImageContentElement {
270    fn new(image_view: Entity<ImageView>) -> Self {
271        Self { image_view }
272    }
273}
274
275impl IntoElement for ImageContentElement {
276    type Element = Self;
277
278    fn into_element(self) -> Self::Element {
279        self
280    }
281}
282
283impl Element for ImageContentElement {
284    type RequestLayoutState = ();
285    type PrepaintState = Option<(AnyElement, bool)>;
286
287    fn id(&self) -> Option<ElementId> {
288        None
289    }
290
291    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
292        None
293    }
294
295    fn request_layout(
296        &mut self,
297        _id: Option<&GlobalElementId>,
298        _inspector_id: Option<&InspectorElementId>,
299        window: &mut Window,
300        cx: &mut App,
301    ) -> (LayoutId, Self::RequestLayoutState) {
302        (
303            window.request_layout(
304                Style {
305                    size: size(relative(1.).into(), relative(1.).into()),
306                    ..Default::default()
307                },
308                [],
309                cx,
310            ),
311            (),
312        )
313    }
314
315    fn prepaint(
316        &mut self,
317        _id: Option<&GlobalElementId>,
318        _inspector_id: Option<&InspectorElementId>,
319        bounds: Bounds<Pixels>,
320        _request_layout: &mut Self::RequestLayoutState,
321        window: &mut Window,
322        cx: &mut App,
323    ) -> Self::PrepaintState {
324        let image_view = self.image_view.read(cx);
325        let image = image_view.image_item.read(cx).image.clone();
326
327        let first_layout = image_view.container_bounds.is_none();
328
329        let initial_zoom_level = first_layout
330            .then(|| {
331                image_view
332                    .image_size
333                    .map(|image_size| ImageView::compute_fit_to_view_zoom(bounds, image_size))
334            })
335            .flatten();
336
337        let zoom_level = initial_zoom_level.unwrap_or(image_view.zoom_level);
338
339        let pan_offset = image_view.pan_offset;
340        let border_color = cx.theme().colors().border;
341
342        let is_dragging = image_view.is_dragging();
343
344        let scaled_size = image_view
345            .image_size
346            .map(|(w, h)| (px(w as f32 * zoom_level), px(h as f32 * zoom_level)));
347
348        let (mut left, mut top) = (px(0.0), px(0.0));
349        let mut scaled_width = px(0.0);
350        let mut scaled_height = px(0.0);
351
352        if let Some((width, height)) = scaled_size {
353            scaled_width = width;
354            scaled_height = height;
355
356            let center_x = bounds.size.width / 2.0;
357            let center_y = bounds.size.height / 2.0;
358
359            left = center_x - (scaled_width / 2.0) + pan_offset.x;
360            top = center_y - (scaled_height / 2.0) + pan_offset.y;
361        }
362
363        self.image_view.update(cx, |this, _| {
364            this.container_bounds = Some(bounds);
365            if let Some(initial_zoom_level) = initial_zoom_level {
366                this.zoom_level = initial_zoom_level;
367            }
368        });
369
370        let mut image_content = div()
371            .relative()
372            .size_full()
373            .child(
374                div()
375                    .absolute()
376                    .left(left)
377                    .top(top)
378                    .w(scaled_width)
379                    .h(scaled_height)
380                    .child(
381                        div()
382                            .size_full()
383                            .absolute()
384                            .top_0()
385                            .left_0()
386                            .child(div().size_full().bg(checkerboard(
387                                cx.theme().colors().panel_background,
388                                BASE_SQUARE_SIZE * zoom_level,
389                            )))
390                            .border_1()
391                            .border_color(border_color),
392                    )
393                    .child({
394                        img(image)
395                            .id(("image-viewer-image", self.image_view.entity_id()))
396                            .size_full()
397                    }),
398            )
399            .into_any_element();
400
401        image_content.prepaint_as_root(bounds.origin, bounds.size.into(), window, cx);
402        Some((image_content, is_dragging))
403    }
404
405    fn paint(
406        &mut self,
407        _id: Option<&GlobalElementId>,
408        _inspector_id: Option<&InspectorElementId>,
409        _bounds: Bounds<Pixels>,
410        _request_layout: &mut Self::RequestLayoutState,
411        prepaint: &mut Self::PrepaintState,
412        window: &mut Window,
413        cx: &mut App,
414    ) {
415        let Some((mut element, is_dragging)) = prepaint.take() else {
416            return;
417        };
418
419        if is_dragging {
420            let image_view = self.image_view.downgrade();
421            window.on_mouse_event(move |_event: &MouseUpEvent, phase, _window, cx| {
422                if phase == DispatchPhase::Bubble
423                    && let Some(entity) = image_view.upgrade()
424                {
425                    entity.update(cx, |this, cx| {
426                        this.last_mouse_position = None;
427                        cx.notify();
428                    });
429                }
430            });
431        }
432
433        element.paint(window, cx);
434    }
435}
436
437pub enum ImageViewEvent {
438    TitleChanged,
439}
440
441impl EventEmitter<ImageViewEvent> for ImageView {}
442
443impl Item for ImageView {
444    type Event = ImageViewEvent;
445
446    fn to_item_events(event: &Self::Event, f: &mut dyn FnMut(workspace::item::ItemEvent)) {
447        match event {
448            ImageViewEvent::TitleChanged => {
449                f(workspace::item::ItemEvent::UpdateTab);
450                f(workspace::item::ItemEvent::UpdateBreadcrumbs);
451            }
452        }
453    }
454
455    fn for_each_project_item(
456        &self,
457        cx: &App,
458        f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
459    ) {
460        f(self.image_item.entity_id(), self.image_item.read(cx))
461    }
462
463    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
464        let abs_path = self.image_item.read(cx).abs_path(cx)?;
465        let file_path = abs_path.compact().to_string_lossy().into_owned();
466        Some(file_path.into())
467    }
468
469    fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
470        let project_path = self.image_item.read(cx).project_path(cx);
471
472        let label_color = if ItemSettings::get_global(cx).git_status {
473            let git_status = self
474                .project
475                .read(cx)
476                .project_path_git_status(&project_path, cx)
477                .map(|status| status.summary())
478                .unwrap_or_default();
479
480            self.project
481                .read(cx)
482                .entry_for_path(&project_path, cx)
483                .map(|entry| {
484                    entry_git_aware_label_color(git_status, entry.is_ignored, params.selected)
485                })
486                .unwrap_or_else(|| params.text_color())
487        } else {
488            params.text_color()
489        };
490
491        Label::new(self.tab_content_text(params.detail.unwrap_or_default(), cx))
492            .single_line()
493            .color(label_color)
494            .when(params.preview, |this| this.italic())
495            .into_any_element()
496    }
497
498    fn tab_content_text(&self, _: usize, cx: &App) -> SharedString {
499        self.image_item
500            .read(cx)
501            .file
502            .file_name(cx)
503            .to_string()
504            .into()
505    }
506
507    fn tab_icon(&self, _: &Window, cx: &App) -> Option<Icon> {
508        let path = self.image_item.read(cx).abs_path(cx)?;
509        ItemSettings::get_global(cx)
510            .file_icons
511            .then(|| FileIcons::get_icon(&path, cx))
512            .flatten()
513            .map(Icon::from_path)
514    }
515
516    fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
517        let show_breadcrumb = EditorSettings::get_global(cx).toolbar.breadcrumbs;
518        if show_breadcrumb {
519            ToolbarItemLocation::PrimaryLeft
520        } else {
521            ToolbarItemLocation::Hidden
522        }
523    }
524
525    fn breadcrumbs(&self, cx: &App) -> Option<Vec<BreadcrumbText>> {
526        let text = breadcrumbs_text_for_image(self.project.read(cx), self.image_item.read(cx), cx);
527        let settings = ThemeSettings::get_global(cx);
528
529        Some(vec![BreadcrumbText {
530            text,
531            highlights: None,
532            font: Some(settings.buffer_font.clone()),
533        }])
534    }
535
536    fn can_split(&self) -> bool {
537        true
538    }
539
540    fn clone_on_split(
541        &self,
542        _workspace_id: Option<WorkspaceId>,
543        _: &mut Window,
544        cx: &mut Context<Self>,
545    ) -> Task<Option<Entity<Self>>>
546    where
547        Self: Sized,
548    {
549        Task::ready(Some(cx.new(|cx| Self {
550            image_item: self.image_item.clone(),
551            project: self.project.clone(),
552            focus_handle: cx.focus_handle(),
553            zoom_level: self.zoom_level,
554            pan_offset: self.pan_offset,
555            last_mouse_position: None,
556            container_bounds: None,
557            image_size: self.image_size,
558        })))
559    }
560
561    fn has_deleted_file(&self, cx: &App) -> bool {
562        self.image_item.read(cx).file.disk_state().is_deleted()
563    }
564    fn buffer_kind(&self, _: &App) -> workspace::item::ItemBufferKind {
565        workspace::item::ItemBufferKind::Singleton
566    }
567}
568
569fn breadcrumbs_text_for_image(project: &Project, image: &ImageItem, cx: &App) -> String {
570    let mut path = image.file.path().clone();
571    if project.visible_worktrees(cx).count() > 1
572        && let Some(worktree) = project.worktree_for_id(image.project_path(cx).worktree_id, cx)
573    {
574        path = worktree.read(cx).root_name().join(&path);
575    }
576
577    path.display(project.path_style(cx)).to_string()
578}
579
580impl SerializableItem for ImageView {
581    fn serialized_item_kind() -> &'static str {
582        "ImageView"
583    }
584
585    fn deserialize(
586        project: Entity<Project>,
587        _workspace: WeakEntity<Workspace>,
588        workspace_id: WorkspaceId,
589        item_id: ItemId,
590        window: &mut Window,
591        cx: &mut App,
592    ) -> Task<anyhow::Result<Entity<Self>>> {
593        window.spawn(cx, async move |cx| {
594            let image_path = IMAGE_VIEWER
595                .get_image_path(item_id, workspace_id)?
596                .context("No image path found")?;
597
598            let (worktree, relative_path) = project
599                .update(cx, |project, cx| {
600                    project.find_or_create_worktree(image_path.clone(), false, cx)
601                })
602                .await
603                .context("Path not found")?;
604            let worktree_id = worktree.update(cx, |worktree, _cx| worktree.id());
605
606            let project_path = ProjectPath {
607                worktree_id,
608                path: relative_path,
609            };
610
611            let image_item = project
612                .update(cx, |project, cx| project.open_image(project_path, cx))
613                .await?;
614
615            cx.update(
616                |window, cx| Ok(cx.new(|cx| ImageView::new(image_item, project, window, cx))),
617            )?
618        })
619    }
620
621    fn cleanup(
622        workspace_id: WorkspaceId,
623        alive_items: Vec<ItemId>,
624        _window: &mut Window,
625        cx: &mut App,
626    ) -> Task<anyhow::Result<()>> {
627        delete_unloaded_items(
628            alive_items,
629            workspace_id,
630            "image_viewers",
631            &IMAGE_VIEWER,
632            cx,
633        )
634    }
635
636    fn serialize(
637        &mut self,
638        workspace: &mut Workspace,
639        item_id: ItemId,
640        _closing: bool,
641        _window: &mut Window,
642        cx: &mut Context<Self>,
643    ) -> Option<Task<anyhow::Result<()>>> {
644        let workspace_id = workspace.database_id()?;
645        let image_path = self.image_item.read(cx).abs_path(cx)?;
646
647        Some(cx.background_spawn({
648            async move {
649                log::debug!("Saving image at path {image_path:?}");
650                IMAGE_VIEWER
651                    .save_image_path(item_id, workspace_id, image_path)
652                    .await
653            }
654        }))
655    }
656
657    fn should_serialize(&self, _event: &Self::Event) -> bool {
658        false
659    }
660}
661
662impl EventEmitter<()> for ImageView {}
663impl Focusable for ImageView {
664    fn focus_handle(&self, _cx: &App) -> FocusHandle {
665        self.focus_handle.clone()
666    }
667}
668
669impl Render for ImageView {
670    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
671        div()
672            .track_focus(&self.focus_handle(cx))
673            .key_context("ImageViewer")
674            .on_action(cx.listener(Self::zoom_in))
675            .on_action(cx.listener(Self::zoom_out))
676            .on_action(cx.listener(Self::reset_zoom))
677            .on_action(cx.listener(Self::fit_to_view))
678            .on_action(cx.listener(Self::zoom_to_actual_size))
679            .size_full()
680            .relative()
681            .bg(cx.theme().colors().editor_background)
682            .child(
683                div()
684                    .id("image-container")
685                    .size_full()
686                    .overflow_hidden()
687                    .cursor(if self.is_dragging() {
688                        gpui::CursorStyle::ClosedHand
689                    } else {
690                        gpui::CursorStyle::OpenHand
691                    })
692                    .on_scroll_wheel(cx.listener(Self::handle_scroll_wheel))
693                    .on_mouse_down(MouseButton::Left, cx.listener(Self::handle_mouse_down))
694                    .on_mouse_down(MouseButton::Middle, cx.listener(Self::handle_mouse_down))
695                    .on_mouse_up(MouseButton::Left, cx.listener(Self::handle_mouse_up))
696                    .on_mouse_up(MouseButton::Middle, cx.listener(Self::handle_mouse_up))
697                    .on_mouse_move(cx.listener(Self::handle_mouse_move))
698                    .child(ImageContentElement::new(cx.entity())),
699            )
700    }
701}
702
703impl ProjectItem for ImageView {
704    type Item = ImageItem;
705
706    fn for_project_item(
707        project: Entity<Project>,
708        _: Option<&Pane>,
709        item: Entity<Self::Item>,
710        window: &mut Window,
711        cx: &mut Context<Self>,
712    ) -> Self
713    where
714        Self: Sized,
715    {
716        Self::new(item, project, window, cx)
717    }
718
719    fn for_broken_project_item(
720        abs_path: &Path,
721        is_local: bool,
722        e: &anyhow::Error,
723        window: &mut Window,
724        cx: &mut App,
725    ) -> Option<InvalidItemView>
726    where
727        Self: Sized,
728    {
729        Some(InvalidItemView::new(abs_path, is_local, e, window, cx))
730    }
731}
732
733pub struct ImageViewToolbarControls {
734    image_view: Option<WeakEntity<ImageView>>,
735    _subscription: Option<gpui::Subscription>,
736}
737
738impl ImageViewToolbarControls {
739    pub fn new() -> Self {
740        Self {
741            image_view: None,
742            _subscription: None,
743        }
744    }
745}
746
747impl Render for ImageViewToolbarControls {
748    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
749        let Some(image_view) = self.image_view.as_ref().and_then(|v| v.upgrade()) else {
750            return div().into_any_element();
751        };
752
753        let zoom_level = image_view.read(cx).zoom_level;
754        let zoom_percentage = format!("{}%", (zoom_level * 100.0).round() as i32);
755
756        h_flex()
757            .gap_1()
758            .child(
759                IconButton::new("zoom-out", IconName::Dash)
760                    .icon_size(IconSize::Small)
761                    .tooltip(|_window, cx| Tooltip::for_action("Zoom Out", &ZoomOut, cx))
762                    .on_click({
763                        let image_view = image_view.downgrade();
764                        move |_, window, cx| {
765                            if let Some(view) = image_view.upgrade() {
766                                view.update(cx, |this, cx| {
767                                    this.zoom_out(&ZoomOut, window, cx);
768                                });
769                            }
770                        }
771                    }),
772            )
773            .child(
774                Button::new("zoom-level", zoom_percentage)
775                    .label_size(LabelSize::Small)
776                    .tooltip(|_window, cx| Tooltip::for_action("Reset Zoom", &ResetZoom, cx))
777                    .on_click({
778                        let image_view = image_view.downgrade();
779                        move |_, window, cx| {
780                            if let Some(view) = image_view.upgrade() {
781                                view.update(cx, |this, cx| {
782                                    this.reset_zoom(&ResetZoom, window, cx);
783                                });
784                            }
785                        }
786                    }),
787            )
788            .child(
789                IconButton::new("zoom-in", IconName::Plus)
790                    .icon_size(IconSize::Small)
791                    .tooltip(|_window, cx| Tooltip::for_action("Zoom In", &ZoomIn, 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_in(&ZoomIn, window, cx);
798                                });
799                            }
800                        }
801                    }),
802            )
803            .child(
804                IconButton::new("fit-to-view", IconName::Maximize)
805                    .icon_size(IconSize::Small)
806                    .tooltip(|_window, cx| Tooltip::for_action("Fit to View", &FitToView, 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.fit_to_view(&FitToView, window, cx);
813                                });
814                            }
815                        }
816                    }),
817            )
818            .into_any_element()
819    }
820}
821
822impl EventEmitter<ToolbarItemEvent> for ImageViewToolbarControls {}
823
824impl ToolbarItemView for ImageViewToolbarControls {
825    fn set_active_pane_item(
826        &mut self,
827        active_pane_item: Option<&dyn ItemHandle>,
828        _window: &mut Window,
829        cx: &mut Context<Self>,
830    ) -> ToolbarItemLocation {
831        self.image_view = None;
832        self._subscription = None;
833
834        if let Some(item) = active_pane_item.and_then(|i| i.downcast::<ImageView>()) {
835            self._subscription = Some(cx.observe(&item, |_, _, cx| {
836                cx.notify();
837            }));
838            self.image_view = Some(item.downgrade());
839            cx.notify();
840            return ToolbarItemLocation::PrimaryRight;
841        }
842
843        ToolbarItemLocation::Hidden
844    }
845}
846
847pub fn init(cx: &mut App) {
848    workspace::register_project_item::<ImageView>(cx);
849    workspace::register_serializable_item::<ImageView>(cx);
850}
851
852mod persistence {
853    use std::path::PathBuf;
854
855    use db::{
856        query,
857        sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
858        sqlez_macros::sql,
859    };
860    use workspace::{ItemId, WorkspaceDb, WorkspaceId};
861
862    pub struct ImageViewerDb(ThreadSafeConnection);
863
864    impl Domain for ImageViewerDb {
865        const NAME: &str = stringify!(ImageViewerDb);
866
867        const MIGRATIONS: &[&str] = &[sql!(
868                CREATE TABLE image_viewers (
869                    workspace_id INTEGER,
870                    item_id INTEGER UNIQUE,
871
872                    image_path BLOB,
873
874                    PRIMARY KEY(workspace_id, item_id),
875                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
876                    ON DELETE CASCADE
877                ) STRICT;
878        )];
879    }
880
881    db::static_connection!(IMAGE_VIEWER, ImageViewerDb, [WorkspaceDb]);
882
883    impl ImageViewerDb {
884        query! {
885            pub async fn save_image_path(
886                item_id: ItemId,
887                workspace_id: WorkspaceId,
888                image_path: PathBuf
889            ) -> Result<()> {
890                INSERT OR REPLACE INTO image_viewers(item_id, workspace_id, image_path)
891                VALUES (?, ?, ?)
892            }
893        }
894
895        query! {
896            pub fn get_image_path(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<PathBuf>> {
897                SELECT image_path
898                FROM image_viewers
899                WHERE item_id = ? AND workspace_id = ?
900            }
901        }
902    }
903}