BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / image_viewer.rs

image_viewer.rs

image_viewer.rs 35.0 KiB Download Raw
1use std::io::Cursor;
2use std::path::{Path, PathBuf};
3use std::sync::Arc;
4use std::time::Duration;
5
6use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
9
10use image::{Frame, ImageReader};
11
12use super::avatar::person_avatar;
13use super::shortcuts::{ZoomIn, ZoomOut, ZoomReset};
14use super::widgets::symbol;
15use crate::app_state::AppState;
16use crate::downloads;
17use crate::image_clipboard::ClipboardImage;
18use crate::image_view_gallery::{GalleryItem, ViewerRequest};
19use crate::image_view_math::{
20 MAX_ZOOM, Pair, View, clamp_pan, clamp_scale, counter_label, display_size, fit_scale,
21 image_origin, next_rotation, percent_label, rotated_size, step_index, step_scale,
22 thumbnail_window, toggle_target, wheel_scale, zoom_at,
23};
24use crate::theme;
25
26const HEADER_HEIGHT: f32 = 52.;
27const FOOTER_HEIGHT: f32 = 120.;
28const BUTTON_SIZE: f32 = 36.;
29const BUTTON_RADIUS: f32 = 8.;
30const BUTTON_ICON_SIZE: f32 = 20.;
31const NAV_ICON_SIZE: f32 = 24.;
32const ZOOM_LABEL_WIDTH: f32 = 52.;
33const NAV_SIZE: f32 = 44.;
34const NAV_MARGIN: f32 = 16.;
35const AVATAR_SIZE: f32 = 32.;
36const SIDE_PADDING: f32 = 16.;
37const THUMBNAIL_SIZE: f32 = 48.;
38const THUMBNAIL_GAP: f32 = 8.;
39const THUMBNAIL_RADIUS: f32 = 6.;
40const THUMBNAIL_BORDER: f32 = 2.;
41const CAPTION_MAX_WIDTH: f32 = 720.;
42const CAPTION_HEIGHT: f32 = 22.;
43const STATUS_HEIGHT: f32 = 18.;
44const STRIP_HEIGHT: f32 = THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER;
45const WHEEL_LINE_HEIGHT: f32 = 20.;
46const BACKDROP: u32 = 0x080809fc;
47const DISABLED_OPACITY: f32 = 0.35;
48const NOTICE_DURATION: Duration = Duration::from_secs(2);
49
50pub enum ImageViewerEvent {
51 Close,
52}
53
54struct RotatedImage {
55 url: String,
56 quarter_turns: u8,
57 render: Arc<RenderImage>,
58}
59
60#[derive(Clone, Copy)]
61struct Layout {
62 stage: Pair,
63 source: Pair,
64 fit: f32,
65 scale: f32,
66 pan: Pair,
67}
68
69pub struct ImageViewer {
70 app: Entity<AppState>,
71 conversation_id: String,
72 conversation_title: String,
73 items: Vec<GalleryItem>,
74 index: usize,
75 scale: Option<f32>,
76 pan: Pair,
77 quarter_turns: u8,
78 rotated: Option<RotatedImage>,
79 entered_fullscreen: bool,
80 drag_from: Option<Point<Pixels>>,
81 notice: Option<String>,
82 notice_serial: u64,
83 focus_handle: FocusHandle,
84 _observation: Subscription,
85}
86
87impl EventEmitter<ImageViewerEvent> for ImageViewer {}
88
89fn decode(path: &Path) -> Option<image::DynamicImage> {
90 ImageReader::open(path)
91 .ok()?
92 .with_guessed_format()
93 .ok()?
94 .decode()
95 .ok()
96}
97
98fn rotate_decoded(decoded: image::DynamicImage, quarter_turns: u8) -> image::DynamicImage {
99 match quarter_turns {
100 1 => decoded.rotate90(),
101 2 => decoded.rotate180(),
102 3 => decoded.rotate270(),
103 _ => decoded,
104 }
105}
106
107fn rotated_render(path: &Path, quarter_turns: u8) -> Option<RenderImage> {
108 let mut pixels = rotate_decoded(decode(path)?, quarter_turns).to_rgba8();
109 for pixel in pixels.chunks_exact_mut(4) {
110 pixel.swap(0, 2);
111 }
112 Some(RenderImage::new(vec![Frame::new(pixels)]))
113}
114
115fn rotated_png(path: &Path, quarter_turns: u8) -> Option<Vec<u8>> {
116 let rotated = rotate_decoded(decode(path)?, quarter_turns);
117 let mut bytes = Vec::new();
118 rotated
119 .write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png)
120 .ok()?;
121 Some(bytes)
122}
123
124fn clipboard_image(path: &Path, quarter_turns: u8) -> Option<ClipboardImage> {
125 let bytes = if quarter_turns != 0 {
126 rotated_png(path, quarter_turns)?
127 } else {
128 std::fs::read(path).ok()?
129 };
130 ClipboardImage::from_bytes(&bytes)
131}
132
133pub(super) fn suggested_name(path: &Path, rotated: bool) -> String {
134 let name = path
135 .file_name()
136 .map(|name| name.to_string_lossy().into_owned())
137 .unwrap_or_else(|| "image".to_owned());
138 if rotated {
139 return Path::new(&name)
140 .with_extension("png")
141 .to_string_lossy()
142 .into_owned();
143 }
144 if path.extension().is_some() {
145 return name;
146 }
147 let extension = std::fs::read(path)
148 .ok()
149 .and_then(|bytes| image::guess_format(&bytes).ok())
150 .and_then(|format| format.extensions_str().first().copied())
151 .unwrap_or("png");
152 format!("{name}.{extension}")
153}
154
155pub(super) fn write_image(source: &Path, target: &Path, quarter_turns: u8) -> std::io::Result<()> {
156 if quarter_turns == 0 {
157 return std::fs::copy(source, target).map(|_| ());
158 }
159 let bytes = rotated_png(source, quarter_turns)
160 .ok_or_else(|| std::io::Error::other("rotation failed"))?;
161 std::fs::write(target, bytes)
162}
163
164fn control_button(
165 id: &'static str,
166 glyph: &'static str,
167 tooltip: &'static str,
168 enabled: bool,
169 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
170) -> Stateful<Div> {
171 div()
172 .id(id)
173 .size(px(BUTTON_SIZE))
174 .flex_none()
175 .flex()
176 .items_center()
177 .justify_center()
178 .rounded(px(BUTTON_RADIUS))
179 .text_color(white())
180 .when(enabled, |button| {
181 button
182 .cursor_pointer()
183 .hover(|button| button.bg(white().opacity(0.12)))
184 })
185 .when(!enabled, |button| button.opacity(DISABLED_OPACITY))
186 .tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx))
187 .child(symbol(glyph, BUTTON_ICON_SIZE, white()))
188 .on_click(move |event, window, cx| {
189 cx.stop_propagation();
190 if enabled {
191 on_click(event, window, cx);
192 }
193 })
194}
195
196impl ImageViewer {
197 pub fn new(
198 app: Entity<AppState>,
199 request: ViewerRequest,
200 window: &mut Window,
201 cx: &mut Context<Self>,
202 ) -> Self {
203 let focus_handle = cx.focus_handle();
204 window.focus(&focus_handle, cx);
205 let observation = cx.observe(&app, |_, _, cx| cx.notify());
206 let mut viewer = ImageViewer {
207 app,
208 conversation_id: request.conversation_id,
209 conversation_title: request.conversation_title,
210 index: request.index.min(request.items.len().saturating_sub(1)),
211 items: request.items,
212 scale: None,
213 pan: (0., 0.),
214 quarter_turns: 0,
215 rotated: None,
216 entered_fullscreen: false,
217 drag_from: None,
218 notice: None,
219 notice_serial: 0,
220 focus_handle,
221 _observation: observation,
222 };
223 cx.on_release_in(window, |this, window, _| {
224 this.release_rotated(window);
225 if this.entered_fullscreen && window.is_fullscreen() {
226 window.toggle_fullscreen();
227 }
228 })
229 .detach();
230 viewer.preload(window, cx);
231 viewer
232 }
233
234 pub fn focus_handle(&self) -> FocusHandle {
235 self.focus_handle.clone()
236 }
237
238 fn preload(&mut self, window: &Window, cx: &mut Context<Self>) {
239 let last_index = self.items.len().saturating_sub(1);
240 let visible = thumbnail_window(
241 self.index,
242 self.items.len(),
243 Self::thumbnail_capacity(window),
244 );
245 let first = visible.start.min(self.index.saturating_sub(1));
246 let last = visible
247 .end
248 .saturating_sub(1)
249 .max((self.index + 1).min(last_index));
250 let directory = &self.app.read(cx).directory;
251 let missing: Vec<_> = self
252 .items
253 .get(first..=last)
254 .unwrap_or_default()
255 .iter()
256 .map(|item| item.image.clone())
257 .filter(|image| directory.image(&image.url).is_none())
258 .collect();
259 if !missing.is_empty() {
260 self.app
261 .update(cx, |state, cx| state.request_images(missing, cx));
262 }
263 }
264
265 fn thumbnail_capacity(window: &Window) -> usize {
266 let width = f32::from(window.viewport_size().width);
267 ((width - 2. * SIDE_PADDING) / (THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER + THUMBNAIL_GAP))
268 .floor()
269 .max(1.) as usize
270 }
271
272 fn release_rotated(&mut self, window: &mut Window) {
273 if let Some(rotated) = self.rotated.take() {
274 window.drop_image(rotated.render).ok();
275 }
276 }
277
278 fn toggle_fullscreen(&mut self, window: &mut Window) {
279 self.entered_fullscreen = !window.is_fullscreen();
280 window.toggle_fullscreen();
281 }
282
283 fn current(&self) -> Option<&GalleryItem> {
284 self.items.get(self.index)
285 }
286
287 fn current_failed(&self, cx: &App) -> bool {
288 self.current()
289 .is_some_and(|item| self.app.read(cx).directory.image_failed(&item.image.url))
290 }
291
292 fn current_path(&self, cx: &App) -> Option<PathBuf> {
293 let item = self.current()?;
294 let entry = self.app.read(cx).directory.image(&item.image.url)?;
295 Some(entry.path.clone())
296 }
297
298 fn stage_size(window: &Window) -> Pair {
299 let viewport = window.viewport_size();
300 (
301 f32::from(viewport.width).max(1.),
302 (f32::from(viewport.height) - HEADER_HEIGHT - FOOTER_HEIGHT).max(1.),
303 )
304 }
305
306 fn layout(&self, window: &Window, cx: &App) -> Option<Layout> {
307 let item = self.current()?;
308 let entry = self.app.read(cx).directory.image(&item.image.url)?;
309 let stage = Self::stage_size(window);
310 let declared = item.image.width.zip(item.image.height);
311 let source = entry
312 .size
313 .or(declared)
314 .map_or(stage, |(width, height)| (width as f32, height as f32));
315 let source = rotated_size(source, self.quarter_turns);
316 let fit = fit_scale(source, stage);
317 let scale = self.scale.map_or(fit, |scale| clamp_scale(scale, fit));
318 let pan = clamp_pan(self.pan, display_size(source, scale), stage);
319 Some(Layout {
320 stage,
321 source,
322 fit,
323 scale,
324 pan,
325 })
326 }
327
328 fn anchor_of(position: Point<Pixels>, window: &Window) -> Pair {
329 let stage = Self::stage_size(window);
330 (
331 f32::from(position.x) - stage.0 / 2.,
332 f32::from(position.y) - HEADER_HEIGHT - stage.1 / 2.,
333 )
334 }
335
336 fn zoom_to(&mut self, wanted: f32, anchor: Pair, window: &Window, cx: &mut Context<Self>) {
337 let Some(layout) = self.layout(window, cx) else {
338 return;
339 };
340 let view = zoom_at(
341 View {
342 scale: layout.scale,
343 pan: layout.pan,
344 },
345 wanted,
346 anchor,
347 layout.source,
348 layout.stage,
349 );
350 self.scale = (view.scale > layout.fit).then_some(view.scale);
351 self.pan = view.pan;
352 cx.notify();
353 }
354
355 fn zoom_step(&mut self, direction: i32, window: &Window, cx: &mut Context<Self>) {
356 let Some(layout) = self.layout(window, cx) else {
357 return;
358 };
359 self.zoom_to(step_scale(layout.scale, direction), (0., 0.), window, cx);
360 }
361
362 fn zoom_fit(&mut self, cx: &mut Context<Self>) {
363 self.scale = None;
364 self.pan = (0., 0.);
365 cx.notify();
366 }
367
368 fn toggle_zoom(&mut self, position: Point<Pixels>, window: &Window, cx: &mut Context<Self>) {
369 let Some(layout) = self.layout(window, cx) else {
370 return;
371 };
372 let target = toggle_target(layout.scale, layout.fit);
373 self.zoom_to(target, Self::anchor_of(position, window), window, cx);
374 }
375
376 fn on_wheel(&mut self, event: &ScrollWheelEvent, window: &mut Window, cx: &mut Context<Self>) {
377 let Some(layout) = self.layout(window, cx) else {
378 return;
379 };
380 let top = f32::from(event.position.y);
381 if top < HEADER_HEIGHT || top > HEADER_HEIGHT + layout.stage.1 {
382 return;
383 }
384 let delta = event.delta.pixel_delta(px(WHEEL_LINE_HEIGHT)).y.into();
385 let anchor = Self::anchor_of(event.position, window);
386 self.zoom_to(wheel_scale(layout.scale, delta), anchor, window, cx);
387 cx.stop_propagation();
388 }
389
390 fn on_mouse_move(
391 &mut self,
392 event: &MouseMoveEvent,
393 window: &mut Window,
394 cx: &mut Context<Self>,
395 ) {
396 let Some(last) = self.drag_from else {
397 return;
398 };
399 if event.pressed_button != Some(MouseButton::Left) {
400 self.drag_from = None;
401 return;
402 }
403 let Some(layout) = self.layout(window, cx) else {
404 return;
405 };
406 let moved = (
407 layout.pan.0 + f32::from(event.position.x - last.x),
408 layout.pan.1 + f32::from(event.position.y - last.y),
409 );
410 self.pan = clamp_pan(
411 moved,
412 display_size(layout.source, layout.scale),
413 layout.stage,
414 );
415 self.drag_from = Some(event.position);
416 cx.notify();
417 }
418
419 fn end_drag(&mut self, cx: &mut Context<Self>) {
420 if self.drag_from.take().is_some() {
421 cx.notify();
422 }
423 }
424
425 fn jump(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
426 if index == self.index || index >= self.items.len() {
427 return;
428 }
429 self.index = index;
430 self.scale = None;
431 self.pan = (0., 0.);
432 self.quarter_turns = 0;
433 self.release_rotated(window);
434 self.drag_from = None;
435 self.preload(window, cx);
436 cx.notify();
437 }
438
439 fn go(&mut self, delta: isize, window: &mut Window, cx: &mut Context<Self>) {
440 self.jump(step_index(self.index, self.items.len(), delta), window, cx);
441 }
442
443 fn rotate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
444 let (Some(path), Some(item)) = (self.current_path(cx), self.current()) else {
445 return;
446 };
447 let url = item.image.url.clone();
448 self.quarter_turns = next_rotation(self.quarter_turns);
449 self.scale = None;
450 self.pan = (0., 0.);
451 self.release_rotated(window);
452 let quarter_turns = self.quarter_turns;
453 if quarter_turns != 0 {
454 cx.spawn_in(window, async move |this, cx| {
455 let rotated = cx
456 .background_spawn(async move { rotated_render(&path, quarter_turns) })
457 .await;
458 this.update_in(cx, |this, window, cx| {
459 let still_current = this.quarter_turns == quarter_turns
460 && this.current().is_some_and(|item| item.image.url == url);
461 if !still_current {
462 return;
463 }
464 match rotated {
465 Some(render) => {
466 this.release_rotated(window);
467 this.rotated = Some(RotatedImage {
468 url,
469 quarter_turns,
470 render: Arc::new(render),
471 });
472 }
473 None => {
474 this.quarter_turns = 0;
475 this.show_notice("Could not rotate", cx);
476 }
477 }
478 cx.notify();
479 })
480 .ok();
481 })
482 .detach();
483 }
484 cx.notify();
485 }
486
487 fn show_notice(&mut self, text: impl Into<String>, cx: &mut Context<Self>) {
488 self.notice_serial += 1;
489 let serial = self.notice_serial;
490 self.notice = Some(text.into());
491 cx.spawn(async move |this, cx| {
492 cx.background_executor().timer(NOTICE_DURATION).await;
493 this.update(cx, |this, cx| {
494 if this.notice_serial == serial {
495 this.notice = None;
496 cx.notify();
497 }
498 })
499 .ok();
500 })
501 .detach();
502 cx.notify();
503 }
504
505 fn rotated_render(&self) -> Option<&Arc<RenderImage>> {
506 let url = &self.current()?.image.url;
507 self.rotated
508 .as_ref()
509 .filter(|rotated| rotated.url == *url && rotated.quarter_turns == self.quarter_turns)
510 .map(|rotated| &rotated.render)
511 }
512
513 fn rotation_pending(&self) -> bool {
514 self.quarter_turns != 0 && self.rotated_render().is_none()
515 }
516
517 fn copy_image(&mut self, cx: &mut Context<Self>) {
518 let Some(path) = self.current_path(cx) else {
519 return;
520 };
521 if self.rotation_pending() {
522 self.show_notice("Rotating", cx);
523 return;
524 }
525 let quarter_turns = self.quarter_turns;
526 cx.spawn(async move |this, cx| {
527 let fallback = path.clone();
528 let item = cx
529 .background_spawn(async move { clipboard_image(&path, quarter_turns) })
530 .await;
531 this.update(cx, |this, cx| match item {
532 Some(image) => {
533 image.write(cx);
534 this.show_notice("Image copied", cx);
535 }
536 None => {
537 cx.write_to_clipboard(ClipboardItem::new_string(
538 fallback.display().to_string(),
539 ));
540 this.show_notice("Copied file path", cx);
541 }
542 })
543 .ok();
544 })
545 .detach();
546 }
547
548 fn save_as(&mut self, cx: &mut Context<Self>) {
549 let Some(source) = self.current_path(cx) else {
550 return;
551 };
552 if self.rotation_pending() {
553 self.show_notice("Rotating", cx);
554 return;
555 }
556 let quarter_turns = self.quarter_turns;
557 cx.spawn(async move |this, cx| {
558 let name_source = source.clone();
559 let name = cx
560 .background_spawn(async move { suggested_name(&name_source, quarter_turns != 0) })
561 .await;
562 let Ok(receiver) = this.update(cx, |_, cx| {
563 cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&name))
564 }) else {
565 return;
566 };
567 let Ok(Ok(Some(target))) = receiver.await else {
568 return;
569 };
570 let written = cx
571 .background_spawn(async move {
572 write_image(&source, &target, quarter_turns).map(|_| target)
573 })
574 .await;
575 this.update(cx, |this, cx| match written {
576 Ok(target) => {
577 let name = target
578 .file_name()
579 .map(|name| name.to_string_lossy().into_owned())
580 .unwrap_or_default();
581 this.show_notice(format!("Saved {name}"), cx)
582 }
583 Err(_) => this.show_notice("Could not save the image", cx),
584 })
585 .ok();
586 })
587 .detach();
588 }
589
590 fn forward(&mut self, cx: &mut Context<Self>) {
591 let Some(item) = self.current() else {
592 return;
593 };
594 let message_key = item.message_key.clone();
595 if self.app.read(cx).mode.read_only {
596 self.show_notice("Read-only mode: message not forwarded", cx);
597 return;
598 }
599 let conversation_id = self.conversation_id.clone();
600 self.app.update(cx, |state, cx| {
601 state.request_forward(&conversation_id, &message_key, cx)
602 });
603 }
604
605 fn open_externally(&mut self, cx: &mut Context<Self>) {
606 if let Some(path) = self.current_path(cx) {
607 cx.open_with_system(&path);
608 }
609 }
610
611 fn on_key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
612 let command = event.keystroke.modifiers.secondary();
613 match (event.keystroke.key.as_str(), command) {
614 ("escape", _) => cx.emit(ImageViewerEvent::Close),
615 ("left", false) => self.go(-1, window, cx),
616 ("right", false) => self.go(1, window, cx),
617 ("r", false) => self.rotate(window, cx),
618 ("f11", _) => self.toggle_fullscreen(window),
619 ("=" | "+", true) => self.zoom_step(1, window, cx),
620 ("-", true) => self.zoom_step(-1, window, cx),
621 ("0", true) => self.zoom_fit(cx),
622 ("c", true) => self.copy_image(cx),
623 ("s", true) => self.save_as(cx),
624 _ => {}
625 }
626 cx.stop_propagation();
627 }
628
629 fn header(&self, layout: Option<Layout>, cx: &mut Context<Self>) -> Stateful<Div> {
630 let item = self.current();
631 let author = item.map(|item| item.author.clone()).unwrap_or_default();
632 let subtitle = item
633 .map(|item| format!("{} \u{b7} {}", item.time, self.conversation_title))
634 .unwrap_or_default();
635 let sender_id = item.and_then(|item| item.sender_id.clone());
636 let can_zoom_out = layout.is_some_and(|layout| layout.scale > layout.fit);
637 let can_zoom_in = layout.is_some_and(|layout| layout.scale < MAX_ZOOM);
638 let zoom_label = layout
639 .map(|layout| percent_label(layout.scale))
640 .unwrap_or_default();
641 let loaded = layout.is_some();
642 h_flex()
643 .id("viewer-header")
644 .absolute()
645 .top_0()
646 .left_0()
647 .w_full()
648 .h(px(HEADER_HEIGHT))
649 .px(px(SIDE_PADDING))
650 .gap(px(12.))
651 .items_center()
652 .child(
653 h_flex()
654 .flex_1()
655 .min_w_0()
656 .gap(px(10.))
657 .items_center()
658 .child(div().size(px(AVATAR_SIZE)).flex_none().child(person_avatar(
659 &self.app.read(cx).directory,
660 sender_id.as_deref(),
661 &author,
662 AVATAR_SIZE,
663 )))
664 .child(
665 v_flex()
666 .flex_1()
667 .min_w_0()
668 .child(
669 div()
670 .truncate()
671 .text_size(px(14.))
672 .font_weight(FontWeight::SEMIBOLD)
673 .text_color(white())
674 .child(author),
675 )
676 .child(
677 div()
678 .truncate()
679 .text_size(px(12.))
680 .text_color(white().opacity(0.6))
681 .child(subtitle),
682 ),
683 ),
684 )
685 .child(
686 h_flex()
687 .flex_none()
688 .gap(px(2.))
689 .items_center()
690 .child(control_button(
691 "viewer-zoom-out",
692 "zoom_out",
693 "Zoom out (Ctrl -)",
694 can_zoom_out,
695 cx.listener(|this, _, window, cx| this.zoom_step(-1, window, cx)),
696 ))
697 .child(
698 div()
699 .w(px(ZOOM_LABEL_WIDTH))
700 .flex_none()
701 .text_center()
702 .text_size(px(12.))
703 .text_color(white().opacity(0.8))
704 .child(zoom_label),
705 )
706 .child(control_button(
707 "viewer-zoom-in",
708 "zoom_in",
709 "Zoom in (Ctrl +)",
710 can_zoom_in,
711 cx.listener(|this, _, window, cx| this.zoom_step(1, window, cx)),
712 ))
713 .child(control_button(
714 "viewer-rotate",
715 "rotate_right",
716 "Rotate (R)",
717 loaded,
718 cx.listener(|this, _, window, cx| this.rotate(window, cx)),
719 ))
720 .child(control_button(
721 "viewer-copy",
722 "content_copy",
723 "Copy image (Ctrl C)",
724 loaded,
725 cx.listener(|this, _, _, cx| this.copy_image(cx)),
726 ))
727 .child(control_button(
728 "viewer-save",
729 "download",
730 "Save as (Ctrl S)",
731 loaded,
732 cx.listener(|this, _, _, cx| this.save_as(cx)),
733 ))
734 .child(control_button(
735 "viewer-forward",
736 "forward",
737 "Forward",
738 true,
739 cx.listener(|this, _, _, cx| this.forward(cx)),
740 ))
741 .child(control_button(
742 "viewer-fullscreen",
743 "fullscreen",
744 "Full screen (F11)",
745 true,
746 cx.listener(|this, _, window, _| this.toggle_fullscreen(window)),
747 ))
748 .child(control_button(
749 "viewer-open",
750 "open_in_new",
751 "Open in Photos",
752 loaded,
753 cx.listener(|this, _, _, cx| this.open_externally(cx)),
754 ))
755 .child(control_button(
756 "viewer-close",
757 "close",
758 "Close (Esc)",
759 true,
760 cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close)),
761 )),
762 )
763 .on_click(|_, _, cx| cx.stop_propagation())
764 }
765
766 fn nav_button(
767 &self,
768 id: &'static str,
769 glyph: &'static str,
770 left: bool,
771 stage: Pair,
772 cx: &mut Context<Self>,
773 delta: isize,
774 ) -> Stateful<Div> {
775 let top = ((stage.1 - NAV_SIZE) / 2.).max(0.);
776 div()
777 .id(id)
778 .absolute()
779 .top(px(top))
780 .when(left, |button| button.left(px(NAV_MARGIN)))
781 .when(!left, |button| button.right(px(NAV_MARGIN)))
782 .size(px(NAV_SIZE))
783 .flex()
784 .items_center()
785 .justify_center()
786 .rounded_full()
787 .bg(white().opacity(0.1))
788 .cursor_pointer()
789 .hover(|button| button.bg(white().opacity(0.2)))
790 .child(symbol(glyph, NAV_ICON_SIZE, white()))
791 .on_click(cx.listener(move |this, _, window, cx| {
792 cx.stop_propagation();
793 this.go(delta, window, cx);
794 }))
795 }
796
797 fn picture(&self, layout: Layout, cx: &mut Context<Self>) -> AnyElement {
798 let display = display_size(layout.source, layout.scale);
799 let origin = image_origin(display, layout.stage, layout.pan);
800 let Some(item) = self.current() else {
801 return div().into_any_element();
802 };
803 let source: Option<ImageSource> = if self.quarter_turns == 0 {
804 self.app
805 .read(cx)
806 .directory
807 .image(&item.image.url)
808 .map(|entry| entry.path.clone().into())
809 } else {
810 self.rotated_render()
811 .map(|render| ImageSource::Render(render.clone()))
812 };
813 let Some(source) = source else {
814 return loading_placeholder();
815 };
816 div()
817 .id("viewer-picture")
818 .absolute()
819 .left(px(origin.0))
820 .top(px(origin.1))
821 .w(px(display.0))
822 .h(px(display.1))
823 .child(img(source).size_full().object_fit(ObjectFit::Fill))
824 .on_mouse_down(
825 MouseButton::Left,
826 cx.listener(|this, event: &MouseDownEvent, _, cx| {
827 cx.stop_propagation();
828 this.drag_from = Some(event.position);
829 }),
830 )
831 .on_click(cx.listener(|this, event: &ClickEvent, window, cx| {
832 cx.stop_propagation();
833 if event.click_count() == 2 {
834 this.toggle_zoom(event.position(), window, cx);
835 }
836 }))
837 .into_any_element()
838 }
839
840 fn thumbnail(&self, index: usize, cx: &mut Context<Self>) -> Stateful<Div> {
841 let item = &self.items[index];
842 let current = index == self.index;
843 let path = self
844 .app
845 .read(cx)
846 .directory
847 .image(&item.image.url)
848 .map(|entry| entry.path.clone());
849 div()
850 .id(ElementId::Name(format!("viewer-thumbnail-{index}").into()))
851 .size(px(THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER))
852 .flex_none()
853 .flex()
854 .items_center()
855 .justify_center()
856 .rounded(px(THUMBNAIL_RADIUS + THUMBNAIL_BORDER))
857 .border_2()
858 .border_color(if current {
859 theme::accent()
860 } else {
861 transparent_black()
862 })
863 .cursor_pointer()
864 .child(
865 div()
866 .size(px(THUMBNAIL_SIZE))
867 .flex_none()
868 .flex()
869 .items_center()
870 .justify_center()
871 .overflow_hidden()
872 .rounded(px(THUMBNAIL_RADIUS))
873 .bg(white().opacity(0.08))
874 .when(!current, |frame| frame.opacity(0.7))
875 .map(|frame| match path {
876 Some(path) => {
877 frame.child(img(path).size_full().object_fit(ObjectFit::Cover))
878 }
879 None => frame.child(symbol("image", 18., white().opacity(0.5))),
880 }),
881 )
882 .on_click(cx.listener(move |this, _, window, cx| {
883 cx.stop_propagation();
884 this.jump(index, window, cx);
885 }))
886 }
887
888 fn footer(&self, window: &Window, cx: &mut Context<Self>) -> Stateful<Div> {
889 let width = f32::from(window.viewport_size().width);
890 let range = thumbnail_window(
891 self.index,
892 self.items.len(),
893 Self::thumbnail_capacity(window),
894 );
895 let caption = self
896 .current()
897 .map(|item| item.caption.clone())
898 .unwrap_or_default();
899 let status = self
900 .notice
901 .clone()
902 .unwrap_or_else(|| counter_label(self.index, self.items.len()));
903 v_flex()
904 .id("viewer-footer")
905 .absolute()
906 .bottom_0()
907 .left_0()
908 .w_full()
909 .h(px(FOOTER_HEIGHT))
910 .pb(px(12.))
911 .gap(px(4.))
912 .items_center()
913 .justify_end()
914 .child(
915 div()
916 .w(px((width - 2. * SIDE_PADDING).clamp(0., CAPTION_MAX_WIDTH)))
917 .h(px(CAPTION_HEIGHT))
918 .flex_none()
919 .truncate()
920 .text_center()
921 .text_size(px(13.))
922 .text_color(white().opacity(0.9))
923 .child(caption),
924 )
925 .child(
926 div()
927 .h(px(STATUS_HEIGHT))
928 .flex_none()
929 .text_size(px(12.))
930 .text_color(white().opacity(0.6))
931 .child(status),
932 )
933 .child(
934 h_flex()
935 .h(px(STRIP_HEIGHT))
936 .flex_none()
937 .gap(px(THUMBNAIL_GAP))
938 .items_center()
939 .children(range.map(|index| self.thumbnail(index, cx))),
940 )
941 .on_click(|_, _, cx| cx.stop_propagation())
942 }
943}
944
945fn status_placeholder(text: &'static str) -> AnyElement {
946 v_flex()
947 .size_full()
948 .gap(px(6.))
949 .items_center()
950 .justify_center()
951 .child(symbol("image", 28., white().opacity(0.5)))
952 .child(
953 div()
954 .text_size(px(12.))
955 .text_color(white().opacity(0.6))
956 .child(text),
957 )
958 .into_any_element()
959}
960
961fn loading_placeholder() -> AnyElement {
962 status_placeholder("Loading image")
963}
964
965impl Render for ImageViewer {
966 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
967 let layout = self.layout(window, cx);
968 let stage = Self::stage_size(window);
969 let has_previous = self.index > 0;
970 let has_next = self.index + 1 < self.items.len();
971 let picture = match layout {
972 Some(layout) => self.picture(layout, cx),
973 None if self.current_failed(cx) => status_placeholder("Image unavailable"),
974 None => loading_placeholder(),
975 };
976 let header = self.header(layout, cx);
977 let footer = self.footer(window, cx);
978 div()
979 .id("image-viewer")
980 .key_context("ImageViewer")
981 .track_focus(&self.focus_handle)
982 .absolute()
983 .top_0()
984 .left_0()
985 .size_full()
986 .bg(rgba(BACKDROP))
987 .occlude()
988 .on_key_down(cx.listener(Self::on_key_down))
989 .on_action(cx.listener(|this, _: &ZoomIn, window, cx| this.zoom_step(1, window, cx)))
990 .on_action(cx.listener(|this, _: &ZoomOut, window, cx| this.zoom_step(-1, window, cx)))
991 .on_action(cx.listener(|this, _: &ZoomReset, _, cx| this.zoom_fit(cx)))
992 .on_scroll_wheel(cx.listener(Self::on_wheel))
993 .on_mouse_move(cx.listener(Self::on_mouse_move))
994 .on_mouse_up(
995 MouseButton::Left,
996 cx.listener(|this, _, _, cx| this.end_drag(cx)),
997 )
998 .on_mouse_up_out(
999 MouseButton::Left,
1000 cx.listener(|this, _, _, cx| this.end_drag(cx)),
1001 )
1002 .on_click(cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close)))
1003 .child(
1004 div()
1005 .absolute()
1006 .top(px(HEADER_HEIGHT))
1007 .left_0()
1008 .w(px(stage.0))
1009 .h(px(stage.1))
1010 .overflow_hidden()
1011 .child(picture)
1012 .when(has_previous, |stage_element| {
1013 stage_element.child(self.nav_button(
1014 "viewer-previous",
1015 "chevron_left",
1016 true,
1017 stage,
1018 cx,
1019 -1,
1020 ))
1021 })
1022 .when(has_next, |stage_element| {
1023 stage_element.child(self.nav_button(
1024 "viewer-next",
1025 "chevron_right",
1026 false,
1027 stage,
1028 cx,
1029 1,
1030 ))
1031 }),
1032 )
1033 .child(header)
1034 .child(footer)
1035 }
1036}