1use gpui::{prelude::FluentBuilder as _, *};
4use std::rc::Rc;
5
6use crate::capabilities::foundation::theme::use_theme;
7use crate::capabilities::primitives::button::{Button, ButtonSize, ButtonVariant};
8
9actions!(
10 image_viewer,
11 [
12 ImageViewerClose,
13 ImageViewerNext,
14 ImageViewerPrev,
15 ImageViewerZoomIn,
16 ImageViewerZoomOut,
17 ImageViewerResetZoom
18 ]
19);
20
21#[derive(Clone)]
22pub struct ImageItem {
23 pub src: SharedString,
24 pub alt: Option<SharedString>,
25 pub caption: Option<SharedString>,
26}
27
28impl ImageItem {
29 pub fn new(src: impl Into<SharedString>) -> Self {
30 Self {
31 src: src.into(),
32 alt: None,
33 caption: None,
34 }
35 }
36
37 pub fn alt(mut self, alt: impl Into<SharedString>) -> Self {
38 self.alt = Some(alt.into());
39 self
40 }
41
42 pub fn caption(mut self, caption: impl Into<SharedString>) -> Self {
43 self.caption = Some(caption.into());
44 self
45 }
46}
47
48#[derive(Clone, Copy, Debug, PartialEq, Default)]
49pub enum ImageViewerSize {
50 Auto,
51 #[default]
52 Contain,
53 Cover,
54 Custom(f32),
55}
56
57const MIN_ZOOM: f32 = 0.1;
58const MAX_ZOOM: f32 = 5.0;
59const ZOOM_STEP: f32 = 0.25;
60
61type CloseCallback = Rc<dyn Fn(&mut Window, &mut App)>;
62
63pub struct ImageViewerState {
64 images: Vec<ImageItem>,
65 current_index: usize,
66 zoom: f32,
67 pan_offset: Point<Pixels>,
68 _is_panning: bool,
69 _last_mouse_pos: Point<Pixels>,
70 _loading: bool,
71 show_thumbnails: bool,
72 _fit_mode: ImageViewerSize,
73}
74
75impl ImageViewerState {
76 pub fn new(images: Vec<ImageItem>) -> Self {
77 Self {
78 images,
79 current_index: 0,
80 zoom: 1.0,
81 pan_offset: point(px(0.0), px(0.0)),
82 _is_panning: false,
83 _last_mouse_pos: point(px(0.0), px(0.0)),
84 _loading: false,
85 show_thumbnails: true,
86 _fit_mode: ImageViewerSize::default(),
87 }
88 }
89
90 pub fn set_images(&mut self, images: Vec<ImageItem>, cx: &mut Context<Self>) {
91 self.images = images;
92 self.current_index = 0;
93 self.reset_view();
94 cx.notify();
95 }
96
97 pub fn go_to(&mut self, index: usize, cx: &mut Context<Self>) {
98 if index < self.images.len() {
99 self.current_index = index;
100 self.reset_view();
101 cx.notify();
102 }
103 }
104
105 pub fn next(&mut self, cx: &mut Context<Self>) {
106 if self.current_index < self.images.len().saturating_sub(1) {
107 self.current_index += 1;
108 self.reset_view();
109 cx.notify();
110 }
111 }
112
113 pub fn prev(&mut self, cx: &mut Context<Self>) {
114 if self.current_index > 0 {
115 self.current_index -= 1;
116 self.reset_view();
117 cx.notify();
118 }
119 }
120
121 pub fn zoom_in(&mut self, cx: &mut Context<Self>) {
122 self.zoom = (self.zoom + ZOOM_STEP).min(MAX_ZOOM);
123 cx.notify();
124 }
125
126 pub fn zoom_out(&mut self, cx: &mut Context<Self>) {
127 self.zoom = (self.zoom - ZOOM_STEP).max(MIN_ZOOM);
128 cx.notify();
129 }
130
131 pub fn reset_zoom(&mut self, cx: &mut Context<Self>) {
132 self.zoom = 1.0;
133 self.pan_offset = point(px(0.0), px(0.0));
134 cx.notify();
135 }
136
137 pub fn set_zoom(&mut self, zoom: f32, cx: &mut Context<Self>) {
138 self.zoom = zoom.clamp(MIN_ZOOM, MAX_ZOOM);
139 cx.notify();
140 }
141
142 pub fn toggle_thumbnails(&mut self, cx: &mut Context<Self>) {
143 self.show_thumbnails = !self.show_thumbnails;
144 cx.notify();
145 }
146
147 fn reset_view(&mut self) {
148 self.zoom = 1.0;
149 self.pan_offset = point(px(0.0), px(0.0));
150 }
151
152 pub fn current_image(&self) -> Option<&ImageItem> {
153 self.images.get(self.current_index)
154 }
155
156 pub fn has_next(&self) -> bool {
157 self.current_index < self.images.len().saturating_sub(1)
158 }
159
160 pub fn has_prev(&self) -> bool {
161 self.current_index > 0
162 }
163
164 pub fn image_count(&self) -> usize {
165 self.images.len()
166 }
167
168 pub fn current_index(&self) -> usize {
169 self.current_index
170 }
171
172 pub fn zoom(&self) -> f32 {
173 self.zoom
174 }
175
176 pub fn is_zoomed(&self) -> bool {
177 (self.zoom - 1.0).abs() > 0.01
178 }
179}
180
181pub struct ImageViewer {
182 focus_handle: FocusHandle,
183 has_focused: bool,
184 state: Entity<ImageViewerState>,
185 on_close: Option<CloseCallback>,
186 close_on_backdrop_click: bool,
187 close_on_escape: bool,
188 show_controls: bool,
189 show_counter: bool,
190 show_thumbnails: bool,
191 style: StyleRefinement,
192}
193
194impl ImageViewer {
195 pub fn new(state: Entity<ImageViewerState>, cx: &mut Context<Self>) -> Self {
196 Self {
197 focus_handle: cx.focus_handle(),
198 has_focused: false,
199 state,
200 on_close: None,
201 close_on_backdrop_click: true,
202 close_on_escape: true,
203 show_controls: true,
204 show_counter: true,
205 show_thumbnails: true,
206 style: StyleRefinement::default(),
207 }
208 }
209
210 pub fn on_close(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
211 self.on_close = Some(Rc::new(handler));
212 self
213 }
214
215 pub fn close_on_backdrop_click(mut self, close: bool) -> Self {
216 self.close_on_backdrop_click = close;
217 self
218 }
219
220 pub fn close_on_escape(mut self, close: bool) -> Self {
221 self.close_on_escape = close;
222 self
223 }
224
225 pub fn show_controls(mut self, show: bool) -> Self {
226 self.show_controls = show;
227 self
228 }
229
230 pub fn show_counter(mut self, show: bool) -> Self {
231 self.show_counter = show;
232 self
233 }
234
235 pub fn show_thumbnails(mut self, show: bool) -> Self {
236 self.show_thumbnails = show;
237 self
238 }
239
240 fn handle_close(&self, window: &mut Window, cx: &mut App) {
241 if let Some(handler) = &self.on_close {
242 (handler)(window, cx);
243 }
244 }
245}
246
247impl Styled for ImageViewer {
248 fn style(&mut self) -> &mut StyleRefinement {
249 &mut self.style
250 }
251}
252
253impl Focusable for ImageViewer {
254 fn focus_handle(&self, _: &App) -> FocusHandle {
255 self.focus_handle.clone()
256 }
257}
258
259impl EventEmitter<()> for ImageViewer {}
260
261impl Render for ImageViewer {
262 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
263 let theme = use_theme(cx);
264 let state = self.state.read(cx);
265 let current_image = state.current_image().cloned();
266 let current_index = state.current_index();
267 let image_count = state.image_count();
268 let zoom = state.zoom();
269 let has_prev = state.has_prev();
270 let has_next = state.has_next();
271 let images = state.images.clone();
272 let _pan_offset = state.pan_offset;
273 let show_thumbs = self.show_thumbnails && state.show_thumbnails && image_count > 1;
274
275 let viewer_entity = cx.entity().clone();
276 let state_entity = self.state.clone();
277
278 if !self.has_focused {
279 window.focus(&self.focus_handle);
280 self.has_focused = true;
281 }
282
283 let close_handler = self.on_close.clone();
284 let close_on_escape = self.close_on_escape;
285 let close_on_backdrop = self.close_on_backdrop_click;
286
287 div()
288 .id("image-viewer-overlay")
289 .key_context("ImageViewer")
290 .track_focus(&self.focus_handle)
291 .absolute()
292 .inset_0()
293 .flex()
294 .flex_col()
295 .bg(gpui::black().opacity(0.9))
296 .on_action({
297 let viewer_entity = viewer_entity.clone();
298 move |_: &ImageViewerClose, window, cx| {
299 if close_on_escape {
300 cx.update_entity(&viewer_entity, |viewer, cx| {
301 viewer.handle_close(window, cx);
302 });
303 }
304 }
305 })
306 .on_action({
307 let state_entity = state_entity.clone();
308 move |_: &ImageViewerNext, _, cx| {
309 cx.update_entity(&state_entity, |state, cx| state.next(cx));
310 }
311 })
312 .on_action({
313 let state_entity = state_entity.clone();
314 move |_: &ImageViewerPrev, _, cx| {
315 cx.update_entity(&state_entity, |state, cx| state.prev(cx));
316 }
317 })
318 .on_action({
319 let state_entity = state_entity.clone();
320 move |_: &ImageViewerZoomIn, _, cx| {
321 cx.update_entity(&state_entity, |state, cx| state.zoom_in(cx));
322 }
323 })
324 .on_action({
325 let state_entity = state_entity.clone();
326 move |_: &ImageViewerZoomOut, _, cx| {
327 cx.update_entity(&state_entity, |state, cx| state.zoom_out(cx));
328 }
329 })
330 .on_action({
331 let state_entity = state_entity.clone();
332 move |_: &ImageViewerResetZoom, _, cx| {
333 cx.update_entity(&state_entity, |state, cx| state.reset_zoom(cx));
334 }
335 })
336 .child(
337 div()
338 .id("image-viewer-header")
339 .flex()
340 .items_center()
341 .justify_between()
342 .px(px(16.0))
343 .py(px(12.0))
344 .child(div().flex().items_center().gap(px(8.0)).when(
345 self.show_counter && image_count > 1,
346 |this| {
347 this.child(
348 div()
349 .text_size(px(14.0))
350 .text_color(gpui::white())
351 .font_family(theme.tokens.font_family.clone())
352 .child(format!("{} of {}", current_index + 1, image_count)),
353 )
354 },
355 ))
356 .child(div().flex().items_center().gap(px(4.0)).when(
357 self.show_controls,
358 |this| {
359 let state_entity = state_entity.clone();
360 let state_entity2 = state_entity.clone();
361 let state_entity3 = state_entity.clone();
362
363 this.child(
364 Button::new("zoom-out", "")
365 .variant(ButtonVariant::Ghost)
366 .size(ButtonSize::Icon)
367 .icon("zoom-out")
368 .on_click(move |_, _, cx| {
369 cx.update_entity(&state_entity, |state, cx| {
370 state.zoom_out(cx)
371 });
372 }),
373 )
374 .child(
375 div()
376 .min_w(px(50.0))
377 .text_size(px(13.0))
378 .text_color(gpui::white())
379 .font_family(theme.tokens.font_family.clone())
380 .text_center()
381 .child(format!("{}%", (zoom * 100.0) as i32)),
382 )
383 .child(
384 Button::new("zoom-in", "")
385 .variant(ButtonVariant::Ghost)
386 .size(ButtonSize::Icon)
387 .icon("zoom-in")
388 .on_click(move |_, _, cx| {
389 cx.update_entity(&state_entity2, |state, cx| {
390 state.zoom_in(cx)
391 });
392 }),
393 )
394 .child(
395 div()
396 .w(px(1.0))
397 .h(px(20.0))
398 .bg(gpui::white().opacity(0.2))
399 .mx(px(8.0)),
400 )
401 .child(
402 Button::new("reset-zoom", "Reset")
403 .variant(ButtonVariant::Ghost)
404 .size(ButtonSize::Sm)
405 .on_click(move |_, _, cx| {
406 cx.update_entity(&state_entity3, |state, cx| {
407 state.reset_zoom(cx)
408 });
409 }),
410 )
411 },
412 ))
413 .child({
414 let viewer_entity = viewer_entity.clone();
415 Button::new("close-viewer", "")
416 .variant(ButtonVariant::Ghost)
417 .size(ButtonSize::Icon)
418 .icon("x")
419 .on_click(move |_, window, cx| {
420 cx.update_entity(&viewer_entity, |viewer, cx| {
421 viewer.handle_close(window, cx);
422 });
423 })
424 }),
425 )
426 .child(
427 div()
428 .id("image-viewer-content")
429 .flex_1()
430 .flex()
431 .items_center()
432 .justify_center()
433 .relative()
434 .overflow_hidden()
435 .when(close_on_backdrop, |this| {
436 let close_handler = close_handler.clone();
437 this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
438 if let Some(handler) = &close_handler {
439 (handler)(window, cx);
440 }
441 })
442 })
443 .when(has_prev, |this| {
444 let state_entity = state_entity.clone();
445 this.child(
446 div()
447 .id("prev-button")
448 .absolute()
449 .left(px(16.0))
450 .top_0()
451 .bottom_0()
452 .flex()
453 .items_center()
454 .child(
455 Button::new("prev-image", "")
456 .variant(ButtonVariant::Secondary)
457 .size(ButtonSize::Icon)
458 .icon("arrow-left")
459 .on_click(move |_, _, cx| {
460 cx.update_entity(&state_entity, |state, cx| {
461 state.prev(cx)
462 });
463 }),
464 ),
465 )
466 })
467 .when(has_next, |this| {
468 let state_entity = state_entity.clone();
469 this.child(
470 div()
471 .id("next-button")
472 .absolute()
473 .right(px(16.0))
474 .top_0()
475 .bottom_0()
476 .flex()
477 .items_center()
478 .child(
479 Button::new("next-image", "")
480 .variant(ButtonVariant::Secondary)
481 .size(ButtonSize::Icon)
482 .icon("arrow-right")
483 .on_click(move |_, _, cx| {
484 cx.update_entity(&state_entity, |state, cx| {
485 state.next(cx)
486 });
487 }),
488 ),
489 )
490 })
491 .when_some(current_image.clone(), |this, image| {
492 this.child(
493 div()
494 .id("image-container")
495 .flex()
496 .items_center()
497 .justify_center()
498 .on_mouse_down(MouseButton::Left, |_, _, cx| {
499 cx.stop_propagation();
500 })
501 .child(
502 img(image.src.clone())
503 .max_w(relative(0.9 * zoom))
504 .max_h(relative(0.8 * zoom))
505 .object_fit(ObjectFit::Contain),
506 ),
507 )
508 }),
509 )
510 .when_some(current_image.as_ref().and_then(|i| i.caption.clone()), {
511 |this, caption| {
512 this.child(
513 div()
514 .id("image-caption")
515 .px(px(16.0))
516 .py(px(8.0))
517 .text_size(px(14.0))
518 .text_color(gpui::white().opacity(0.8))
519 .font_family(theme.tokens.font_family.clone())
520 .text_center()
521 .child(caption),
522 )
523 }
524 })
525 .when(show_thumbs, |this| {
526 this.child(
527 div()
528 .id("thumbnail-strip")
529 .flex()
530 .items_center()
531 .justify_center()
532 .gap(px(8.0))
533 .px(px(16.0))
534 .py(px(12.0))
535 .bg(gpui::black().opacity(0.5))
536 .children(images.iter().enumerate().map(|(idx, image)| {
537 let is_current = idx == current_index;
538 let state_entity = state_entity.clone();
539
540 div()
541 .id(ElementId::Name(format!("thumb-{}", idx).into()))
542 .size(px(60.0))
543 .rounded(px(4.0))
544 .overflow_hidden()
545 .border_2()
546 .border_color(if is_current {
547 theme.tokens.primary
548 } else {
549 gpui::transparent_black()
550 })
551 .cursor(CursorStyle::PointingHand)
552 .hover(|style| style.opacity(0.8))
553 .on_mouse_down(MouseButton::Left, move |_, _window, cx| {
554 cx.stop_propagation();
555 cx.update_entity(&state_entity, |state, cx| {
556 state.go_to(idx, cx)
557 });
558 })
559 .child(
560 img(image.src.clone())
561 .size_full()
562 .object_fit(ObjectFit::Cover),
563 )
564 })),
565 )
566 })
567 }
568}
569
570pub fn init_image_viewer(cx: &mut App) {
571 if !crate::capabilities::foundation::initialization::begin(cx, "image-viewer") {
572 return;
573 }
574 cx.bind_keys([
575 KeyBinding::new("escape", ImageViewerClose, Some("ImageViewer")),
576 KeyBinding::new("left", ImageViewerPrev, Some("ImageViewer")),
577 KeyBinding::new("right", ImageViewerNext, Some("ImageViewer")),
578 KeyBinding::new("up", ImageViewerZoomIn, Some("ImageViewer")),
579 KeyBinding::new("down", ImageViewerZoomOut, Some("ImageViewer")),
580 KeyBinding::new("0", ImageViewerResetZoom, Some("ImageViewer")),
581 KeyBinding::new("+", ImageViewerZoomIn, Some("ImageViewer")),
582 KeyBinding::new("-", ImageViewerZoomOut, Some("ImageViewer")),
583 KeyBinding::new("=", ImageViewerZoomIn, Some("ImageViewer")),
584 ]);
585}