BlueGit

ict rusty-teams

Files

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

attachments.rs

attachments.rs 22.6 KiB Download Raw
1use crate::views::image_memory::{bounded, preview};
2use std::rc::Rc;
3
4use gpui_kit::assets::IconName;
5use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
8use teams_core::{FileCard, FileKind, ImageRef, external_image_url};
9
10use super::image_menu::{ImageShare, with_image_menu};
11use super::widgets::{icon, symbol};
12use crate::data::Directory;
13use crate::downloads::{self, DownloadState};
14use crate::format;
15use crate::inline_video;
16use crate::remote_image;
17use crate::render::{Block, render_blocks, render_table, table_images};
18use crate::rows::LocalImage;
19use crate::theme;
20
21pub const IMAGE_MAX_WIDTH: f32 = 360.;
22const IMAGE_MAX_HEIGHT: f32 = 300.;
23const IMAGE_MIN_SIDE: f32 = 48.;
24const IMAGE_FALLBACK: (f32, f32) = (240., 160.);
25const IMAGE_RADIUS: f32 = 10.;
26const FILE_CARD_WIDTH: f32 = 300.;
27const FILE_BADGE_SIZE: f32 = 34.;
28const SAVE_BUTTON_SIZE: f32 = 28.;
29const SAVE_BUTTON_RADIUS: f32 = 6.;
30const SAVE_PROGRESS_HEIGHT: f32 = 2.;
31const FILE_PREVIEW_HEIGHT: f32 = FILE_CARD_WIDTH * 9. / 16.;
32const PORTRAIT_PAGE_RATIO: f32 = 1.414;
33const PLAY_BUTTON_SIZE: f32 = 40.;
34const LOCAL_IMAGE_PREFIX: &str = "../hostedContents/";
35const LOCAL_IMAGE_SUFFIX: &str = "/$value";
36
37pub type FileActivate = Rc<dyn Fn(usize, &mut App)>;
38/// Opens the image viewer, or plays the clip for a video thumbnail.
39pub type ImageOpen = Rc<dyn Fn(&ImageRef, &mut App)>;
40#[derive(Clone)]
41pub struct ImageActions {
42 pub open: ImageOpen,
43 pub share: Option<ImageShare>,
44}
45
46#[derive(Clone)]
47pub struct FileActions {
48 pub states: Vec<Option<DownloadState>>,
49 pub activate: FileActivate,
50}
51
52pub fn fit_image(size: Option<(u32, u32)>) -> (f32, f32) {
53 fit_image_within(size, IMAGE_MAX_HEIGHT)
54}
55
56fn fit_image_within(size: Option<(u32, u32)>, max_height: f32) -> (f32, f32) {
57 let Some((width, height)) = size.filter(|(width, height)| *width > 0 && *height > 0) else {
58 return IMAGE_FALLBACK;
59 };
60 let (width, height) = (width as f32, height as f32);
61 let scale = (IMAGE_MAX_WIDTH / width).min(max_height / height).min(1.);
62 (
63 (width * scale).max(IMAGE_MIN_SIDE).round(),
64 (height * scale).max(IMAGE_MIN_SIDE).round(),
65 )
66}
67
68fn declared_size(image: &ImageRef) -> Option<(u32, u32)> {
69 image.width.zip(image.height)
70}
71
72fn image_size(
73 image: &ImageRef,
74 directory: &Directory,
75 sent_preview: Option<&LocalImage>,
76) -> (f32, f32) {
77 let loaded = directory
78 .image(&image.url)
79 .and_then(|entry| entry.size)
80 .or_else(|| sent_preview.and_then(|preview| preview.size));
81 let max_height = if external_image_url(&image.url).is_some() {
82 remote_image::MAX_HEIGHT as f32
83 } else {
84 IMAGE_MAX_HEIGHT
85 };
86 fit_image_within(declared_size(image).or(loaded), max_height)
87}
88
89fn sent_preview<'a>(
90 images: &[ImageRef],
91 position: usize,
92 sent_previews: &'a [LocalImage],
93) -> Option<&'a LocalImage> {
94 if external_image_url(&images[position].url).is_some() {
95 return None;
96 }
97 let uploaded_before = images[..position]
98 .iter()
99 .filter(|image| external_image_url(&image.url).is_none())
100 .count();
101 sent_previews.get(uploaded_before)
102}
103
104fn local_image(image: &LocalImage, id: ElementId) -> Stateful<Img> {
105 img(bounded(image.image.clone()))
106 .id(id)
107 .size_full()
108 .rounded(px(IMAGE_RADIUS))
109 .object_fit(ObjectFit::Cover)
110}
111
112fn image_view(
113 image: &ImageRef,
114 id: String,
115 directory: &Directory,
116 open_image: Option<&ImageActions>,
117 sent_preview: Option<&LocalImage>,
118) -> AnyElement {
119 let (width, height) = image_size(image, directory, sent_preview);
120 let image_id = ElementId::Name(format!("{id}-image").into());
121 let clip = image.video_url().is_some();
122 let frame = div()
123 .id(ElementId::Name(id.into()))
124 .relative()
125 .w(px(width))
126 .h(px(height))
127 .max_w(relative(1.))
128 .flex_none()
129 .rounded(px(IMAGE_RADIUS))
130 .overflow_hidden();
131 let Some(entry) = directory.image(&image.url) else {
132 if let Some(sent) = sent_preview {
133 return frame.child(local_image(sent, image_id)).into_any_element();
134 }
135 if clip {
136 let (image, open_image) = (image.clone(), open_image.cloned());
137 return frame
138 .bg(theme::code_surface())
139 .cursor_pointer()
140 .child(play_badge())
141 .when_some(open_image, |frame, actions| {
142 frame.on_click(move |_, _, cx| (actions.open)(&image, cx))
143 })
144 .into_any_element();
145 }
146 return frame
147 .flex()
148 .flex_col()
149 .gap(px(6.))
150 .items_center()
151 .justify_center()
152 .bg(theme::background())
153 .child(icon(IconName::Image, 24., theme::text_muted()))
154 .child(
155 div()
156 .text_size(px(11.))
157 .text_color(theme::text_muted())
158 .child("Loading image"),
159 )
160 .into_any_element();
161 };
162 let path = entry.path.clone();
163 let share = open_image.and_then(|actions| actions.share.clone());
164 let (image, open_image) = (image.clone(), open_image.cloned());
165 let frame = frame
166 .cursor_pointer()
167 .child(
168 img(preview(entry.path.clone()))
169 .id(image_id.clone())
170 .size_full()
171 .rounded(px(IMAGE_RADIUS))
172 .object_fit(ObjectFit::Cover)
173 .when_some(sent_preview.cloned(), |remote, sent| {
174 remote.with_loading(move || {
175 local_image(&sent, image_id.clone()).into_any_element()
176 })
177 }),
178 )
179 .when(clip, |frame| frame.child(play_badge()))
180 .on_click({
181 let path = path.clone();
182 move |_, _, cx| match &open_image {
183 Some(actions) => (actions.open)(&image, cx),
184 None => cx.open_with_system(&path),
185 }
186 });
187 with_image_menu(frame, path, share).into_any_element()
188}
189
190struct KindStyle {
191 label: &'static str,
192 description: &'static str,
193 color: u32,
194}
195
196fn kind_style(kind: FileKind) -> KindStyle {
197 let (label, description, color) = match kind {
198 FileKind::Word => ("DOC", "Word document", 0x2563EB),
199 FileKind::Excel => ("XLS", "Excel spreadsheet", 0x15803D),
200 FileKind::PowerPoint => ("PPT", "PowerPoint", 0xC2410C),
201 FileKind::Pdf => ("PDF", "PDF document", 0xB91C1C),
202 FileKind::Image => ("IMG", "Image", 0x7C3AED),
203 FileKind::Video => ("VID", "Video", 0xBE185D),
204 FileKind::Archive => ("ZIP", "Archive", 0xB45309),
205 FileKind::Loop => ("", "Loop component", 0x7C3AED),
206 FileKind::Other => ("", "File", 0x525252),
207 };
208 KindStyle {
209 label,
210 description,
211 color,
212 }
213}
214
215pub fn kind_description(kind: FileKind) -> &'static str {
216 kind_style(kind).description
217}
218
219pub fn file_subtitle(card: &FileCard) -> String {
220 let description = kind_style(card.kind).description;
221 match card.size {
222 Some(size) => format!("{description} \u{b7} {}", format::file_size_label(size)),
223 None => description.to_owned(),
224 }
225}
226
227pub fn file_badge(kind: FileKind, size: f32) -> Div {
228 let style = kind_style(kind);
229 div()
230 .size(px(size))
231 .flex_none()
232 .flex()
233 .items_center()
234 .justify_center()
235 .rounded(px(7.))
236 .bg(theme::color(style.color))
237 .text_color(gpui_kit::white())
238 .text_size(px(10.5))
239 .font_weight(FontWeight::BOLD)
240 .when(style.label.is_empty(), |badge| {
241 badge.child(icon(IconName::File, 16., gpui_kit::white()))
242 })
243 .when(!style.label.is_empty(), |badge| badge.child(style.label))
244}
245
246fn local_image_view(image: &LocalImage, id: String) -> AnyElement {
247 let (width, height) = fit_image(image.size);
248 let image_id = ElementId::Name(format!("{id}-image").into());
249 div()
250 .id(ElementId::Name(id.into()))
251 .w(px(width))
252 .h(px(height))
253 .max_w(relative(1.))
254 .flex_none()
255 .rounded(px(IMAGE_RADIUS))
256 .overflow_hidden()
257 .child(local_image(image, image_id))
258 .into_any_element()
259}
260
261fn save_button(
262 state: Option<&DownloadState>,
263 id: String,
264 index: usize,
265 activate: FileActivate,
266) -> Stateful<Div> {
267 let look = downloads::button_look(state);
268 let tooltip = look.tooltip.clone();
269 let clickable = look.clickable;
270 let button = div()
271 .id(ElementId::Name(id.into()))
272 .size(px(SAVE_BUTTON_SIZE))
273 .flex_none()
274 .flex()
275 .items_center()
276 .justify_center()
277 .rounded(px(SAVE_BUTTON_RADIUS))
278 .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
279 .when(look.clickable, |button| {
280 button
281 .cursor_pointer()
282 .hover(|button| button.bg(theme::row_hover()))
283 })
284 .on_click(move |_, _, cx| {
285 cx.stop_propagation();
286 if clickable {
287 activate(index, cx);
288 }
289 });
290 match look.percent {
291 Some(percent) => button.child(
292 div()
293 .text_size(px(11.))
294 .text_color(theme::text_muted())
295 .child(downloads::percent_label(percent)),
296 ),
297 None => button.child(symbol(look.symbol, 16., theme::text_muted())),
298 }
299}
300
301fn file_preview(card: &FileCard, id: &str, directory: &Directory) -> Option<Stateful<Div>> {
302 let image = card.preview().and_then(|preview| {
303 directory
304 .image(&preview.url)
305 .map(|entry| entry.path.clone())
306 });
307 if image.is_none() && card.kind != FileKind::Video {
308 return None;
309 }
310 let frame = div()
311 .id(SharedString::from(format!("{id}-preview")))
312 .relative()
313 .w_full()
314 .h(px(FILE_PREVIEW_HEIGHT))
315 .overflow_hidden()
316 .bg(theme::code_surface());
317 let frame = match image {
318 Some(path) if card.kind.is_document() && card.kind != FileKind::PowerPoint => {
319 frame.bg(theme::white()).child(
320 img(bounded(path))
321 .w_full()
322 .h(px(FILE_CARD_WIDTH * PORTRAIT_PAGE_RATIO))
323 .object_fit(ObjectFit::Cover),
324 )
325 }
326 Some(path) => frame.child(img(bounded(path)).size_full().object_fit(match card.kind {
327 FileKind::Video | FileKind::PowerPoint => ObjectFit::Cover,
328 _ => ObjectFit::Contain,
329 })),
330 None => frame,
331 };
332 let player_key = SharedString::from(format!("{id}-player"));
333 let content_url = card.open_url.clone();
334 Some(frame.when(card.kind == FileKind::Video, |frame| {
335 let play_key = player_key.clone();
336 frame
337 .child(inline_video::slot(player_key))
338 .on_click(move |_, window, cx| {
339 if inline_video::play(play_key.clone(), &content_url, window, cx) {
340 cx.stop_propagation();
341 }
342 })
343 .child(play_badge())
344 }))
345}
346
347/// A round play button centered over a video preview.
348fn play_badge() -> Div {
349 h_flex()
350 .absolute()
351 .inset_0()
352 .items_center()
353 .justify_center()
354 .child(
355 h_flex()
356 .size(px(PLAY_BUTTON_SIZE))
357 .rounded_full()
358 .items_center()
359 .justify_center()
360 .bg(black().opacity(0.5))
361 .child(icon(IconName::Play, 18., theme::white())),
362 )
363}
364
365fn file_view(
366 card: &FileCard,
367 id: String,
368 index: usize,
369 actions: Option<&FileActions>,
370 directory: &Directory,
371) -> AnyElement {
372 let badge = file_badge(card.kind, FILE_BADGE_SIZE);
373 let url = card.open_url.clone();
374 let state = actions
375 .and_then(|actions| actions.states.get(index))
376 .and_then(Option::as_ref);
377 let progress = downloads::progress_fraction(state);
378 let button = actions
379 .filter(|_| !card.open_url.is_empty() && card.kind != FileKind::Loop)
380 .map(|actions| save_button(state, format!("{id}-save"), index, actions.activate.clone()));
381 let preview = file_preview(card, &id, directory);
382 let row = h_flex()
383 .w_full()
384 .gap(px(12.))
385 .px(px(8.))
386 .py(px(8.))
387 .items_center()
388 .child(badge)
389 .child(
390 v_flex()
391 .flex_1()
392 .min_w_0()
393 .child(
394 div()
395 .truncate()
396 .text_size(px(13.))
397 .text_color(theme::text())
398 .child(card.name.clone()),
399 )
400 .child(
401 div()
402 .truncate()
403 .text_size(px(11.))
404 .text_color(theme::text_muted())
405 .child(file_subtitle(card)),
406 ),
407 )
408 .child(icon(IconName::ExternalLink, 14., theme::text_muted()))
409 .children(button);
410 v_flex()
411 .id(ElementId::Name(id.into()))
412 .relative()
413 .overflow_hidden()
414 .w_full()
415 .max_w(px(FILE_CARD_WIDTH))
416 .rounded(px(10.))
417 .bg(theme::surface())
418 .cursor_pointer()
419 .hover(|card| card.bg(theme::row_hover()))
420 .map(|card_view| {
421 if card.kind.is_document() {
422 card_view.child(row).children(preview)
423 } else {
424 card_view.children(preview).child(row)
425 }
426 })
427 .when_some(progress, |card, fraction| {
428 card.child(
429 div()
430 .absolute()
431 .left_0()
432 .bottom_0()
433 .h(px(SAVE_PROGRESS_HEIGHT))
434 .w(relative(fraction))
435 .bg(theme::accent()),
436 )
437 })
438 .on_click(move |_, _, cx| cx.open_url(&url))
439 .into_any_element()
440}
441
442#[derive(Debug, Clone, Copy, PartialEq, Eq)]
443enum Placement {
444 Remote(usize),
445 Local(usize),
446}
447
448fn local_image_index(url: &str) -> Option<usize> {
449 url.strip_prefix(LOCAL_IMAGE_PREFIX)?
450 .strip_suffix(LOCAL_IMAGE_SUFFIX)?
451 .parse::<usize>()
452 .ok()?
453 .checked_sub(1)
454}
455
456fn placement(url: &str, images: &[ImageRef], local_count: usize) -> Option<Placement> {
457 if let Some(index) = images.iter().position(|image| image.url == url) {
458 return Some(Placement::Remote(index));
459 }
460 local_image_index(url)
461 .filter(|index| *index < local_count)
462 .map(Placement::Local)
463}
464
465fn placements(blocks: &[Block], images: &[ImageRef], local_count: usize) -> Vec<Placement> {
466 blocks
467 .iter()
468 .flat_map(|block| match block {
469 Block::Image { url } => vec![url.as_str()],
470 table => table_images(table),
471 })
472 .filter_map(|url| placement(url, images, local_count))
473 .collect()
474}
475
476fn draws_images(block: &Block) -> bool {
477 matches!(block, Block::Image { .. }) || !table_images(block).is_empty()
478}
479
480pub fn message_body(
481 blocks: &[Block],
482 images: &[ImageRef],
483 local_images: &[LocalImage],
484 sent_previews: &[LocalImage],
485 id: &str,
486 own: bool,
487 directory: &Directory,
488 open_image: Option<&ImageActions>,
489 cx: &App,
490) -> Vec<AnyElement> {
491 if !blocks.iter().any(draws_images) {
492 return vec![render_blocks(blocks, id, own, cx)];
493 }
494 let mut elements = Vec::new();
495 let mut run_start = 0;
496 let render_run = |start: usize, end: usize, elements: &mut Vec<AnyElement>| {
497 if end > start {
498 let part_id = format!("{id}-part-{start}");
499 elements.push(render_blocks(&blocks[start..end], &part_id, own, cx));
500 }
501 };
502 let placed_view = |url: &str, key: &str| -> Option<AnyElement> {
503 match placement(url, images, local_images.len())? {
504 Placement::Remote(position) => Some(image_view(
505 &images[position],
506 format!("{key}-image-{position}"),
507 directory,
508 open_image,
509 sent_preview(images, position, sent_previews),
510 )),
511 Placement::Local(position) => Some(local_image_view(
512 &local_images[position],
513 format!("{key}-local-image-{position}"),
514 )),
515 }
516 };
517 for (index, block) in blocks.iter().enumerate() {
518 if !draws_images(block) {
519 continue;
520 }
521 render_run(run_start, index, &mut elements);
522 run_start = index + 1;
523 match block {
524 Block::Image { url } => elements.extend(placed_view(url, id)),
525 Block::Table { header, rows } => {
526 let table_id = format!("{id}-table-{index}");
527 elements.push(render_table(*header, rows, &table_id, own, cx, &|url| {
528 placed_view(url, &table_id)
529 }));
530 }
531 _ => {}
532 }
533 }
534 render_run(run_start, blocks.len(), &mut elements);
535 elements
536}
537
538pub fn attachments_view(
539 blocks: &[Block],
540 images: &[ImageRef],
541 local_images: &[LocalImage],
542 sent_previews: &[LocalImage],
543 files: &[FileCard],
544 id: &str,
545 directory: &Directory,
546 file_actions: Option<&FileActions>,
547 open_image: Option<&ImageActions>,
548) -> Option<Div> {
549 let placed = placements(blocks, images, local_images.len());
550 let unplaced_images: Vec<(usize, &ImageRef)> = images
551 .iter()
552 .enumerate()
553 .filter(|(index, _)| !placed.contains(&Placement::Remote(*index)))
554 .collect();
555 let unplaced_local: Vec<(usize, &LocalImage)> = local_images
556 .iter()
557 .enumerate()
558 .filter(|(index, _)| !placed.contains(&Placement::Local(*index)))
559 .collect();
560 if unplaced_images.is_empty() && unplaced_local.is_empty() && files.is_empty() {
561 return None;
562 }
563 Some(
564 v_flex()
565 .gap(px(6.))
566 .items_start()
567 .children(unplaced_images.into_iter().map(|(index, image)| {
568 image_view(
569 image,
570 format!("{id}-image-{index}"),
571 directory,
572 open_image,
573 sent_preview(images, index, sent_previews),
574 )
575 }))
576 .children(
577 unplaced_local.into_iter().map(|(index, image)| {
578 local_image_view(image, format!("{id}-local-image-{index}"))
579 }),
580 )
581 .children(files.iter().enumerate().map(|(index, card)| {
582 file_view(
583 card,
584 format!("{id}-file-{index}"),
585 index,
586 file_actions,
587 directory,
588 )
589 })),
590 )
591}
592
593#[cfg(test)]
594mod tests {
595 use super::{
596 IMAGE_FALLBACK, Placement, file_subtitle, fit_image, fit_image_within, local_image_index,
597 placement, placements, sent_preview,
598 };
599 use crate::render::{Block, TableCell};
600 use crate::rows::LocalImage;
601 use teams_core::{FileCard, FileKind, ImageRef};
602
603 fn image_ref(url: &str) -> ImageRef {
604 ImageRef {
605 id: url.into(),
606 url: url.into(),
607 width: None,
608 height: None,
609 alt: None,
610 }
611 }
612
613 fn image_block(url: &str) -> Block {
614 Block::Image { url: url.into() }
615 }
616
617 #[test]
618 fn sent_previews_follow_the_uploaded_images_and_skip_gifs() {
619 let gif = "https://media.giphy.com/media/x/giphy.gif";
620 let images = [image_ref("hosted-a"), image_ref(gif), image_ref("hosted-b")];
621 let previews: Vec<LocalImage> = [(1, 1), (2, 2)]
622 .into_iter()
623 .map(|size| LocalImage {
624 image: std::sync::Arc::new(gpui_kit::Image::empty()),
625 size: Some(size),
626 })
627 .collect();
628 let size_at =
629 |position| sent_preview(&images, position, &previews).and_then(|preview| preview.size);
630 assert_eq!(size_at(0), Some((1, 1)));
631 assert_eq!(size_at(1), None);
632 assert_eq!(size_at(2), Some((2, 2)));
633 }
634
635 #[test]
636 fn hosted_content_urls_map_to_zero_based_local_indices() {
637 assert_eq!(local_image_index("../hostedContents/2/$value"), Some(1));
638 assert_eq!(local_image_index("../hostedContents/0/$value"), None);
639 assert_eq!(local_image_index("https://x/y"), None);
640 }
641
642 #[test]
643 fn placed_images_are_found_by_url_before_local_indices() {
644 let images = [image_ref("a"), image_ref("b")];
645 let blocks = [
646 image_block("b"),
647 image_block("../hostedContents/2/$value"),
648 image_block("../hostedContents/9/$value"),
649 image_block("missing"),
650 ];
651 assert_eq!(
652 placements(&blocks, &images, 2),
653 vec![Placement::Remote(1), Placement::Local(1)]
654 );
655 assert_eq!(placement("a", &images, 0), Some(Placement::Remote(0)));
656 }
657
658 #[test]
659 fn an_image_in_a_table_cell_counts_as_placed() {
660 let images = [image_ref("a"), image_ref("b")];
661 let table = Block::Table {
662 header: false,
663 rows: vec![vec![TableCell {
664 inline: Default::default(),
665 images: vec!["b".into()],
666 }]],
667 };
668 assert_eq!(placements(&[table], &images, 0), vec![Placement::Remote(1)]);
669 }
670
671 #[test]
672 fn wide_images_shrink_to_the_max_width_keeping_aspect() {
673 assert_eq!(fit_image(Some((720, 360))), (360., 180.));
674 }
675
676 #[test]
677 fn gifs_and_stickers_are_capped_at_250_high() {
678 assert_eq!(fit_image_within(Some((300, 500)), 250.), (150., 250.));
679 }
680
681 #[test]
682 fn tall_images_shrink_to_the_max_height() {
683 assert_eq!(fit_image(Some((300, 600))), (150., 300.));
684 }
685
686 #[test]
687 fn small_images_keep_their_size() {
688 assert_eq!(fit_image(Some((200, 100))), (200., 100.));
689 }
690
691 #[test]
692 fn unknown_or_empty_sizes_use_the_fallback() {
693 assert_eq!(fit_image(None), IMAGE_FALLBACK);
694 assert_eq!(fit_image(Some((0, 10))), IMAGE_FALLBACK);
695 }
696
697 #[test]
698 fn thin_images_keep_a_clickable_side() {
699 assert_eq!(fit_image(Some((3000, 10))), (360., 48.));
700 }
701
702 #[test]
703 fn subtitle_adds_the_size_when_known() {
704 let card = FileCard {
705 name: "a.pdf".into(),
706 kind: FileKind::Pdf,
707 content_type: None,
708 size: Some(2048),
709 open_url: String::new(),
710 };
711 assert_eq!(file_subtitle(&card), "PDF document \u{b7} 2 KB");
712 let unknown = FileCard { size: None, ..card };
713 assert_eq!(file_subtitle(&unknown), "PDF document");
714 }
715}