BlueGit

ict rusty-teams

fix(app): image viewer review findings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-11 · 7 weeks ago

Hash
2292588229bc8f9a920b3c3ffaee6ec413460947
Parent
1937648c
4 files changed +263 −88
crates/app/src/app_state.rs +11 −2
@@ -447,8 +447,17 @@ impl AppState {
447 447 changed = true;
448 448 }
449 449 None => {
450 let done = data::fetch_image(&engine, image);
451 self.on_done(done, cx, |_, _| {});
450 let done = data::fetch_image(&engine, image.clone());
451 cx.spawn(async move |this, cx| {
452 if !matches!(done.await, Ok(Ok(()))) {
453 this.update(cx, |state, cx| {
454 state.directory.mark_image_failed(&image.url);
455 cx.notify();
456 })
457 .ok();
458 }
459 })
460 .detach();
452 461 }
453 462 }
454 463 }
@@ -447,8 +447,17 @@ impl AppState {
447 changed = true;
447 changed = true;
448 }
448 }
449 None => {
449 None => {
450 let done = data::fetch_image(&engine, image);
450 let done = data::fetch_image(&engine, image.clone());
451 self.on_done(done, cx, |_, _| {});
451 cx.spawn(async move |this, cx| {
452 if !matches!(done.await, Ok(Ok(()))) {
453 this.update(cx, |state, cx| {
454 state.directory.mark_image_failed(&image.url);
455 cx.notify();
456 })
457 .ok();
458 }
459 })
460 .detach();
452 }
461 }
453 }
462 }
454 }
463 }
crates/app/src/data.rs +19 −0
@@ -133,6 +133,7 @@ pub struct Directory {
133 133 pub(crate) presence_pending: HashSet<String>,
134 134 pub(crate) images: HashMap<String, ImageEntry>,
135 135 pub(crate) images_requested: HashSet<String>,
136 pub(crate) images_failed: HashSet<String>,
136 137 }
137 138
138 139 impl Directory {
@@ -144,6 +145,14 @@ impl Directory {
144 145 self.images.get(key)
145 146 }
146 147
148 pub fn image_failed(&self, key: &str) -> bool {
149 self.images_failed.contains(key) && !self.images.contains_key(key)
150 }
151
152 pub fn mark_image_failed(&mut self, key: &str) {
153 self.images_failed.insert(key.to_owned());
154 }
155
147 156 pub fn set_image(&mut self, key: &str, path: &Path) {
148 157 let size = image::image_dimensions(path).ok();
149 158 self.images.insert(
@@ -595,6 +604,16 @@ mod tests {
595 604 assert_eq!(directory.pending_avatars().len(), 2);
596 605 }
597 606
607 #[test]
608 fn a_failed_image_is_only_failed_until_it_arrives() {
609 let mut directory = Directory::default();
610 assert!(!directory.image_failed("a"));
611 directory.mark_image_failed("a");
612 assert!(directory.image_failed("a"));
613 directory.set_image("a", Path::new("a.png"));
614 assert!(!directory.image_failed("a"));
615 }
616
598 617 #[test]
599 618 fn images_are_requested_once() {
600 619 let mut directory = Directory::default();
@@ -133,6 +133,7 @@ pub struct Directory {
133 pub(crate) presence_pending: HashSet<String>,
133 pub(crate) presence_pending: HashSet<String>,
134 pub(crate) images: HashMap<String, ImageEntry>,
134 pub(crate) images: HashMap<String, ImageEntry>,
135 pub(crate) images_requested: HashSet<String>,
135 pub(crate) images_requested: HashSet<String>,
136 pub(crate) images_failed: HashSet<String>,
136}
137}
137
138
138impl Directory {
139impl Directory {
@@ -144,6 +145,14 @@ impl Directory {
144 self.images.get(key)
145 self.images.get(key)
145 }
146 }
146
147
148 pub fn image_failed(&self, key: &str) -> bool {
149 self.images_failed.contains(key) && !self.images.contains_key(key)
150 }
151
152 pub fn mark_image_failed(&mut self, key: &str) {
153 self.images_failed.insert(key.to_owned());
154 }
155
147 pub fn set_image(&mut self, key: &str, path: &Path) {
156 pub fn set_image(&mut self, key: &str, path: &Path) {
148 let size = image::image_dimensions(path).ok();
157 let size = image::image_dimensions(path).ok();
149 self.images.insert(
158 self.images.insert(
@@ -595,6 +604,16 @@ mod tests {
595 assert_eq!(directory.pending_avatars().len(), 2);
604 assert_eq!(directory.pending_avatars().len(), 2);
596 }
605 }
597
606
607 #[test]
608 fn a_failed_image_is_only_failed_until_it_arrives() {
609 let mut directory = Directory::default();
610 assert!(!directory.image_failed("a"));
611 directory.mark_image_failed("a");
612 assert!(directory.image_failed("a"));
613 directory.set_image("a", Path::new("a.png"));
614 assert!(!directory.image_failed("a"));
615 }
616
598 #[test]
617 #[test]
599 fn images_are_requested_once() {
618 fn images_are_requested_once() {
600 let mut directory = Directory::default();
619 let mut directory = Directory::default();
crates/app/src/views/image_viewer.rs +199 −72
@@ -7,6 +7,8 @@ use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
7 7 use gpui_kit::prelude::FluentBuilder as _;
8 8 use gpui_kit::*;
9 9
10 use image::{Frame, ImageReader};
11
10 12 use super::avatar::person_avatar;
11 13 use super::widgets::symbol;
12 14 use crate::app_state::AppState;
@@ -50,7 +52,7 @@ pub enum ImageViewerEvent {
50 52 struct RotatedImage {
51 53 url: String,
52 54 quarter_turns: u8,
53 image: Arc<Image>,
55 render: Arc<RenderImage>,
54 56 }
55 57
56 58 #[derive(Clone, Copy)]
@@ -72,6 +74,7 @@ pub struct ImageViewer {
72 74 pan: Pair,
73 75 quarter_turns: u8,
74 76 rotated: Option<RotatedImage>,
77 entered_fullscreen: bool,
75 78 drag_from: Option<Point<Pixels>>,
76 79 notice: Option<String>,
77 80 notice_serial: u64,
@@ -81,19 +84,39 @@ pub struct ImageViewer {
81 84
82 85 impl EventEmitter<ImageViewerEvent> for ImageViewer {}
83 86
84 fn rotate_file(path: &Path, quarter_turns: u8) -> Option<Image> {
85 let decoded = image::open(path).ok()?;
86 let rotated = match quarter_turns {
87 fn decode(path: &Path) -> Option<image::DynamicImage> {
88 ImageReader::open(path)
89 .ok()?
90 .with_guessed_format()
91 .ok()?
92 .decode()
93 .ok()
94 }
95
96 fn rotate_decoded(decoded: image::DynamicImage, quarter_turns: u8) -> image::DynamicImage {
97 match quarter_turns {
87 98 1 => decoded.rotate90(),
88 99 2 => decoded.rotate180(),
89 100 3 => decoded.rotate270(),
90 101 _ => decoded,
91 };
102 }
103 }
104
105 fn 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
113 fn rotated_png(path: &Path, quarter_turns: u8) -> Option<Vec<u8>> {
114 let rotated = rotate_decoded(decode(path)?, quarter_turns);
92 115 let mut bytes = Vec::new();
93 116 rotated
94 117 .write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png)
95 118 .ok()?;
96 Some(Image::from_bytes(ImageFormat::Png, bytes))
119 Some(bytes)
97 120 }
98 121
99 122 fn clipboard_format(bytes: &[u8]) -> Option<ImageFormat> {
@@ -107,11 +130,24 @@ fn clipboard_format(bytes: &[u8]) -> Option<ImageFormat> {
107 130 }
108 131 }
109 132
110 fn suggested_name(path: &Path) -> String {
133 fn 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
143 fn suggested_name(path: &Path, rotated: bool) -> String {
111 144 let name = path
112 145 .file_name()
113 146 .map(|name| name.to_string_lossy().into_owned())
114 147 .unwrap_or_else(|| "image".to_owned());
148 if rotated {
149 return Path::new(&name).with_extension("png").to_string_lossy().into_owned();
150 }
115 151 if path.extension().is_some() {
116 152 return name;
117 153 }
@@ -123,6 +159,15 @@ fn suggested_name(path: &Path) -> String {
123 159 format!("{name}.{extension}")
124 160 }
125 161
162 fn 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
126 171 fn control_button(
127 172 id: &'static str,
128 173 glyph: &'static str,
@@ -175,13 +220,21 @@ impl ImageViewer {
175 220 pan: (0., 0.),
176 221 quarter_turns: 0,
177 222 rotated: None,
223 entered_fullscreen: false,
178 224 drag_from: None,
179 225 notice: None,
180 226 notice_serial: 0,
181 227 focus_handle,
182 228 _observation: observation,
183 229 };
184 viewer.preload(cx);
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);
185 238 viewer
186 239 }
187 240
@@ -189,9 +242,15 @@ impl ImageViewer {
189 242 self.focus_handle.clone()
190 243 }
191 244
192 fn preload(&mut self, cx: &mut Context<Self>) {
193 let first = self.index.saturating_sub(1);
194 let last = (self.index + 1).min(self.items.len().saturating_sub(1));
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));
195 254 let directory = &self.app.read(cx).directory;
196 255 let missing: Vec<_> = self
197 256 .items
@@ -207,10 +266,33 @@ impl ImageViewer {
207 266 }
208 267 }
209 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
210 287 fn current(&self) -> Option<&GalleryItem> {
211 288 self.items.get(self.index)
212 289 }
213 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
214 296 fn current_path(&self, cx: &App) -> Option<PathBuf> {
215 297 let item = self.current()?;
216 298 let entry = self.app.read(cx).directory.image(&item.image.url)?;
@@ -299,6 +381,10 @@ impl ImageViewer {
299 381 let Some(layout) = self.layout(window, cx) else {
300 382 return;
301 383 };
384 let top = f32::from(event.position.y);
385 if top < HEADER_HEIGHT || top > HEADER_HEIGHT + layout.stage.1 {
386 return;
387 }
302 388 let delta = event.delta.pixel_delta(px(WHEEL_LINE_HEIGHT)).y.into();
303 389 let anchor = Self::anchor_of(event.position, window);
304 390 self.zoom_to(wheel_scale(layout.scale, delta), anchor, window, cx);
@@ -336,7 +422,7 @@ impl ImageViewer {
336 422 }
337 423 }
338 424
339 fn jump(&mut self, index: usize, cx: &mut Context<Self>) {
425 fn jump(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
340 426 if index == self.index || index >= self.items.len() {
341 427 return;
342 428 }
@@ -344,17 +430,17 @@ impl ImageViewer {
344 430 self.scale = None;
345 431 self.pan = (0., 0.);
346 432 self.quarter_turns = 0;
347 self.rotated = None;
433 self.release_rotated(window);
348 434 self.drag_from = None;
349 self.preload(cx);
435 self.preload(window, cx);
350 436 cx.notify();
351 437 }
352 438
353 fn go(&mut self, delta: isize, cx: &mut Context<Self>) {
354 self.jump(step_index(self.index, self.items.len(), delta), cx);
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);
355 441 }
356 442
357 fn rotate(&mut self, cx: &mut Context<Self>) {
443 fn rotate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
358 444 let (Some(path), Some(item)) = (self.current_path(cx), self.current()) else {
359 445 return;
360 446 };
@@ -362,25 +448,34 @@ impl ImageViewer {
362 448 self.quarter_turns = next_rotation(self.quarter_turns);
363 449 self.scale = None;
364 450 self.pan = (0., 0.);
365 self.rotated = None;
451 self.release_rotated(window);
366 452 let quarter_turns = self.quarter_turns;
367 453 if quarter_turns != 0 {
368 cx.spawn(async move |this, cx| {
369 let task_url = url.clone();
454 cx.spawn_in(window, async move |this, cx| {
370 455 let rotated = cx
371 .background_spawn(async move { rotate_file(&path, quarter_turns) })
456 .background_spawn(async move { rotated_render(&path, quarter_turns) })
372 457 .await;
373 this.update(cx, |this, cx| {
458 this.update_in(cx, |this, window, cx| {
374 459 let still_current = this.quarter_turns == quarter_turns
375 && this.current().is_some_and(|item| item.image.url == task_url);
376 if let Some(image) = rotated.filter(|_| still_current) {
377 this.rotated = Some(RotatedImage {
378 url: task_url,
379 quarter_turns,
380 image: Arc::new(image),
381 });
382 cx.notify();
460 && this.current().is_some_and(|item| item.image.url == url);
461 if !still_current {
462 return;
383 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();
384 479 })
385 480 .ok();
386 481 })
@@ -407,53 +502,75 @@ impl ImageViewer {
407 502 cx.notify();
408 503 }
409 504
410 fn rotated_image(&self) -> Option<&Arc<Image>> {
505 fn rotated_render(&self) -> Option<&Arc<RenderImage>> {
411 506 let url = &self.current()?.image.url;
412 507 self.rotated
413 508 .as_ref()
414 509 .filter(|rotated| rotated.url == *url && rotated.quarter_turns == self.quarter_turns)
415 .map(|rotated| &rotated.image)
510 .map(|rotated| &rotated.render)
511 }
512
513 fn rotation_pending(&self) -> bool {
514 self.quarter_turns != 0 && self.rotated_render().is_none()
416 515 }
417 516
418 517 fn copy_image(&mut self, cx: &mut Context<Self>) {
419 518 let Some(path) = self.current_path(cx) else {
420 519 return;
421 520 };
422 let item = match self.rotated_image() {
423 Some(rotated) => Some(ClipboardItem::new_image(rotated)),
424 None => std::fs::read(&path).ok().and_then(|bytes| {
425 let format = clipboard_format(&bytes)?;
426 Some(ClipboardItem::new_image(&Image::from_bytes(format, bytes)))
427 }),
428 };
429 match item {
430 Some(item) => {
431 cx.write_to_clipboard(item);
432 self.show_notice("Image copied", cx);
433 }
434 None => {
435 cx.write_to_clipboard(ClipboardItem::new_string(path.display().to_string()));
436 self.show_notice("Copied file path", cx);
437 }
521 if self.rotation_pending() {
522 self.show_notice("Rotating", cx);
523 return;
438 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();
439 544 }
440 545
441 546 fn save_as(&mut self, cx: &mut Context<Self>) {
442 547 let Some(source) = self.current_path(cx) else {
443 548 return;
444 549 };
445 let receiver =
446 cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&suggested_name(&source)));
550 if self.rotation_pending() {
551 self.show_notice("Rotating", cx);
552 return;
553 }
554 let quarter_turns = self.quarter_turns;
447 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 };
448 565 let Ok(Ok(Some(target))) = receiver.await else {
449 566 return;
450 567 };
451 let copied = cx
568 let written = cx
452 569 .background_spawn(async move {
453 std::fs::copy(&source, &target).map(|_| target)
570 write_image(&source, &target, quarter_turns).map(|_| target)
454 571 })
455 572 .await;
456 this.update(cx, |this, cx| match copied {
573 this.update(cx, |this, cx| match written {
457 574 Ok(target) => {
458 575 let name = target
459 576 .file_name()
@@ -493,10 +610,10 @@ impl ImageViewer {
493 610 let command = event.keystroke.modifiers.secondary();
494 611 match (event.keystroke.key.as_str(), command) {
495 612 ("escape", _) => cx.emit(ImageViewerEvent::Close),
496 ("left", false) => self.go(-1, cx),
497 ("right", false) => self.go(1, cx),
498 ("r", false) => self.rotate(cx),
499 ("f11", _) => window.toggle_fullscreen(),
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),
500 617 ("=" | "+", true) => self.zoom_step(1, window, cx),
501 618 ("-", true) => self.zoom_step(-1, window, cx),
502 619 ("0", true) => self.zoom_fit(cx),
@@ -507,7 +624,7 @@ impl ImageViewer {
507 624 cx.stop_propagation();
508 625 }
509 626
510 fn header(&self, layout: Option<Layout>, cx: &mut Context<Self>) -> Div {
627 fn header(&self, layout: Option<Layout>, cx: &mut Context<Self>) -> Stateful<Div> {
511 628 let item = self.current();
512 629 let author = item.map(|item| item.author.clone()).unwrap_or_default();
513 630 let subtitle = item
@@ -519,6 +636,7 @@ impl ImageViewer {
519 636 let zoom_label = layout.map(|layout| percent_label(layout.scale)).unwrap_or_default();
520 637 let loaded = layout.is_some();
521 638 h_flex()
639 .id("viewer-header")
522 640 .absolute()
523 641 .top_0()
524 642 .left_0()
@@ -598,7 +716,7 @@ impl ImageViewer {
598 716 "rotate_right",
599 717 "Rotate (R)",
600 718 loaded,
601 cx.listener(|this, _, _, cx| this.rotate(cx)),
719 cx.listener(|this, _, window, cx| this.rotate(window, cx)),
602 720 ))
603 721 .child(control_button(
604 722 "viewer-copy",
@@ -626,7 +744,7 @@ impl ImageViewer {
626 744 "fullscreen",
627 745 "Full screen (F11)",
628 746 true,
629 cx.listener(|_, _, window, _| window.toggle_fullscreen()),
747 cx.listener(|this, _, window, _| this.toggle_fullscreen(window)),
630 748 ))
631 749 .child(control_button(
632 750 "viewer-open",
@@ -643,6 +761,7 @@ impl ImageViewer {
643 761 cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close)),
644 762 )),
645 763 )
764 .on_click(|_, _, cx| cx.stop_propagation())
646 765 }
647 766
648 767 fn nav_button(
@@ -670,9 +789,9 @@ impl ImageViewer {
670 789 .cursor_pointer()
671 790 .hover(|button| button.bg(white().opacity(0.2)))
672 791 .child(symbol(glyph, NAV_ICON_SIZE, white()))
673 .on_click(cx.listener(move |this, _, _, cx| {
792 .on_click(cx.listener(move |this, _, window, cx| {
674 793 cx.stop_propagation();
675 this.go(delta, cx);
794 this.go(delta, window, cx);
676 795 }))
677 796 }
678 797
@@ -689,7 +808,7 @@ impl ImageViewer {
689 808 .image(&item.image.url)
690 809 .map(|entry| entry.path.clone().into())
691 810 } else {
692 self.rotated_image().map(|image| ImageSource::Image(image.clone()))
811 self.rotated_render().map(|render| ImageSource::Render(render.clone()))
693 812 };
694 813 let Some(source) = source else {
695 814 return loading_placeholder();
@@ -762,18 +881,19 @@ impl ImageViewer {
762 881 None => frame.child(symbol("image", 18., white().opacity(0.5))),
763 882 }),
764 883 )
765 .on_click(cx.listener(move |this, _, _, cx| {
884 .on_click(cx.listener(move |this, _, window, cx| {
766 885 cx.stop_propagation();
767 this.jump(index, cx);
886 this.jump(index, window, cx);
768 887 }))
769 888 }
770 889
771 fn footer(&self, window: &Window, cx: &mut Context<Self>) -> Div {
890 fn footer(&self, window: &Window, cx: &mut Context<Self>) -> Stateful<Div> {
772 891 let width = f32::from(window.viewport_size().width);
773 let capacity = ((width - 2. * SIDE_PADDING) / (THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER + THUMBNAIL_GAP))
774 .floor()
775 .max(1.) as usize;
776 let range = thumbnail_window(self.index, self.items.len(), capacity);
892 let range = thumbnail_window(
893 self.index,
894 self.items.len(),
895 Self::thumbnail_capacity(window),
896 );
777 897 let caption = self
778 898 .current()
779 899 .map(|item| item.caption.clone())
@@ -783,6 +903,7 @@ impl ImageViewer {
783 903 .clone()
784 904 .unwrap_or_else(|| counter_label(self.index, self.items.len()));
785 905 v_flex()
906 .id("viewer-footer")
786 907 .absolute()
787 908 .bottom_0()
788 909 .left_0()
@@ -819,10 +940,11 @@ impl ImageViewer {
819 940 .items_center()
820 941 .children(range.map(|index| self.thumbnail(index, cx))),
821 942 )
943 .on_click(|_, _, cx| cx.stop_propagation())
822 944 }
823 945 }
824 946
825 fn loading_placeholder() -> AnyElement {
947 fn status_placeholder(text: &'static str) -> AnyElement {
826 948 v_flex()
827 949 .size_full()
828 950 .gap(px(6.))
@@ -833,11 +955,15 @@ fn loading_placeholder() -> AnyElement {
833 955 div()
834 956 .text_size(px(12.))
835 957 .text_color(white().opacity(0.6))
836 .child("Loading image"),
958 .child(text),
837 959 )
838 960 .into_any_element()
839 961 }
840 962
963 fn loading_placeholder() -> AnyElement {
964 status_placeholder("Loading image")
965 }
966
841 967 impl Render for ImageViewer {
842 968 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
843 969 let layout = self.layout(window, cx);
@@ -846,6 +972,7 @@ impl Render for ImageViewer {
846 972 let has_next = self.index + 1 < self.items.len();
847 973 let picture = match layout {
848 974 Some(layout) => self.picture(layout, cx),
975 None if self.current_failed(cx) => status_placeholder("Image unavailable"),
849 976 None => loading_placeholder(),
850 977 };
851 978 let header = self.header(layout, cx);
@@ -7,6 +7,8 @@ use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
8use gpui_kit::*;
9
9
10use image::{Frame, ImageReader};
11
10use super::avatar::person_avatar;
12use super::avatar::person_avatar;
11use super::widgets::symbol;
13use super::widgets::symbol;
12use crate::app_state::AppState;
14use crate::app_state::AppState;
@@ -50,7 +52,7 @@ pub enum ImageViewerEvent {
50struct RotatedImage {
52struct RotatedImage {
51 url: String,
53 url: String,
52 quarter_turns: u8,
54 quarter_turns: u8,
53 image: Arc<Image>,
55 render: Arc<RenderImage>,
54}
56}
55
57
56#[derive(Clone, Copy)]
58#[derive(Clone, Copy)]
@@ -72,6 +74,7 @@ pub struct ImageViewer {
72 pan: Pair,
74 pan: Pair,
73 quarter_turns: u8,
75 quarter_turns: u8,
74 rotated: Option<RotatedImage>,
76 rotated: Option<RotatedImage>,
77 entered_fullscreen: bool,
75 drag_from: Option<Point<Pixels>>,
78 drag_from: Option<Point<Pixels>>,
76 notice: Option<String>,
79 notice: Option<String>,
77 notice_serial: u64,
80 notice_serial: u64,
@@ -81,19 +84,39 @@ pub struct ImageViewer {
81
84
82impl EventEmitter<ImageViewerEvent> for ImageViewer {}
85impl EventEmitter<ImageViewerEvent> for ImageViewer {}
83
86
84fn rotate_file(path: &Path, quarter_turns: u8) -> Option<Image> {
87fn decode(path: &Path) -> Option<image::DynamicImage> {
85 let decoded = image::open(path).ok()?;
88 ImageReader::open(path)
86 let rotated = match quarter_turns {
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 {
87 1 => decoded.rotate90(),
98 1 => decoded.rotate90(),
88 2 => decoded.rotate180(),
99 2 => decoded.rotate180(),
89 3 => decoded.rotate270(),
100 3 => decoded.rotate270(),
90 _ => decoded,
101 _ => decoded,
91 };
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);
92 let mut bytes = Vec::new();
115 let mut bytes = Vec::new();
93 rotated
116 rotated
94 .write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png)
117 .write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png)
95 .ok()?;
118 .ok()?;
96 Some(Image::from_bytes(ImageFormat::Png, bytes))
119 Some(bytes)
97}
120}
98
121
99fn clipboard_format(bytes: &[u8]) -> Option<ImageFormat> {
122fn clipboard_format(bytes: &[u8]) -> Option<ImageFormat> {
@@ -107,11 +130,24 @@ fn clipboard_format(bytes: &[u8]) -> Option<ImageFormat> {
107 }
130 }
108}
131}
109
132
110fn suggested_name(path: &Path) -> String {
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 {
111 let name = path
144 let name = path
112 .file_name()
145 .file_name()
113 .map(|name| name.to_string_lossy().into_owned())
146 .map(|name| name.to_string_lossy().into_owned())
114 .unwrap_or_else(|| "image".to_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 }
115 if path.extension().is_some() {
151 if path.extension().is_some() {
116 return name;
152 return name;
117 }
153 }
@@ -123,6 +159,15 @@ fn suggested_name(path: &Path) -> String {
123 format!("{name}.{extension}")
159 format!("{name}.{extension}")
124}
160}
125
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
126fn control_button(
171fn control_button(
127 id: &'static str,
172 id: &'static str,
128 glyph: &'static str,
173 glyph: &'static str,
@@ -175,13 +220,21 @@ impl ImageViewer {
175 pan: (0., 0.),
220 pan: (0., 0.),
176 quarter_turns: 0,
221 quarter_turns: 0,
177 rotated: None,
222 rotated: None,
223 entered_fullscreen: false,
178 drag_from: None,
224 drag_from: None,
179 notice: None,
225 notice: None,
180 notice_serial: 0,
226 notice_serial: 0,
181 focus_handle,
227 focus_handle,
182 _observation: observation,
228 _observation: observation,
183 };
229 };
184 viewer.preload(cx);
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);
185 viewer
238 viewer
186 }
239 }
187
240
@@ -189,9 +242,15 @@ impl ImageViewer {
189 self.focus_handle.clone()
242 self.focus_handle.clone()
190 }
243 }
191
244
192 fn preload(&mut self, cx: &mut Context<Self>) {
245 fn preload(&mut self, window: &Window, cx: &mut Context<Self>) {
193 let first = self.index.saturating_sub(1);
246 let last_index = self.items.len().saturating_sub(1);
194 let last = (self.index + 1).min(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));
195 let directory = &self.app.read(cx).directory;
254 let directory = &self.app.read(cx).directory;
196 let missing: Vec<_> = self
255 let missing: Vec<_> = self
197 .items
256 .items
@@ -207,10 +266,33 @@ impl ImageViewer {
207 }
266 }
208 }
267 }
209
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
210 fn current(&self) -> Option<&GalleryItem> {
287 fn current(&self) -> Option<&GalleryItem> {
211 self.items.get(self.index)
288 self.items.get(self.index)
212 }
289 }
213
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
214 fn current_path(&self, cx: &App) -> Option<PathBuf> {
296 fn current_path(&self, cx: &App) -> Option<PathBuf> {
215 let item = self.current()?;
297 let item = self.current()?;
216 let entry = self.app.read(cx).directory.image(&item.image.url)?;
298 let entry = self.app.read(cx).directory.image(&item.image.url)?;
@@ -299,6 +381,10 @@ impl ImageViewer {
299 let Some(layout) = self.layout(window, cx) else {
381 let Some(layout) = self.layout(window, cx) else {
300 return;
382 return;
301 };
383 };
384 let top = f32::from(event.position.y);
385 if top < HEADER_HEIGHT || top > HEADER_HEIGHT + layout.stage.1 {
386 return;
387 }
302 let delta = event.delta.pixel_delta(px(WHEEL_LINE_HEIGHT)).y.into();
388 let delta = event.delta.pixel_delta(px(WHEEL_LINE_HEIGHT)).y.into();
303 let anchor = Self::anchor_of(event.position, window);
389 let anchor = Self::anchor_of(event.position, window);
304 self.zoom_to(wheel_scale(layout.scale, delta), anchor, window, cx);
390 self.zoom_to(wheel_scale(layout.scale, delta), anchor, window, cx);
@@ -336,7 +422,7 @@ impl ImageViewer {
336 }
422 }
337 }
423 }
338
424
339 fn jump(&mut self, index: usize, cx: &mut Context<Self>) {
425 fn jump(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
340 if index == self.index || index >= self.items.len() {
426 if index == self.index || index >= self.items.len() {
341 return;
427 return;
342 }
428 }
@@ -344,17 +430,17 @@ impl ImageViewer {
344 self.scale = None;
430 self.scale = None;
345 self.pan = (0., 0.);
431 self.pan = (0., 0.);
346 self.quarter_turns = 0;
432 self.quarter_turns = 0;
347 self.rotated = None;
433 self.release_rotated(window);
348 self.drag_from = None;
434 self.drag_from = None;
349 self.preload(cx);
435 self.preload(window, cx);
350 cx.notify();
436 cx.notify();
351 }
437 }
352
438
353 fn go(&mut self, delta: isize, cx: &mut Context<Self>) {
439 fn go(&mut self, delta: isize, window: &mut Window, cx: &mut Context<Self>) {
354 self.jump(step_index(self.index, self.items.len(), delta), cx);
440 self.jump(step_index(self.index, self.items.len(), delta), window, cx);
355 }
441 }
356
442
357 fn rotate(&mut self, cx: &mut Context<Self>) {
443 fn rotate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
358 let (Some(path), Some(item)) = (self.current_path(cx), self.current()) else {
444 let (Some(path), Some(item)) = (self.current_path(cx), self.current()) else {
359 return;
445 return;
360 };
446 };
@@ -362,25 +448,34 @@ impl ImageViewer {
362 self.quarter_turns = next_rotation(self.quarter_turns);
448 self.quarter_turns = next_rotation(self.quarter_turns);
363 self.scale = None;
449 self.scale = None;
364 self.pan = (0., 0.);
450 self.pan = (0., 0.);
365 self.rotated = None;
451 self.release_rotated(window);
366 let quarter_turns = self.quarter_turns;
452 let quarter_turns = self.quarter_turns;
367 if quarter_turns != 0 {
453 if quarter_turns != 0 {
368 cx.spawn(async move |this, cx| {
454 cx.spawn_in(window, async move |this, cx| {
369 let task_url = url.clone();
370 let rotated = cx
455 let rotated = cx
371 .background_spawn(async move { rotate_file(&path, quarter_turns) })
456 .background_spawn(async move { rotated_render(&path, quarter_turns) })
372 .await;
457 .await;
373 this.update(cx, |this, cx| {
458 this.update_in(cx, |this, window, cx| {
374 let still_current = this.quarter_turns == quarter_turns
459 let still_current = this.quarter_turns == quarter_turns
375 && this.current().is_some_and(|item| item.image.url == task_url);
460 && this.current().is_some_and(|item| item.image.url == url);
376 if let Some(image) = rotated.filter(|_| still_current) {
461 if !still_current {
377 this.rotated = Some(RotatedImage {
462 return;
378 url: task_url,
379 quarter_turns,
380 image: Arc::new(image),
381 });
382 cx.notify();
383 }
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();
384 })
479 })
385 .ok();
480 .ok();
386 })
481 })
@@ -407,53 +502,75 @@ impl ImageViewer {
407 cx.notify();
502 cx.notify();
408 }
503 }
409
504
410 fn rotated_image(&self) -> Option<&Arc<Image>> {
505 fn rotated_render(&self) -> Option<&Arc<RenderImage>> {
411 let url = &self.current()?.image.url;
506 let url = &self.current()?.image.url;
412 self.rotated
507 self.rotated
413 .as_ref()
508 .as_ref()
414 .filter(|rotated| rotated.url == *url && rotated.quarter_turns == self.quarter_turns)
509 .filter(|rotated| rotated.url == *url && rotated.quarter_turns == self.quarter_turns)
415 .map(|rotated| &rotated.image)
510 .map(|rotated| &rotated.render)
511 }
512
513 fn rotation_pending(&self) -> bool {
514 self.quarter_turns != 0 && self.rotated_render().is_none()
416 }
515 }
417
516
418 fn copy_image(&mut self, cx: &mut Context<Self>) {
517 fn copy_image(&mut self, cx: &mut Context<Self>) {
419 let Some(path) = self.current_path(cx) else {
518 let Some(path) = self.current_path(cx) else {
420 return;
519 return;
421 };
520 };
422 let item = match self.rotated_image() {
521 if self.rotation_pending() {
423 Some(rotated) => Some(ClipboardItem::new_image(rotated)),
522 self.show_notice("Rotating", cx);
424 None => std::fs::read(&path).ok().and_then(|bytes| {
523 return;
425 let format = clipboard_format(&bytes)?;
426 Some(ClipboardItem::new_image(&Image::from_bytes(format, bytes)))
427 }),
428 };
429 match item {
430 Some(item) => {
431 cx.write_to_clipboard(item);
432 self.show_notice("Image copied", cx);
433 }
434 None => {
435 cx.write_to_clipboard(ClipboardItem::new_string(path.display().to_string()));
436 self.show_notice("Copied file path", cx);
437 }
438 }
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();
439 }
544 }
440
545
441 fn save_as(&mut self, cx: &mut Context<Self>) {
546 fn save_as(&mut self, cx: &mut Context<Self>) {
442 let Some(source) = self.current_path(cx) else {
547 let Some(source) = self.current_path(cx) else {
443 return;
548 return;
444 };
549 };
445 let receiver =
550 if self.rotation_pending() {
446 cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&suggested_name(&source)));
551 self.show_notice("Rotating", cx);
552 return;
553 }
554 let quarter_turns = self.quarter_turns;
447 cx.spawn(async move |this, cx| {
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 };
448 let Ok(Ok(Some(target))) = receiver.await else {
565 let Ok(Ok(Some(target))) = receiver.await else {
449 return;
566 return;
450 };
567 };
451 let copied = cx
568 let written = cx
452 .background_spawn(async move {
569 .background_spawn(async move {
453 std::fs::copy(&source, &target).map(|_| target)
570 write_image(&source, &target, quarter_turns).map(|_| target)
454 })
571 })
455 .await;
572 .await;
456 this.update(cx, |this, cx| match copied {
573 this.update(cx, |this, cx| match written {
457 Ok(target) => {
574 Ok(target) => {
458 let name = target
575 let name = target
459 .file_name()
576 .file_name()
@@ -493,10 +610,10 @@ impl ImageViewer {
493 let command = event.keystroke.modifiers.secondary();
610 let command = event.keystroke.modifiers.secondary();
494 match (event.keystroke.key.as_str(), command) {
611 match (event.keystroke.key.as_str(), command) {
495 ("escape", _) => cx.emit(ImageViewerEvent::Close),
612 ("escape", _) => cx.emit(ImageViewerEvent::Close),
496 ("left", false) => self.go(-1, cx),
613 ("left", false) => self.go(-1, window, cx),
497 ("right", false) => self.go(1, cx),
614 ("right", false) => self.go(1, window, cx),
498 ("r", false) => self.rotate(cx),
615 ("r", false) => self.rotate(window, cx),
499 ("f11", _) => window.toggle_fullscreen(),
616 ("f11", _) => self.toggle_fullscreen(window),
500 ("=" | "+", true) => self.zoom_step(1, window, cx),
617 ("=" | "+", true) => self.zoom_step(1, window, cx),
501 ("-", true) => self.zoom_step(-1, window, cx),
618 ("-", true) => self.zoom_step(-1, window, cx),
502 ("0", true) => self.zoom_fit(cx),
619 ("0", true) => self.zoom_fit(cx),
@@ -507,7 +624,7 @@ impl ImageViewer {
507 cx.stop_propagation();
624 cx.stop_propagation();
508 }
625 }
509
626
510 fn header(&self, layout: Option<Layout>, cx: &mut Context<Self>) -> Div {
627 fn header(&self, layout: Option<Layout>, cx: &mut Context<Self>) -> Stateful<Div> {
511 let item = self.current();
628 let item = self.current();
512 let author = item.map(|item| item.author.clone()).unwrap_or_default();
629 let author = item.map(|item| item.author.clone()).unwrap_or_default();
513 let subtitle = item
630 let subtitle = item
@@ -519,6 +636,7 @@ impl ImageViewer {
519 let zoom_label = layout.map(|layout| percent_label(layout.scale)).unwrap_or_default();
636 let zoom_label = layout.map(|layout| percent_label(layout.scale)).unwrap_or_default();
520 let loaded = layout.is_some();
637 let loaded = layout.is_some();
521 h_flex()
638 h_flex()
639 .id("viewer-header")
522 .absolute()
640 .absolute()
523 .top_0()
641 .top_0()
524 .left_0()
642 .left_0()
@@ -598,7 +716,7 @@ impl ImageViewer {
598 "rotate_right",
716 "rotate_right",
599 "Rotate (R)",
717 "Rotate (R)",
600 loaded,
718 loaded,
601 cx.listener(|this, _, _, cx| this.rotate(cx)),
719 cx.listener(|this, _, window, cx| this.rotate(window, cx)),
602 ))
720 ))
603 .child(control_button(
721 .child(control_button(
604 "viewer-copy",
722 "viewer-copy",
@@ -626,7 +744,7 @@ impl ImageViewer {
626 "fullscreen",
744 "fullscreen",
627 "Full screen (F11)",
745 "Full screen (F11)",
628 true,
746 true,
629 cx.listener(|_, _, window, _| window.toggle_fullscreen()),
747 cx.listener(|this, _, window, _| this.toggle_fullscreen(window)),
630 ))
748 ))
631 .child(control_button(
749 .child(control_button(
632 "viewer-open",
750 "viewer-open",
@@ -643,6 +761,7 @@ impl ImageViewer {
643 cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close)),
761 cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close)),
644 )),
762 )),
645 )
763 )
764 .on_click(|_, _, cx| cx.stop_propagation())
646 }
765 }
647
766
648 fn nav_button(
767 fn nav_button(
@@ -670,9 +789,9 @@ impl ImageViewer {
670 .cursor_pointer()
789 .cursor_pointer()
671 .hover(|button| button.bg(white().opacity(0.2)))
790 .hover(|button| button.bg(white().opacity(0.2)))
672 .child(symbol(glyph, NAV_ICON_SIZE, white()))
791 .child(symbol(glyph, NAV_ICON_SIZE, white()))
673 .on_click(cx.listener(move |this, _, _, cx| {
792 .on_click(cx.listener(move |this, _, window, cx| {
674 cx.stop_propagation();
793 cx.stop_propagation();
675 this.go(delta, cx);
794 this.go(delta, window, cx);
676 }))
795 }))
677 }
796 }
678
797
@@ -689,7 +808,7 @@ impl ImageViewer {
689 .image(&item.image.url)
808 .image(&item.image.url)
690 .map(|entry| entry.path.clone().into())
809 .map(|entry| entry.path.clone().into())
691 } else {
810 } else {
692 self.rotated_image().map(|image| ImageSource::Image(image.clone()))
811 self.rotated_render().map(|render| ImageSource::Render(render.clone()))
693 };
812 };
694 let Some(source) = source else {
813 let Some(source) = source else {
695 return loading_placeholder();
814 return loading_placeholder();
@@ -762,18 +881,19 @@ impl ImageViewer {
762 None => frame.child(symbol("image", 18., white().opacity(0.5))),
881 None => frame.child(symbol("image", 18., white().opacity(0.5))),
763 }),
882 }),
764 )
883 )
765 .on_click(cx.listener(move |this, _, _, cx| {
884 .on_click(cx.listener(move |this, _, window, cx| {
766 cx.stop_propagation();
885 cx.stop_propagation();
767 this.jump(index, cx);
886 this.jump(index, window, cx);
768 }))
887 }))
769 }
888 }
770
889
771 fn footer(&self, window: &Window, cx: &mut Context<Self>) -> Div {
890 fn footer(&self, window: &Window, cx: &mut Context<Self>) -> Stateful<Div> {
772 let width = f32::from(window.viewport_size().width);
891 let width = f32::from(window.viewport_size().width);
773 let capacity = ((width - 2. * SIDE_PADDING) / (THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER + THUMBNAIL_GAP))
892 let range = thumbnail_window(
774 .floor()
893 self.index,
775 .max(1.) as usize;
894 self.items.len(),
776 let range = thumbnail_window(self.index, self.items.len(), capacity);
895 Self::thumbnail_capacity(window),
896 );
777 let caption = self
897 let caption = self
778 .current()
898 .current()
779 .map(|item| item.caption.clone())
899 .map(|item| item.caption.clone())
@@ -783,6 +903,7 @@ impl ImageViewer {
783 .clone()
903 .clone()
784 .unwrap_or_else(|| counter_label(self.index, self.items.len()));
904 .unwrap_or_else(|| counter_label(self.index, self.items.len()));
785 v_flex()
905 v_flex()
906 .id("viewer-footer")
786 .absolute()
907 .absolute()
787 .bottom_0()
908 .bottom_0()
788 .left_0()
909 .left_0()
@@ -819,10 +940,11 @@ impl ImageViewer {
819 .items_center()
940 .items_center()
820 .children(range.map(|index| self.thumbnail(index, cx))),
941 .children(range.map(|index| self.thumbnail(index, cx))),
821 )
942 )
943 .on_click(|_, _, cx| cx.stop_propagation())
822 }
944 }
823}
945}
824
946
825fn loading_placeholder() -> AnyElement {
947fn status_placeholder(text: &'static str) -> AnyElement {
826 v_flex()
948 v_flex()
827 .size_full()
949 .size_full()
828 .gap(px(6.))
950 .gap(px(6.))
@@ -833,11 +955,15 @@ fn loading_placeholder() -> AnyElement {
833 div()
955 div()
834 .text_size(px(12.))
956 .text_size(px(12.))
835 .text_color(white().opacity(0.6))
957 .text_color(white().opacity(0.6))
836 .child("Loading image"),
958 .child(text),
837 )
959 )
838 .into_any_element()
960 .into_any_element()
839}
961}
840
962
963fn loading_placeholder() -> AnyElement {
964 status_placeholder("Loading image")
965}
966
841impl Render for ImageViewer {
967impl Render for ImageViewer {
842 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
968 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
843 let layout = self.layout(window, cx);
969 let layout = self.layout(window, cx);
@@ -846,6 +972,7 @@ impl Render for ImageViewer {
846 let has_next = self.index + 1 < self.items.len();
972 let has_next = self.index + 1 < self.items.len();
847 let picture = match layout {
973 let picture = match layout {
848 Some(layout) => self.picture(layout, cx),
974 Some(layout) => self.picture(layout, cx),
975 None if self.current_failed(cx) => status_placeholder("Image unavailable"),
849 None => loading_placeholder(),
976 None => loading_placeholder(),
850 };
977 };
851 let header = self.header(layout, cx);
978 let header = self.header(layout, cx);
crates/app/src/views/shell.rs +34 −14
@@ -312,10 +312,11 @@ impl AppShell {
312 312 cx: &mut Context<Self>,
313 313 ) {
314 314 if self.switcher.take().is_some() {
315 window.focus(&self.focus_handle, cx);
315 self.restore_focus(window, cx);
316 316 cx.notify();
317 317 return;
318 318 }
319 self.close_image_viewer(window, cx);
319 320 let candidates = candidates_from(self.state.read(cx));
320 321 let app = self.state.clone();
321 322 let switcher = cx.new(|cx| Switcher::new(app, candidates, initial_query, window, cx));
@@ -341,7 +342,7 @@ impl AppShell {
341 342 SwitcherEvent::Close => {}
342 343 }
343 344 this.switcher = None;
344 window.focus(&this.focus_handle, cx);
345 this.restore_focus(window, cx);
345 346 cx.notify();
346 347 },
347 348 )
@@ -371,6 +372,7 @@ impl AppShell {
371 372 {
372 373 return;
373 374 }
375 self.close_image_viewer(window, cx);
374 376 self.switcher = None;
375 377 let app = self.state.clone();
376 378 let dialog = cx.new(|cx| StatusMessageDialog::new(app, window, cx));
@@ -379,7 +381,7 @@ impl AppShell {
379 381 window,
380 382 |this, _, _: &StatusMessageDialogEvent, window, cx| {
381 383 this.status_dialog = None;
382 window.focus(&this.focus_handle, cx);
384 this.restore_focus(window, cx);
383 385 cx.notify();
384 386 },
385 387 )
@@ -390,10 +392,11 @@ impl AppShell {
390 392
391 393 fn toggle_shortcuts_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
392 394 if self.shortcuts_dialog.take().is_some() {
393 window.focus(&self.focus_handle, cx);
395 self.restore_focus(window, cx);
394 396 cx.notify();
395 397 return;
396 398 }
399 self.close_image_viewer(window, cx);
397 400 self.switcher = None;
398 401 let dialog = cx.new(|cx| ShortcutsDialog::new(window, cx));
399 402 cx.subscribe_in(
@@ -401,7 +404,7 @@ impl AppShell {
401 404 window,
402 405 |this, _, _: &ShortcutsDialogEvent, window, cx| {
403 406 this.shortcuts_dialog = None;
404 window.focus(&this.focus_handle, cx);
407 this.restore_focus(window, cx);
405 408 cx.notify();
406 409 },
407 410 )
@@ -417,6 +420,7 @@ impl AppShell {
417 420 else {
418 421 return;
419 422 };
423 self.close_image_viewer(window, cx);
420 424 if let Some(card) = &self.profile_card {
421 425 card.update(cx, |card, cx| {
422 426 card.move_to(request.user_id, request.anchor, cx)
@@ -430,7 +434,7 @@ impl AppShell {
430 434 window,
431 435 |this, _, _: &ProfileCardEvent, window, cx| {
432 436 this.profile_card = None;
433 window.focus(&this.focus_handle, cx);
437 this.restore_focus(window, cx);
434 438 cx.notify();
435 439 },
436 440 )
@@ -463,6 +467,13 @@ impl AppShell {
463 467 cx.notify();
464 468 }
465 469
470 fn close_image_viewer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
471 if self.image_viewer.take().is_some() {
472 window.focus(&self.focus_handle, cx);
473 cx.notify();
474 }
475 }
476
466 477 fn restore_focus(&self, window: &mut Window, cx: &mut Context<Self>) {
467 478 match &self.image_viewer {
468 479 Some(viewer) => {
@@ -607,7 +618,8 @@ impl Render for AppShell {
607 618 .on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {
608 619 this.toggle_switcher("", window, cx);
609 620 }))
610 .on_action(cx.listener(|this, _: &NewChat, _, cx| {
621 .on_action(cx.listener(|this, _: &NewChat, window, cx| {
622 this.close_image_viewer(window, cx);
611 623 this.state.update(cx, |state, cx| state.start_new_chat(cx));
612 624 }))
613 625 .on_action(cx.listener(|this, _: &ToggleCallMute, _, cx| {
@@ -616,26 +628,33 @@ impl Render for AppShell {
616 628 .on_action(cx.listener(|this, _: &ShowShortcuts, window, cx| {
617 629 this.toggle_shortcuts_dialog(window, cx);
618 630 }))
619 .on_action(cx.listener(|this, _: &OpenActivity, _, cx| {
631 .on_action(cx.listener(|this, _: &OpenActivity, window, cx| {
632 this.close_image_viewer(window, cx);
620 633 this.sidebar.update(cx, |sidebar, cx| sidebar.show_activity(cx));
621 634 }))
622 .on_action(cx.listener(|this, _: &OpenSaved, _, cx| {
635 .on_action(cx.listener(|this, _: &OpenSaved, window, cx| {
636 this.close_image_viewer(window, cx);
623 637 this.sidebar.update(cx, |sidebar, cx| sidebar.show_saved(cx));
624 638 }))
625 .on_action(cx.listener(|this, _: &OpenChatsTab, _, cx| {
639 .on_action(cx.listener(|this, _: &OpenChatsTab, window, cx| {
640 this.close_image_viewer(window, cx);
626 641 this.sidebar.update(cx, |sidebar, cx| sidebar.show_chats(cx));
627 642 }))
628 .on_action(cx.listener(|this, _: &OpenChannelsTab, _, cx| {
643 .on_action(cx.listener(|this, _: &OpenChannelsTab, window, cx| {
644 this.close_image_viewer(window, cx);
629 645 this.sidebar.update(cx, |sidebar, cx| sidebar.show_channels(cx));
630 646 }))
631 .on_action(cx.listener(|this, _: &OpenCallsTab, _, cx| {
647 .on_action(cx.listener(|this, _: &OpenCallsTab, window, cx| {
648 this.close_image_viewer(window, cx);
632 649 this.sidebar.update(cx, |sidebar, cx| sidebar.show_calls(cx));
633 650 }))
634 .on_action(cx.listener(|this, _: &PreviousConversation, _, cx| {
651 .on_action(cx.listener(|this, _: &PreviousConversation, window, cx| {
652 this.close_image_viewer(window, cx);
635 653 this.sidebar
636 654 .update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Previous, cx));
637 655 }))
638 .on_action(cx.listener(|this, _: &NextConversation, _, cx| {
656 .on_action(cx.listener(|this, _: &NextConversation, window, cx| {
657 this.close_image_viewer(window, cx);
639 658 this.sidebar
640 659 .update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Next, cx));
641 660 }))
@@ -655,6 +674,7 @@ impl Render for AppShell {
655 674 this.state.update(cx, |state, cx| state.toggle_call_share(cx));
656 675 }))
657 676 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
677 this.close_image_viewer(window, cx);
658 678 this.conversation.update(cx, |conversation, cx| {
659 679 conversation.reply_to_hovered(window, cx)
660 680 });
@@ -312,10 +312,11 @@ impl AppShell {
312 cx: &mut Context<Self>,
312 cx: &mut Context<Self>,
313 ) {
313 ) {
314 if self.switcher.take().is_some() {
314 if self.switcher.take().is_some() {
315 window.focus(&self.focus_handle, cx);
315 self.restore_focus(window, cx);
316 cx.notify();
316 cx.notify();
317 return;
317 return;
318 }
318 }
319 self.close_image_viewer(window, cx);
319 let candidates = candidates_from(self.state.read(cx));
320 let candidates = candidates_from(self.state.read(cx));
320 let app = self.state.clone();
321 let app = self.state.clone();
321 let switcher = cx.new(|cx| Switcher::new(app, candidates, initial_query, window, cx));
322 let switcher = cx.new(|cx| Switcher::new(app, candidates, initial_query, window, cx));
@@ -341,7 +342,7 @@ impl AppShell {
341 SwitcherEvent::Close => {}
342 SwitcherEvent::Close => {}
342 }
343 }
343 this.switcher = None;
344 this.switcher = None;
344 window.focus(&this.focus_handle, cx);
345 this.restore_focus(window, cx);
345 cx.notify();
346 cx.notify();
346 },
347 },
347 )
348 )
@@ -371,6 +372,7 @@ impl AppShell {
371 {
372 {
372 return;
373 return;
373 }
374 }
375 self.close_image_viewer(window, cx);
374 self.switcher = None;
376 self.switcher = None;
375 let app = self.state.clone();
377 let app = self.state.clone();
376 let dialog = cx.new(|cx| StatusMessageDialog::new(app, window, cx));
378 let dialog = cx.new(|cx| StatusMessageDialog::new(app, window, cx));
@@ -379,7 +381,7 @@ impl AppShell {
379 window,
381 window,
380 |this, _, _: &StatusMessageDialogEvent, window, cx| {
382 |this, _, _: &StatusMessageDialogEvent, window, cx| {
381 this.status_dialog = None;
383 this.status_dialog = None;
382 window.focus(&this.focus_handle, cx);
384 this.restore_focus(window, cx);
383 cx.notify();
385 cx.notify();
384 },
386 },
385 )
387 )
@@ -390,10 +392,11 @@ impl AppShell {
390
392
391 fn toggle_shortcuts_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
393 fn toggle_shortcuts_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
392 if self.shortcuts_dialog.take().is_some() {
394 if self.shortcuts_dialog.take().is_some() {
393 window.focus(&self.focus_handle, cx);
395 self.restore_focus(window, cx);
394 cx.notify();
396 cx.notify();
395 return;
397 return;
396 }
398 }
399 self.close_image_viewer(window, cx);
397 self.switcher = None;
400 self.switcher = None;
398 let dialog = cx.new(|cx| ShortcutsDialog::new(window, cx));
401 let dialog = cx.new(|cx| ShortcutsDialog::new(window, cx));
399 cx.subscribe_in(
402 cx.subscribe_in(
@@ -401,7 +404,7 @@ impl AppShell {
401 window,
404 window,
402 |this, _, _: &ShortcutsDialogEvent, window, cx| {
405 |this, _, _: &ShortcutsDialogEvent, window, cx| {
403 this.shortcuts_dialog = None;
406 this.shortcuts_dialog = None;
404 window.focus(&this.focus_handle, cx);
407 this.restore_focus(window, cx);
405 cx.notify();
408 cx.notify();
406 },
409 },
407 )
410 )
@@ -417,6 +420,7 @@ impl AppShell {
417 else {
420 else {
418 return;
421 return;
419 };
422 };
423 self.close_image_viewer(window, cx);
420 if let Some(card) = &self.profile_card {
424 if let Some(card) = &self.profile_card {
421 card.update(cx, |card, cx| {
425 card.update(cx, |card, cx| {
422 card.move_to(request.user_id, request.anchor, cx)
426 card.move_to(request.user_id, request.anchor, cx)
@@ -430,7 +434,7 @@ impl AppShell {
430 window,
434 window,
431 |this, _, _: &ProfileCardEvent, window, cx| {
435 |this, _, _: &ProfileCardEvent, window, cx| {
432 this.profile_card = None;
436 this.profile_card = None;
433 window.focus(&this.focus_handle, cx);
437 this.restore_focus(window, cx);
434 cx.notify();
438 cx.notify();
435 },
439 },
436 )
440 )
@@ -463,6 +467,13 @@ impl AppShell {
463 cx.notify();
467 cx.notify();
464 }
468 }
465
469
470 fn close_image_viewer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
471 if self.image_viewer.take().is_some() {
472 window.focus(&self.focus_handle, cx);
473 cx.notify();
474 }
475 }
476
466 fn restore_focus(&self, window: &mut Window, cx: &mut Context<Self>) {
477 fn restore_focus(&self, window: &mut Window, cx: &mut Context<Self>) {
467 match &self.image_viewer {
478 match &self.image_viewer {
468 Some(viewer) => {
479 Some(viewer) => {
@@ -607,7 +618,8 @@ impl Render for AppShell {
607 .on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {
618 .on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {
608 this.toggle_switcher("", window, cx);
619 this.toggle_switcher("", window, cx);
609 }))
620 }))
610 .on_action(cx.listener(|this, _: &NewChat, _, cx| {
621 .on_action(cx.listener(|this, _: &NewChat, window, cx| {
622 this.close_image_viewer(window, cx);
611 this.state.update(cx, |state, cx| state.start_new_chat(cx));
623 this.state.update(cx, |state, cx| state.start_new_chat(cx));
612 }))
624 }))
613 .on_action(cx.listener(|this, _: &ToggleCallMute, _, cx| {
625 .on_action(cx.listener(|this, _: &ToggleCallMute, _, cx| {
@@ -616,26 +628,33 @@ impl Render for AppShell {
616 .on_action(cx.listener(|this, _: &ShowShortcuts, window, cx| {
628 .on_action(cx.listener(|this, _: &ShowShortcuts, window, cx| {
617 this.toggle_shortcuts_dialog(window, cx);
629 this.toggle_shortcuts_dialog(window, cx);
618 }))
630 }))
619 .on_action(cx.listener(|this, _: &OpenActivity, _, cx| {
631 .on_action(cx.listener(|this, _: &OpenActivity, window, cx| {
632 this.close_image_viewer(window, cx);
620 this.sidebar.update(cx, |sidebar, cx| sidebar.show_activity(cx));
633 this.sidebar.update(cx, |sidebar, cx| sidebar.show_activity(cx));
621 }))
634 }))
622 .on_action(cx.listener(|this, _: &OpenSaved, _, cx| {
635 .on_action(cx.listener(|this, _: &OpenSaved, window, cx| {
636 this.close_image_viewer(window, cx);
623 this.sidebar.update(cx, |sidebar, cx| sidebar.show_saved(cx));
637 this.sidebar.update(cx, |sidebar, cx| sidebar.show_saved(cx));
624 }))
638 }))
625 .on_action(cx.listener(|this, _: &OpenChatsTab, _, cx| {
639 .on_action(cx.listener(|this, _: &OpenChatsTab, window, cx| {
640 this.close_image_viewer(window, cx);
626 this.sidebar.update(cx, |sidebar, cx| sidebar.show_chats(cx));
641 this.sidebar.update(cx, |sidebar, cx| sidebar.show_chats(cx));
627 }))
642 }))
628 .on_action(cx.listener(|this, _: &OpenChannelsTab, _, cx| {
643 .on_action(cx.listener(|this, _: &OpenChannelsTab, window, cx| {
644 this.close_image_viewer(window, cx);
629 this.sidebar.update(cx, |sidebar, cx| sidebar.show_channels(cx));
645 this.sidebar.update(cx, |sidebar, cx| sidebar.show_channels(cx));
630 }))
646 }))
631 .on_action(cx.listener(|this, _: &OpenCallsTab, _, cx| {
647 .on_action(cx.listener(|this, _: &OpenCallsTab, window, cx| {
648 this.close_image_viewer(window, cx);
632 this.sidebar.update(cx, |sidebar, cx| sidebar.show_calls(cx));
649 this.sidebar.update(cx, |sidebar, cx| sidebar.show_calls(cx));
633 }))
650 }))
634 .on_action(cx.listener(|this, _: &PreviousConversation, _, cx| {
651 .on_action(cx.listener(|this, _: &PreviousConversation, window, cx| {
652 this.close_image_viewer(window, cx);
635 this.sidebar
653 this.sidebar
636 .update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Previous, cx));
654 .update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Previous, cx));
637 }))
655 }))
638 .on_action(cx.listener(|this, _: &NextConversation, _, cx| {
656 .on_action(cx.listener(|this, _: &NextConversation, window, cx| {
657 this.close_image_viewer(window, cx);
639 this.sidebar
658 this.sidebar
640 .update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Next, cx));
659 .update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Next, cx));
641 }))
660 }))
@@ -655,6 +674,7 @@ impl Render for AppShell {
655 this.state.update(cx, |state, cx| state.toggle_call_share(cx));
674 this.state.update(cx, |state, cx| state.toggle_call_share(cx));
656 }))
675 }))
657 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
676 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
677 this.close_image_viewer(window, cx);
658 this.conversation.update(cx, |conversation, cx| {
678 this.conversation.update(cx, |conversation, cx| {
659 conversation.reply_to_hovered(window, cx)
679 conversation.reply_to_hovered(window, cx)
660 });
680 });