BlueGit

ict rusty-teams

Files

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

attachments.rs

attachments.rs 21.9 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.preview().and_then(|preview| {
278 directory
279 .image(&preview.url)
280 .map(|entry| entry.path.clone())
281 });
282 if image.is_none() && card.kind != FileKind::Video {
283 return None;
284 }
285 let frame = div()
286 .id(SharedString::from(format!("{id}-preview")))
287 .relative()
288 .w_full()
289 .h(px(FILE_PREVIEW_HEIGHT))
290 .overflow_hidden()
291 .bg(theme::code_surface());
292 let frame = match image {
293 Some(path) if card.kind.is_document() && card.kind != FileKind::PowerPoint => {
294 frame.bg(theme::white()).child(
295 img(bounded(path))
296 .w_full()
297 .h(px(FILE_CARD_WIDTH * PORTRAIT_PAGE_RATIO))
298 .object_fit(ObjectFit::Cover),
299 )
300 }
301 Some(path) => frame.child(img(bounded(path)).size_full().object_fit(match card.kind {
302 FileKind::Video | FileKind::PowerPoint => ObjectFit::Cover,
303 _ => ObjectFit::Contain,
304 })),
305 None => frame,
306 };
307 let player_key = SharedString::from(format!("{id}-player"));
308 let content_url = card.open_url.clone();
309 Some(frame.when(card.kind == FileKind::Video, |frame| {
310 let play_key = player_key.clone();
311 frame
312 .child(inline_video::slot(player_key))
313 .on_click(move |_, window, cx| {
314 if inline_video::play(play_key.clone(), &content_url, window, cx) {
315 cx.stop_propagation();
316 }
317 })
318 .child(
319 h_flex()
320 .absolute()
321 .inset_0()
322 .items_center()
323 .justify_center()
324 .child(
325 h_flex()
326 .size(px(PLAY_BUTTON_SIZE))
327 .rounded_full()
328 .items_center()
329 .justify_center()
330 .bg(black().opacity(0.5))
331 .child(icon(IconName::Play, 18., theme::white())),
332 ),
333 )
334 }))
335}
336
337fn file_view(
338 card: &FileCard,
339 id: String,
340 index: usize,
341 actions: Option<&FileActions>,
342 directory: &Directory,
343) -> AnyElement {
344 let badge = file_badge(card.kind, FILE_BADGE_SIZE);
345 let url = card.open_url.clone();
346 let state = actions
347 .and_then(|actions| actions.states.get(index))
348 .and_then(Option::as_ref);
349 let progress = downloads::progress_fraction(state);
350 let button = actions
351 .filter(|_| !card.open_url.is_empty() && card.kind != FileKind::Loop)
352 .map(|actions| save_button(state, format!("{id}-save"), index, actions.activate.clone()));
353 let preview = file_preview(card, &id, directory);
354 let row = h_flex()
355 .w_full()
356 .gap(px(12.))
357 .px(px(8.))
358 .py(px(8.))
359 .items_center()
360 .child(badge)
361 .child(
362 v_flex()
363 .flex_1()
364 .min_w_0()
365 .child(
366 div()
367 .truncate()
368 .text_size(px(13.))
369 .text_color(theme::text())
370 .child(card.name.clone()),
371 )
372 .child(
373 div()
374 .truncate()
375 .text_size(px(11.))
376 .text_color(theme::text_muted())
377 .child(file_subtitle(card)),
378 ),
379 )
380 .child(icon(IconName::ExternalLink, 14., theme::text_muted()))
381 .children(button);
382 v_flex()
383 .id(ElementId::Name(id.into()))
384 .relative()
385 .overflow_hidden()
386 .w_full()
387 .max_w(px(FILE_CARD_WIDTH))
388 .rounded(px(10.))
389 .bg(theme::surface())
390 .cursor_pointer()
391 .hover(|card| card.bg(theme::row_hover()))
392 .map(|card_view| {
393 if card.kind.is_document() {
394 card_view.child(row).children(preview)
395 } else {
396 card_view.children(preview).child(row)
397 }
398 })
399 .when_some(progress, |card, fraction| {
400 card.child(
401 div()
402 .absolute()
403 .left_0()
404 .bottom_0()
405 .h(px(SAVE_PROGRESS_HEIGHT))
406 .w(relative(fraction))
407 .bg(theme::accent()),
408 )
409 })
410 .on_click(move |_, _, cx| cx.open_url(&url))
411 .into_any_element()
412}
413
414#[derive(Debug, Clone, Copy, PartialEq, Eq)]
415enum Placement {
416 Remote(usize),
417 Local(usize),
418}
419
420fn local_image_index(url: &str) -> Option<usize> {
421 url.strip_prefix(LOCAL_IMAGE_PREFIX)?
422 .strip_suffix(LOCAL_IMAGE_SUFFIX)?
423 .parse::<usize>()
424 .ok()?
425 .checked_sub(1)
426}
427
428fn placement(url: &str, images: &[ImageRef], local_count: usize) -> Option<Placement> {
429 if let Some(index) = images.iter().position(|image| image.url == url) {
430 return Some(Placement::Remote(index));
431 }
432 local_image_index(url)
433 .filter(|index| *index < local_count)
434 .map(Placement::Local)
435}
436
437fn placements(blocks: &[Block], images: &[ImageRef], local_count: usize) -> Vec<Placement> {
438 blocks
439 .iter()
440 .flat_map(|block| match block {
441 Block::Image { url } => vec![url.as_str()],
442 table => table_images(table),
443 })
444 .filter_map(|url| placement(url, images, local_count))
445 .collect()
446}
447
448fn draws_images(block: &Block) -> bool {
449 matches!(block, Block::Image { .. }) || !table_images(block).is_empty()
450}
451
452pub fn message_body(
453 blocks: &[Block],
454 images: &[ImageRef],
455 local_images: &[LocalImage],
456 sent_previews: &[LocalImage],
457 id: &str,
458 own: bool,
459 directory: &Directory,
460 open_image: Option<&ImageActions>,
461 cx: &App,
462) -> Vec<AnyElement> {
463 if !blocks.iter().any(draws_images) {
464 return vec![render_blocks(blocks, id, own, cx)];
465 }
466 let mut elements = Vec::new();
467 let mut run_start = 0;
468 let render_run = |start: usize, end: usize, elements: &mut Vec<AnyElement>| {
469 if end > start {
470 let part_id = format!("{id}-part-{start}");
471 elements.push(render_blocks(&blocks[start..end], &part_id, own, cx));
472 }
473 };
474 let placed_view = |url: &str, key: &str| -> Option<AnyElement> {
475 match placement(url, images, local_images.len())? {
476 Placement::Remote(position) => Some(image_view(
477 &images[position],
478 format!("{key}-image-{position}"),
479 directory,
480 open_image,
481 sent_preview(images, position, sent_previews),
482 )),
483 Placement::Local(position) => Some(local_image_view(
484 &local_images[position],
485 format!("{key}-local-image-{position}"),
486 )),
487 }
488 };
489 for (index, block) in blocks.iter().enumerate() {
490 if !draws_images(block) {
491 continue;
492 }
493 render_run(run_start, index, &mut elements);
494 run_start = index + 1;
495 match block {
496 Block::Image { url } => elements.extend(placed_view(url, id)),
497 Block::Table { header, rows } => {
498 let table_id = format!("{id}-table-{index}");
499 elements.push(render_table(*header, rows, &table_id, own, cx, &|url| {
500 placed_view(url, &table_id)
501 }));
502 }
503 _ => {}
504 }
505 }
506 render_run(run_start, blocks.len(), &mut elements);
507 elements
508}
509
510pub fn attachments_view(
511 blocks: &[Block],
512 images: &[ImageRef],
513 local_images: &[LocalImage],
514 sent_previews: &[LocalImage],
515 files: &[FileCard],
516 id: &str,
517 directory: &Directory,
518 file_actions: Option<&FileActions>,
519 open_image: Option<&ImageActions>,
520) -> Option<Div> {
521 let placed = placements(blocks, images, local_images.len());
522 let unplaced_images: Vec<(usize, &ImageRef)> = images
523 .iter()
524 .enumerate()
525 .filter(|(index, _)| !placed.contains(&Placement::Remote(*index)))
526 .collect();
527 let unplaced_local: Vec<(usize, &LocalImage)> = local_images
528 .iter()
529 .enumerate()
530 .filter(|(index, _)| !placed.contains(&Placement::Local(*index)))
531 .collect();
532 if unplaced_images.is_empty() && unplaced_local.is_empty() && files.is_empty() {
533 return None;
534 }
535 Some(
536 v_flex()
537 .gap(px(6.))
538 .items_start()
539 .children(unplaced_images.into_iter().map(|(index, image)| {
540 image_view(
541 image,
542 format!("{id}-image-{index}"),
543 directory,
544 open_image,
545 sent_preview(images, index, sent_previews),
546 )
547 }))
548 .children(
549 unplaced_local.into_iter().map(|(index, image)| {
550 local_image_view(image, format!("{id}-local-image-{index}"))
551 }),
552 )
553 .children(files.iter().enumerate().map(|(index, card)| {
554 file_view(
555 card,
556 format!("{id}-file-{index}"),
557 index,
558 file_actions,
559 directory,
560 )
561 })),
562 )
563}
564
565#[cfg(test)]
566mod tests {
567 use super::{
568 IMAGE_FALLBACK, Placement, file_subtitle, fit_image, fit_image_within, local_image_index,
569 placement, placements, sent_preview,
570 };
571 use crate::rows::LocalImage;
572 use crate::render::{Block, TableCell};
573 use teams_core::{FileCard, FileKind, ImageRef};
574
575 fn image_ref(url: &str) -> ImageRef {
576 ImageRef {
577 id: url.into(),
578 url: url.into(),
579 width: None,
580 height: None,
581 alt: None,
582 }
583 }
584
585 fn image_block(url: &str) -> Block {
586 Block::Image { url: url.into() }
587 }
588
589 #[test]
590 fn sent_previews_follow_the_uploaded_images_and_skip_gifs() {
591 let gif = "https://media.giphy.com/media/x/giphy.gif";
592 let images = [image_ref("hosted-a"), image_ref(gif), image_ref("hosted-b")];
593 let previews: Vec<LocalImage> = [(1, 1), (2, 2)]
594 .into_iter()
595 .map(|size| LocalImage { image: std::sync::Arc::new(gpui_kit::Image::empty()), size: Some(size) })
596 .collect();
597 let size_at = |position| sent_preview(&images, position, &previews).and_then(|preview| preview.size);
598 assert_eq!(size_at(0), Some((1, 1)));
599 assert_eq!(size_at(1), None);
600 assert_eq!(size_at(2), Some((2, 2)));
601 }
602
603 #[test]
604 fn hosted_content_urls_map_to_zero_based_local_indices() {
605 assert_eq!(local_image_index("../hostedContents/2/$value"), Some(1));
606 assert_eq!(local_image_index("../hostedContents/0/$value"), None);
607 assert_eq!(local_image_index("https://x/y"), None);
608 }
609
610 #[test]
611 fn placed_images_are_found_by_url_before_local_indices() {
612 let images = [image_ref("a"), image_ref("b")];
613 let blocks = [
614 image_block("b"),
615 image_block("../hostedContents/2/$value"),
616 image_block("../hostedContents/9/$value"),
617 image_block("missing"),
618 ];
619 assert_eq!(
620 placements(&blocks, &images, 2),
621 vec![Placement::Remote(1), Placement::Local(1)]
622 );
623 assert_eq!(placement("a", &images, 0), Some(Placement::Remote(0)));
624 }
625
626 #[test]
627 fn an_image_in_a_table_cell_counts_as_placed() {
628 let images = [image_ref("a"), image_ref("b")];
629 let table = Block::Table {
630 header: false,
631 rows: vec![vec![TableCell {
632 inline: Default::default(),
633 images: vec!["b".into()],
634 }]],
635 };
636 assert_eq!(placements(&[table], &images, 0), vec![Placement::Remote(1)]);
637 }
638
639 #[test]
640 fn wide_images_shrink_to_the_max_width_keeping_aspect() {
641 assert_eq!(fit_image(Some((720, 360))), (360., 180.));
642 }
643
644 #[test]
645 fn gifs_and_stickers_are_capped_at_250_high() {
646 assert_eq!(fit_image_within(Some((300, 500)), 250.), (150., 250.));
647 }
648
649 #[test]
650 fn tall_images_shrink_to_the_max_height() {
651 assert_eq!(fit_image(Some((300, 600))), (150., 300.));
652 }
653
654 #[test]
655 fn small_images_keep_their_size() {
656 assert_eq!(fit_image(Some((200, 100))), (200., 100.));
657 }
658
659 #[test]
660 fn unknown_or_empty_sizes_use_the_fallback() {
661 assert_eq!(fit_image(None), IMAGE_FALLBACK);
662 assert_eq!(fit_image(Some((0, 10))), IMAGE_FALLBACK);
663 }
664
665 #[test]
666 fn thin_images_keep_a_clickable_side() {
667 assert_eq!(fit_image(Some((3000, 10))), (360., 48.));
668 }
669
670 #[test]
671 fn subtitle_adds_the_size_when_known() {
672 let card = FileCard {
673 name: "a.pdf".into(),
674 kind: FileKind::Pdf,
675 content_type: None,
676 size: Some(2048),
677 open_url: String::new(),
678 };
679 assert_eq!(file_subtitle(&card), "PDF document \u{b7} 2 KB");
680 let unknown = FileCard { size: None, ..card };
681 assert_eq!(file_subtitle(&unknown), "PDF document");
682 }
683}