BlueGit

ict rusty-teams

Files

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

attachments.rs

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