BlueGit

ict rusty-teams

Files

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

image_viewer.rs

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