BlueGit

ict rusty-teams

Files

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

image_viewer.rs

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