BlueGit

ict rusty-teams

Files

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

image_viewer.rs

330024a5 History
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::theme;
18use crate::image_view_math::{
19 MAX_ZOOM, Pair, View, clamp_pan, clamp_scale, counter_label, display_size,
20 fit_scale, image_origin, next_rotation, percent_label, rotated_size, step_index, step_scale,
21 thumbnail_window, toggle_target, wheel_scale, zoom_at,
22};
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(ImageFormat::Png, bytes)));
137 }
138 let bytes = std::fs::read(path).ok()?;
139 let format = clipboard_format(&bytes)?;
140 Some(ClipboardItem::new_image(&Image::from_bytes(format, bytes)))
141}
142
143fn suggested_name(path: &Path, rotated: bool) -> String {
144 let name = path
145 .file_name()
146 .map(|name| name.to_string_lossy().into_owned())
147 .unwrap_or_else(|| "image".to_owned());
148 if rotated {
149 return Path::new(&name).with_extension("png").to_string_lossy().into_owned();
150 }
151 if path.extension().is_some() {
152 return name;
153 }
154 let extension = std::fs::read(path)
155 .ok()
156 .and_then(|bytes| image::guess_format(&bytes).ok())
157 .and_then(|format| format.extensions_str().first().copied())
158 .unwrap_or("png");
159 format!("{name}.{extension}")
160}
161
162fn write_image(source: &Path, target: &Path, quarter_turns: u8) -> std::io::Result<()> {
163 if quarter_turns == 0 {
164 return std::fs::copy(source, target).map(|_| ());
165 }
166 let bytes = rotated_png(source, quarter_turns)
167 .ok_or_else(|| std::io::Error::other("rotation failed"))?;
168 std::fs::write(target, bytes)
169}
170
171fn control_button(
172 id: &'static str,
173 glyph: &'static str,
174 tooltip: &'static str,
175 enabled: bool,
176 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
177) -> Stateful<Div> {
178 div()
179 .id(id)
180 .size(px(BUTTON_SIZE))
181 .flex_none()
182 .flex()
183 .items_center()
184 .justify_center()
185 .rounded(px(BUTTON_RADIUS))
186 .text_color(white())
187 .when(enabled, |button| {
188 button
189 .cursor_pointer()
190 .hover(|button| button.bg(white().opacity(0.12)))
191 })
192 .when(!enabled, |button| button.opacity(DISABLED_OPACITY))
193 .tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx))
194 .child(symbol(glyph, BUTTON_ICON_SIZE, white()))
195 .on_click(move |event, window, cx| {
196 cx.stop_propagation();
197 if enabled {
198 on_click(event, window, cx);
199 }
200 })
201}
202
203impl ImageViewer {
204 pub fn new(
205 app: Entity<AppState>,
206 request: ViewerRequest,
207 window: &mut Window,
208 cx: &mut Context<Self>,
209 ) -> Self {
210 let focus_handle = cx.focus_handle();
211 window.focus(&focus_handle, cx);
212 let observation = cx.observe(&app, |_, _, cx| cx.notify());
213 let mut viewer = ImageViewer {
214 app,
215 conversation_id: request.conversation_id,
216 conversation_title: request.conversation_title,
217 index: request.index.min(request.items.len().saturating_sub(1)),
218 items: request.items,
219 scale: None,
220 pan: (0., 0.),
221 quarter_turns: 0,
222 rotated: None,
223 entered_fullscreen: false,
224 drag_from: None,
225 notice: None,
226 notice_serial: 0,
227 focus_handle,
228 _observation: observation,
229 };
230 cx.on_release_in(window, |this, window, _| {
231 this.release_rotated(window);
232 if this.entered_fullscreen && window.is_fullscreen() {
233 window.toggle_fullscreen();
234 }
235 })
236 .detach();
237 viewer.preload(window, cx);
238 viewer
239 }
240
241 pub fn focus_handle(&self) -> FocusHandle {
242 self.focus_handle.clone()
243 }
244
245 fn preload(&mut self, window: &Window, cx: &mut Context<Self>) {
246 let last_index = self.items.len().saturating_sub(1);
247 let visible = thumbnail_window(
248 self.index,
249 self.items.len(),
250 Self::thumbnail_capacity(window),
251 );
252 let first = visible.start.min(self.index.saturating_sub(1));
253 let last = visible.end.saturating_sub(1).max((self.index + 1).min(last_index));
254 let directory = &self.app.read(cx).directory;
255 let missing: Vec<_> = self
256 .items
257 .get(first..=last)
258 .unwrap_or_default()
259 .iter()
260 .map(|item| item.image.clone())
261 .filter(|image| directory.image(&image.url).is_none())
262 .collect();
263 if !missing.is_empty() {
264 self.app
265 .update(cx, |state, cx| state.request_images(missing, cx));
266 }
267 }
268
269 fn thumbnail_capacity(window: &Window) -> usize {
270 let width = f32::from(window.viewport_size().width);
271 ((width - 2. * SIDE_PADDING) / (THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER + THUMBNAIL_GAP))
272 .floor()
273 .max(1.) as usize
274 }
275
276 fn release_rotated(&mut self, window: &mut Window) {
277 if let Some(rotated) = self.rotated.take() {
278 window.drop_image(rotated.render).ok();
279 }
280 }
281
282 fn toggle_fullscreen(&mut self, window: &mut Window) {
283 self.entered_fullscreen = !window.is_fullscreen();
284 window.toggle_fullscreen();
285 }
286
287 fn current(&self) -> Option<&GalleryItem> {
288 self.items.get(self.index)
289 }
290
291 fn current_failed(&self, cx: &App) -> bool {
292 self.current()
293 .is_some_and(|item| self.app.read(cx).directory.image_failed(&item.image.url))
294 }
295
296 fn current_path(&self, cx: &App) -> Option<PathBuf> {
297 let item = self.current()?;
298 let entry = self.app.read(cx).directory.image(&item.image.url)?;
299 Some(entry.path.clone())
300 }
301
302 fn stage_size(window: &Window) -> Pair {
303 let viewport = window.viewport_size();
304 (
305 f32::from(viewport.width).max(1.),
306 (f32::from(viewport.height) - HEADER_HEIGHT - FOOTER_HEIGHT).max(1.),
307 )
308 }
309
310 fn layout(&self, window: &Window, cx: &App) -> Option<Layout> {
311 let item = self.current()?;
312 let entry = self.app.read(cx).directory.image(&item.image.url)?;
313 let stage = Self::stage_size(window);
314 let declared = item.image.width.zip(item.image.height);
315 let source = entry
316 .size
317 .or(declared)
318 .map_or(stage, |(width, height)| (width as f32, height as f32));
319 let source = rotated_size(source, self.quarter_turns);
320 let fit = fit_scale(source, stage);
321 let scale = self.scale.map_or(fit, |scale| clamp_scale(scale, fit));
322 let pan = clamp_pan(self.pan, display_size(source, scale), stage);
323 Some(Layout {
324 stage,
325 source,
326 fit,
327 scale,
328 pan,
329 })
330 }
331
332 fn anchor_of(position: Point<Pixels>, window: &Window) -> Pair {
333 let stage = Self::stage_size(window);
334 (
335 f32::from(position.x) - stage.0 / 2.,
336 f32::from(position.y) - HEADER_HEIGHT - stage.1 / 2.,
337 )
338 }
339
340 fn zoom_to(&mut self, wanted: f32, anchor: Pair, window: &Window, cx: &mut Context<Self>) {
341 let Some(layout) = self.layout(window, cx) else {
342 return;
343 };
344 let view = zoom_at(
345 View {
346 scale: layout.scale,
347 pan: layout.pan,
348 },
349 wanted,
350 anchor,
351 layout.source,
352 layout.stage,
353 );
354 self.scale = (view.scale > layout.fit).then_some(view.scale);
355 self.pan = view.pan;
356 cx.notify();
357 }
358
359 fn zoom_step(&mut self, direction: i32, window: &Window, cx: &mut Context<Self>) {
360 let Some(layout) = self.layout(window, cx) else {
361 return;
362 };
363 self.zoom_to(step_scale(layout.scale, direction), (0., 0.), window, cx);
364 }
365
366 fn zoom_fit(&mut self, cx: &mut Context<Self>) {
367 self.scale = None;
368 self.pan = (0., 0.);
369 cx.notify();
370 }
371
372 fn toggle_zoom(&mut self, position: Point<Pixels>, window: &Window, cx: &mut Context<Self>) {
373 let Some(layout) = self.layout(window, cx) else {
374 return;
375 };
376 let target = toggle_target(layout.scale, layout.fit);
377 self.zoom_to(target, Self::anchor_of(position, window), window, cx);
378 }
379
380 fn on_wheel(&mut self, event: &ScrollWheelEvent, window: &mut Window, cx: &mut Context<Self>) {
381 let Some(layout) = self.layout(window, cx) else {
382 return;
383 };
384 let top = f32::from(event.position.y);
385 if top < HEADER_HEIGHT || top > HEADER_HEIGHT + layout.stage.1 {
386 return;
387 }
388 let delta = event.delta.pixel_delta(px(WHEEL_LINE_HEIGHT)).y.into();
389 let anchor = Self::anchor_of(event.position, window);
390 self.zoom_to(wheel_scale(layout.scale, delta), anchor, window, cx);
391 cx.stop_propagation();
392 }
393
394 fn on_mouse_move(
395 &mut self,
396 event: &MouseMoveEvent,
397 window: &mut Window,
398 cx: &mut Context<Self>,
399 ) {
400 let Some(last) = self.drag_from else {
401 return;
402 };
403 if event.pressed_button != Some(MouseButton::Left) {
404 self.drag_from = None;
405 return;
406 }
407 let Some(layout) = self.layout(window, cx) else {
408 return;
409 };
410 let moved = (
411 layout.pan.0 + f32::from(event.position.x - last.x),
412 layout.pan.1 + f32::from(event.position.y - last.y),
413 );
414 self.pan = clamp_pan(moved, display_size(layout.source, layout.scale), layout.stage);
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_item(&path, quarter_turns) })
530 .await;
531 this.update(cx, |this, cx| match item {
532 Some(item) => {
533 cx.write_to_clipboard(item);
534 this.show_notice("Image copied", cx);
535 }
536 None => {
537 cx.write_to_clipboard(ClipboardItem::new_string(fallback.display().to_string()));
538 this.show_notice("Copied file path", cx);
539 }
540 })
541 .ok();
542 })
543 .detach();
544 }
545
546 fn save_as(&mut self, cx: &mut Context<Self>) {
547 let Some(source) = self.current_path(cx) else {
548 return;
549 };
550 if self.rotation_pending() {
551 self.show_notice("Rotating", cx);
552 return;
553 }
554 let quarter_turns = self.quarter_turns;
555 cx.spawn(async move |this, cx| {
556 let name_source = source.clone();
557 let name = cx
558 .background_spawn(async move { suggested_name(&name_source, quarter_turns != 0) })
559 .await;
560 let Ok(receiver) = this.update(cx, |_, cx| {
561 cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&name))
562 }) else {
563 return;
564 };
565 let Ok(Ok(Some(target))) = receiver.await else {
566 return;
567 };
568 let written = cx
569 .background_spawn(async move {
570 write_image(&source, &target, quarter_turns).map(|_| target)
571 })
572 .await;
573 this.update(cx, |this, cx| match written {
574 Ok(target) => {
575 let name = target
576 .file_name()
577 .map(|name| name.to_string_lossy().into_owned())
578 .unwrap_or_default();
579 this.show_notice(format!("Saved {name}"), cx)
580 }
581 Err(_) => this.show_notice("Could not save the image", cx),
582 })
583 .ok();
584 })
585 .detach();
586 }
587
588 fn forward(&mut self, cx: &mut Context<Self>) {
589 let Some(item) = self.current() else {
590 return;
591 };
592 let message_key = item.message_key.clone();
593 if self.app.read(cx).mode.read_only {
594 self.show_notice("Read-only mode: message not forwarded", cx);
595 return;
596 }
597 let conversation_id = self.conversation_id.clone();
598 self.app.update(cx, |state, cx| {
599 state.request_forward(&conversation_id, &message_key, cx)
600 });
601 }
602
603 fn open_externally(&mut self, cx: &mut Context<Self>) {
604 if let Some(path) = self.current_path(cx) {
605 cx.open_with_system(&path);
606 }
607 }
608
609 fn on_key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
610 let command = event.keystroke.modifiers.secondary();
611 match (event.keystroke.key.as_str(), command) {
612 ("escape", _) => cx.emit(ImageViewerEvent::Close),
613 ("left", false) => self.go(-1, window, cx),
614 ("right", false) => self.go(1, window, cx),
615 ("r", false) => self.rotate(window, cx),
616 ("f11", _) => self.toggle_fullscreen(window),
617 ("=" | "+", true) => self.zoom_step(1, window, cx),
618 ("-", true) => self.zoom_step(-1, window, cx),
619 ("0", true) => self.zoom_fit(cx),
620 ("c", true) => self.copy_image(cx),
621 ("s", true) => self.save_as(cx),
622 _ => {}
623 }
624 cx.stop_propagation();
625 }
626
627 fn header(&self, layout: Option<Layout>, cx: &mut Context<Self>) -> Stateful<Div> {
628 let item = self.current();
629 let author = item.map(|item| item.author.clone()).unwrap_or_default();
630 let subtitle = item
631 .map(|item| format!("{} \u{b7} {}", item.time, self.conversation_title))
632 .unwrap_or_default();
633 let sender_id = item.and_then(|item| item.sender_id.clone());
634 let can_zoom_out = layout.is_some_and(|layout| layout.scale > layout.fit);
635 let can_zoom_in = layout.is_some_and(|layout| layout.scale < MAX_ZOOM);
636 let zoom_label = layout.map(|layout| percent_label(layout.scale)).unwrap_or_default();
637 let loaded = layout.is_some();
638 h_flex()
639 .id("viewer-header")
640 .absolute()
641 .top_0()
642 .left_0()
643 .w_full()
644 .h(px(HEADER_HEIGHT))
645 .px(px(SIDE_PADDING))
646 .gap(px(12.))
647 .items_center()
648 .child(
649 h_flex()
650 .flex_1()
651 .min_w_0()
652 .gap(px(10.))
653 .items_center()
654 .child(
655 div()
656 .size(px(AVATAR_SIZE))
657 .flex_none()
658 .child(person_avatar(
659 &self.app.read(cx).directory,
660 sender_id.as_deref(),
661 &author,
662 AVATAR_SIZE,
663 )),
664 )
665 .child(
666 v_flex()
667 .flex_1()
668 .min_w_0()
669 .child(
670 div()
671 .truncate()
672 .text_size(px(14.))
673 .font_weight(FontWeight::SEMIBOLD)
674 .text_color(white())
675 .child(author),
676 )
677 .child(
678 div()
679 .truncate()
680 .text_size(px(12.))
681 .text_color(white().opacity(0.6))
682 .child(subtitle),
683 ),
684 ),
685 )
686 .child(
687 h_flex()
688 .flex_none()
689 .gap(px(2.))
690 .items_center()
691 .child(control_button(
692 "viewer-zoom-out",
693 "zoom_out",
694 "Zoom out (Ctrl -)",
695 can_zoom_out,
696 cx.listener(|this, _, window, cx| this.zoom_step(-1, window, cx)),
697 ))
698 .child(
699 div()
700 .w(px(ZOOM_LABEL_WIDTH))
701 .flex_none()
702 .text_center()
703 .text_size(px(12.))
704 .text_color(white().opacity(0.8))
705 .child(zoom_label),
706 )
707 .child(control_button(
708 "viewer-zoom-in",
709 "zoom_in",
710 "Zoom in (Ctrl +)",
711 can_zoom_in,
712 cx.listener(|this, _, window, cx| this.zoom_step(1, window, cx)),
713 ))
714 .child(control_button(
715 "viewer-rotate",
716 "rotate_right",
717 "Rotate (R)",
718 loaded,
719 cx.listener(|this, _, window, cx| this.rotate(window, cx)),
720 ))
721 .child(control_button(
722 "viewer-copy",
723 "content_copy",
724 "Copy image (Ctrl C)",
725 loaded,
726 cx.listener(|this, _, _, cx| this.copy_image(cx)),
727 ))
728 .child(control_button(
729 "viewer-save",
730 "download",
731 "Save as (Ctrl S)",
732 loaded,
733 cx.listener(|this, _, _, cx| this.save_as(cx)),
734 ))
735 .child(control_button(
736 "viewer-forward",
737 "forward",
738 "Forward",
739 true,
740 cx.listener(|this, _, _, cx| this.forward(cx)),
741 ))
742 .child(control_button(
743 "viewer-fullscreen",
744 "fullscreen",
745 "Full screen (F11)",
746 true,
747 cx.listener(|this, _, window, _| this.toggle_fullscreen(window)),
748 ))
749 .child(control_button(
750 "viewer-open",
751 "open_in_new",
752 "Open in Photos",
753 loaded,
754 cx.listener(|this, _, _, cx| this.open_externally(cx)),
755 ))
756 .child(control_button(
757 "viewer-close",
758 "close",
759 "Close (Esc)",
760 true,
761 cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close)),
762 )),
763 )
764 .on_click(|_, _, cx| cx.stop_propagation())
765 }
766
767 fn nav_button(
768 &self,
769 id: &'static str,
770 glyph: &'static str,
771 left: bool,
772 stage: Pair,
773 cx: &mut Context<Self>,
774 delta: isize,
775 ) -> Stateful<Div> {
776 let top = ((stage.1 - NAV_SIZE) / 2.).max(0.);
777 div()
778 .id(id)
779 .absolute()
780 .top(px(top))
781 .when(left, |button| button.left(px(NAV_MARGIN)))
782 .when(!left, |button| button.right(px(NAV_MARGIN)))
783 .size(px(NAV_SIZE))
784 .flex()
785 .items_center()
786 .justify_center()
787 .rounded_full()
788 .bg(white().opacity(0.1))
789 .cursor_pointer()
790 .hover(|button| button.bg(white().opacity(0.2)))
791 .child(symbol(glyph, NAV_ICON_SIZE, white()))
792 .on_click(cx.listener(move |this, _, window, cx| {
793 cx.stop_propagation();
794 this.go(delta, window, cx);
795 }))
796 }
797
798 fn picture(&self, layout: Layout, cx: &mut Context<Self>) -> AnyElement {
799 let display = display_size(layout.source, layout.scale);
800 let origin = image_origin(display, layout.stage, layout.pan);
801 let Some(item) = self.current() else {
802 return div().into_any_element();
803 };
804 let source: Option<ImageSource> = if self.quarter_turns == 0 {
805 self.app
806 .read(cx)
807 .directory
808 .image(&item.image.url)
809 .map(|entry| entry.path.clone().into())
810 } else {
811 self.rotated_render().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) => frame.child(
877 img(path)
878 .size_full()
879 .object_fit(ObjectFit::Cover),
880 ),
881 None => frame.child(symbol("image", 18., white().opacity(0.5))),
882 }),
883 )
884 .on_click(cx.listener(move |this, _, window, cx| {
885 cx.stop_propagation();
886 this.jump(index, window, cx);
887 }))
888 }
889
890 fn footer(&self, window: &Window, cx: &mut Context<Self>) -> Stateful<Div> {
891 let width = f32::from(window.viewport_size().width);
892 let range = thumbnail_window(
893 self.index,
894 self.items.len(),
895 Self::thumbnail_capacity(window),
896 );
897 let caption = self
898 .current()
899 .map(|item| item.caption.clone())
900 .unwrap_or_default();
901 let status = self
902 .notice
903 .clone()
904 .unwrap_or_else(|| counter_label(self.index, self.items.len()));
905 v_flex()
906 .id("viewer-footer")
907 .absolute()
908 .bottom_0()
909 .left_0()
910 .w_full()
911 .h(px(FOOTER_HEIGHT))
912 .pb(px(12.))
913 .gap(px(4.))
914 .items_center()
915 .justify_end()
916 .child(
917 div()
918 .w(px((width - 2. * SIDE_PADDING).clamp(0., CAPTION_MAX_WIDTH)))
919 .h(px(CAPTION_HEIGHT))
920 .flex_none()
921 .truncate()
922 .text_center()
923 .text_size(px(13.))
924 .text_color(white().opacity(0.9))
925 .child(caption),
926 )
927 .child(
928 div()
929 .h(px(STATUS_HEIGHT))
930 .flex_none()
931 .text_size(px(12.))
932 .text_color(white().opacity(0.6))
933 .child(status),
934 )
935 .child(
936 h_flex()
937 .h(px(STRIP_HEIGHT))
938 .flex_none()
939 .gap(px(THUMBNAIL_GAP))
940 .items_center()
941 .children(range.map(|index| self.thumbnail(index, cx))),
942 )
943 .on_click(|_, _, cx| cx.stop_propagation())
944 }
945}
946
947fn status_placeholder(text: &'static str) -> AnyElement {
948 v_flex()
949 .size_full()
950 .gap(px(6.))
951 .items_center()
952 .justify_center()
953 .child(symbol("image", 28., white().opacity(0.5)))
954 .child(
955 div()
956 .text_size(px(12.))
957 .text_color(white().opacity(0.6))
958 .child(text),
959 )
960 .into_any_element()
961}
962
963fn loading_placeholder() -> AnyElement {
964 status_placeholder("Loading image")
965}
966
967impl Render for ImageViewer {
968 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
969 let layout = self.layout(window, cx);
970 let stage = Self::stage_size(window);
971 let has_previous = self.index > 0;
972 let has_next = self.index + 1 < self.items.len();
973 let picture = match layout {
974 Some(layout) => self.picture(layout, cx),
975 None if self.current_failed(cx) => status_placeholder("Image unavailable"),
976 None => loading_placeholder(),
977 };
978 let header = self.header(layout, cx);
979 let footer = self.footer(window, cx);
980 div()
981 .id("image-viewer")
982 .key_context("ImageViewer")
983 .track_focus(&self.focus_handle)
984 .absolute()
985 .top_0()
986 .left_0()
987 .size_full()
988 .bg(rgba(BACKDROP))
989 .occlude()
990 .on_key_down(cx.listener(Self::on_key_down))
991 .on_scroll_wheel(cx.listener(Self::on_wheel))
992 .on_mouse_move(cx.listener(Self::on_mouse_move))
993 .on_mouse_up(
994 MouseButton::Left,
995 cx.listener(|this, _, _, cx| this.end_drag(cx)),
996 )
997 .on_mouse_up_out(
998 MouseButton::Left,
999 cx.listener(|this, _, _, cx| this.end_drag(cx)),
1000 )
1001 .on_click(cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close)))
1002 .child(
1003 div()
1004 .absolute()
1005 .top(px(HEADER_HEIGHT))
1006 .left_0()
1007 .w(px(stage.0))
1008 .h(px(stage.1))
1009 .overflow_hidden()
1010 .child(picture)
1011 .when(has_previous, |stage_element| {
1012 stage_element.child(self.nav_button(
1013 "viewer-previous",
1014 "chevron_left",
1015 true,
1016 stage,
1017 cx,
1018 -1,
1019 ))
1020 })
1021 .when(has_next, |stage_element| {
1022 stage_element.child(self.nav_button(
1023 "viewer-next",
1024 "chevron_right",
1025 false,
1026 stage,
1027 cx,
1028 1,
1029 ))
1030 }),
1031 )
1032 .child(header)
1033 .child(footer)
1034 }
1035}