BlueGit

ict rusty-teams

Files

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

image_viewer.rs

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