BlueGit

ict rusty-teams

Files

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

attachments.rs

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