BlueGit

ict rusty-teams

Files

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

attachments.rs

attachments.rs 19.7 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 file_subtitle(card: &FileCard) -> String {
161 let description = kind_style(card.kind).description;
162 match card.size {
163 Some(size) => format!("{description} \u{b7} {}", format::file_size_label(size)),
164 None => description.to_owned(),
165 }
166}
167
168pub fn file_badge(kind: FileKind, size: f32) -> Div {
169 let style = kind_style(kind);
170 div()
171 .size(px(size))
172 .flex_none()
173 .flex()
174 .items_center()
175 .justify_center()
176 .rounded(px(7.))
177 .bg(theme::color(style.color))
178 .text_color(gpui_kit::white())
179 .text_size(px(10.5))
180 .font_weight(FontWeight::BOLD)
181 .when(style.label.is_empty(), |badge| {
182 badge.child(icon(IconName::File, 16., gpui_kit::white()))
183 })
184 .when(!style.label.is_empty(), |badge| badge.child(style.label))
185}
186
187fn local_image_view(image: &LocalImage, id: String) -> AnyElement {
188 let (width, height) = fit_image(image.size);
189 let image_id = ElementId::Name(format!("{id}-image").into());
190 div()
191 .id(ElementId::Name(id.into()))
192 .w(px(width))
193 .h(px(height))
194 .max_w(relative(1.))
195 .flex_none()
196 .rounded(px(IMAGE_RADIUS))
197 .overflow_hidden()
198 .child(
199 img(image.image.clone())
200 .id(image_id)
201 .size_full()
202 .rounded(px(IMAGE_RADIUS))
203 .object_fit(ObjectFit::Cover),
204 )
205 .into_any_element()
206}
207
208fn save_button(
209 state: Option<&DownloadState>,
210 id: String,
211 index: usize,
212 activate: FileActivate,
213) -> Stateful<Div> {
214 let look = downloads::button_look(state);
215 let tooltip = look.tooltip.clone();
216 let clickable = look.clickable;
217 let button = div()
218 .id(ElementId::Name(id.into()))
219 .size(px(SAVE_BUTTON_SIZE))
220 .flex_none()
221 .flex()
222 .items_center()
223 .justify_center()
224 .rounded(px(SAVE_BUTTON_RADIUS))
225 .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
226 .when(look.clickable, |button| {
227 button
228 .cursor_pointer()
229 .hover(|button| button.bg(theme::row_hover()))
230 })
231 .on_click(move |_, _, cx| {
232 cx.stop_propagation();
233 if clickable {
234 activate(index, cx);
235 }
236 });
237 match look.percent {
238 Some(percent) => button.child(
239 div()
240 .text_size(px(11.))
241 .text_color(theme::text_muted())
242 .child(downloads::percent_label(percent)),
243 ),
244 None => button.child(symbol(look.symbol, 16., theme::text_muted())),
245 }
246}
247
248fn file_preview(card: &FileCard, id: &str, directory: &Directory) -> Option<Stateful<Div>> {
249 let image = card
250 .preview()
251 .and_then(|preview| directory.image(&preview.url).map(|entry| entry.path.clone()));
252 if image.is_none() && card.kind != FileKind::Video {
253 return None;
254 }
255 let frame = div()
256 .id(SharedString::from(format!("{id}-preview")))
257 .relative()
258 .w_full()
259 .h(px(FILE_PREVIEW_HEIGHT))
260 .overflow_hidden()
261 .bg(theme::code_surface());
262 let frame = match image {
263 Some(path) if card.kind.is_document() && card.kind != FileKind::PowerPoint => frame
264 .bg(theme::white())
265 .child(img(path).w_full().h(px(FILE_CARD_WIDTH * PORTRAIT_PAGE_RATIO)).object_fit(ObjectFit::Cover)),
266 Some(path) => frame.child(img(path).size_full().object_fit(match card.kind {
267 FileKind::Video | FileKind::PowerPoint => ObjectFit::Cover,
268 _ => ObjectFit::Contain,
269 })),
270 None => frame,
271 };
272 let player_key = SharedString::from(format!("{id}-player"));
273 let content_url = card.open_url.clone();
274 Some(frame.when(card.kind == FileKind::Video, |frame| {
275 let play_key = player_key.clone();
276 frame
277 .child(inline_video::slot(player_key))
278 .on_click(move |_, window, cx| {
279 if inline_video::play(play_key.clone(), &content_url, window, cx) {
280 cx.stop_propagation();
281 }
282 })
283 .child(
284 h_flex()
285 .absolute()
286 .inset_0()
287 .items_center()
288 .justify_center()
289 .child(
290 h_flex()
291 .size(px(PLAY_BUTTON_SIZE))
292 .rounded_full()
293 .items_center()
294 .justify_center()
295 .bg(black().opacity(0.5))
296 .child(icon(IconName::Play, 18., theme::white())),
297 ),
298 )
299 }))
300}
301
302fn file_view(
303 card: &FileCard,
304 id: String,
305 index: usize,
306 actions: Option<&FileActions>,
307 directory: &Directory,
308) -> AnyElement {
309 let badge = file_badge(card.kind, FILE_BADGE_SIZE);
310 let url = card.open_url.clone();
311 let state = actions
312 .and_then(|actions| actions.states.get(index))
313 .and_then(Option::as_ref);
314 let progress = downloads::progress_fraction(state);
315 let button = actions
316 .filter(|_| !card.open_url.is_empty() && card.kind != FileKind::Loop)
317 .map(|actions| save_button(state, format!("{id}-save"), index, actions.activate.clone()));
318 let preview = file_preview(card, &id, directory);
319 let row = h_flex()
320 .w_full()
321 .gap(px(12.))
322 .px(px(8.))
323 .py(px(8.))
324 .items_center()
325 .child(badge)
326 .child(
327 v_flex()
328 .flex_1()
329 .min_w_0()
330 .child(
331 div()
332 .truncate()
333 .text_size(px(13.))
334 .text_color(theme::text())
335 .child(card.name.clone()),
336 )
337 .child(
338 div()
339 .truncate()
340 .text_size(px(11.))
341 .text_color(theme::text_muted())
342 .child(file_subtitle(card)),
343 ),
344 )
345 .child(icon(IconName::ExternalLink, 14., theme::text_muted()))
346 .children(button);
347 v_flex()
348 .id(ElementId::Name(id.into()))
349 .relative()
350 .overflow_hidden()
351 .w_full()
352 .max_w(px(FILE_CARD_WIDTH))
353 .rounded(px(10.))
354 .bg(theme::surface())
355 .cursor_pointer()
356 .hover(|card| card.bg(theme::row_hover()))
357 .map(|card_view| {
358 if card.kind.is_document() {
359 card_view.child(row).children(preview)
360 } else {
361 card_view.children(preview).child(row)
362 }
363 })
364 .when_some(progress, |card, fraction| {
365 card.child(
366 div()
367 .absolute()
368 .left_0()
369 .bottom_0()
370 .h(px(SAVE_PROGRESS_HEIGHT))
371 .w(relative(fraction))
372 .bg(theme::accent()),
373 )
374 })
375 .on_click(move |_, _, cx| cx.open_url(&url))
376 .into_any_element()
377}
378
379#[derive(Debug, Clone, Copy, PartialEq, Eq)]
380enum Placement {
381 Remote(usize),
382 Local(usize),
383}
384
385fn local_image_index(url: &str) -> Option<usize> {
386 url.strip_prefix(LOCAL_IMAGE_PREFIX)?
387 .strip_suffix(LOCAL_IMAGE_SUFFIX)?
388 .parse::<usize>()
389 .ok()?
390 .checked_sub(1)
391}
392
393fn placement(url: &str, images: &[ImageRef], local_count: usize) -> Option<Placement> {
394 if let Some(index) = images.iter().position(|image| image.url == url) {
395 return Some(Placement::Remote(index));
396 }
397 local_image_index(url)
398 .filter(|index| *index < local_count)
399 .map(Placement::Local)
400}
401
402fn placements(blocks: &[Block], images: &[ImageRef], local_count: usize) -> Vec<Placement> {
403 blocks
404 .iter()
405 .flat_map(|block| match block {
406 Block::Image { url } => vec![url.as_str()],
407 table => table_images(table),
408 })
409 .filter_map(|url| placement(url, images, local_count))
410 .collect()
411}
412
413fn draws_images(block: &Block) -> bool {
414 matches!(block, Block::Image { .. }) || !table_images(block).is_empty()
415}
416
417pub fn message_body(
418 blocks: &[Block],
419 images: &[ImageRef],
420 local_images: &[LocalImage],
421 id: &str,
422 own: bool,
423 directory: &Directory,
424 open_image: Option<&ImageActions>,
425 cx: &App,
426) -> Vec<AnyElement> {
427 if !blocks.iter().any(draws_images) {
428 return vec![render_blocks(blocks, id, own, cx)];
429 }
430 let mut elements = Vec::new();
431 let mut run_start = 0;
432 let render_run = |start: usize, end: usize, elements: &mut Vec<AnyElement>| {
433 if end > start {
434 let part_id = format!("{id}-part-{start}");
435 elements.push(render_blocks(&blocks[start..end], &part_id, own, cx));
436 }
437 };
438 let placed_view = |url: &str, key: &str| -> Option<AnyElement> {
439 match placement(url, images, local_images.len())? {
440 Placement::Remote(position) => Some(image_view(
441 &images[position],
442 format!("{key}-image-{position}"),
443 directory,
444 open_image,
445 )),
446 Placement::Local(position) => Some(local_image_view(
447 &local_images[position],
448 format!("{key}-local-image-{position}"),
449 )),
450 }
451 };
452 for (index, block) in blocks.iter().enumerate() {
453 if !draws_images(block) {
454 continue;
455 }
456 render_run(run_start, index, &mut elements);
457 run_start = index + 1;
458 match block {
459 Block::Image { url } => elements.extend(placed_view(url, id)),
460 Block::Table { header, rows } => {
461 let table_id = format!("{id}-table-{index}");
462 elements.push(render_table(*header, rows, &table_id, own, cx, &|url| {
463 placed_view(url, &table_id)
464 }));
465 }
466 _ => {}
467 }
468 }
469 render_run(run_start, blocks.len(), &mut elements);
470 elements
471}
472
473pub fn attachments_view(
474 blocks: &[Block],
475 images: &[ImageRef],
476 local_images: &[LocalImage],
477 files: &[FileCard],
478 id: &str,
479 directory: &Directory,
480 file_actions: Option<&FileActions>,
481 open_image: Option<&ImageActions>,
482) -> Option<Div> {
483 let placed = placements(blocks, images, local_images.len());
484 let unplaced_images: Vec<(usize, &ImageRef)> = images
485 .iter()
486 .enumerate()
487 .filter(|(index, _)| !placed.contains(&Placement::Remote(*index)))
488 .collect();
489 let unplaced_local: Vec<(usize, &LocalImage)> = local_images
490 .iter()
491 .enumerate()
492 .filter(|(index, _)| !placed.contains(&Placement::Local(*index)))
493 .collect();
494 if unplaced_images.is_empty() && unplaced_local.is_empty() && files.is_empty() {
495 return None;
496 }
497 Some(
498 v_flex()
499 .gap(px(6.))
500 .items_start()
501 .children(unplaced_images.into_iter().map(|(index, image)| {
502 image_view(image, format!("{id}-image-{index}"), directory, open_image)
503 }))
504 .children(
505 unplaced_local.into_iter().map(|(index, image)| {
506 local_image_view(image, format!("{id}-local-image-{index}"))
507 }),
508 )
509 .children(files.iter().enumerate().map(|(index, card)| {
510 file_view(
511 card,
512 format!("{id}-file-{index}"),
513 index,
514 file_actions,
515 directory,
516 )
517 })),
518 )
519}
520
521#[cfg(test)]
522mod tests {
523 use super::{
524 IMAGE_FALLBACK, Placement, file_subtitle, fit_image, fit_image_within, local_image_index,
525 placement, placements,
526 };
527 use crate::render::{Block, TableCell};
528 use teams_core::{FileCard, FileKind, ImageRef};
529
530 fn image_ref(url: &str) -> ImageRef {
531 ImageRef {
532 id: url.into(),
533 url: url.into(),
534 width: None,
535 height: None,
536 alt: None,
537 }
538 }
539
540 fn image_block(url: &str) -> Block {
541 Block::Image { url: url.into() }
542 }
543
544 #[test]
545 fn hosted_content_urls_map_to_zero_based_local_indices() {
546 assert_eq!(local_image_index("../hostedContents/2/$value"), Some(1));
547 assert_eq!(local_image_index("../hostedContents/0/$value"), None);
548 assert_eq!(local_image_index("https://x/y"), None);
549 }
550
551 #[test]
552 fn placed_images_are_found_by_url_before_local_indices() {
553 let images = [image_ref("a"), image_ref("b")];
554 let blocks = [
555 image_block("b"),
556 image_block("../hostedContents/2/$value"),
557 image_block("../hostedContents/9/$value"),
558 image_block("missing"),
559 ];
560 assert_eq!(
561 placements(&blocks, &images, 2),
562 vec![Placement::Remote(1), Placement::Local(1)]
563 );
564 assert_eq!(placement("a", &images, 0), Some(Placement::Remote(0)));
565 }
566
567 #[test]
568 fn an_image_in_a_table_cell_counts_as_placed() {
569 let images = [image_ref("a"), image_ref("b")];
570 let table = Block::Table {
571 header: false,
572 rows: vec![vec![TableCell {
573 inline: Default::default(),
574 images: vec!["b".into()],
575 }]],
576 };
577 assert_eq!(placements(&[table], &images, 0), vec![Placement::Remote(1)]);
578 }
579
580 #[test]
581 fn wide_images_shrink_to_the_max_width_keeping_aspect() {
582 assert_eq!(fit_image(Some((720, 360))), (360., 180.));
583 }
584
585 #[test]
586 fn gifs_and_stickers_are_capped_at_250_high() {
587 assert_eq!(fit_image_within(Some((300, 500)), 250.), (150., 250.));
588 }
589
590 #[test]
591 fn tall_images_shrink_to_the_max_height() {
592 assert_eq!(fit_image(Some((300, 600))), (150., 300.));
593 }
594
595 #[test]
596 fn small_images_keep_their_size() {
597 assert_eq!(fit_image(Some((200, 100))), (200., 100.));
598 }
599
600 #[test]
601 fn unknown_or_empty_sizes_use_the_fallback() {
602 assert_eq!(fit_image(None), IMAGE_FALLBACK);
603 assert_eq!(fit_image(Some((0, 10))), IMAGE_FALLBACK);
604 }
605
606 #[test]
607 fn thin_images_keep_a_clickable_side() {
608 assert_eq!(fit_image(Some((3000, 10))), (360., 48.));
609 }
610
611 #[test]
612 fn subtitle_adds_the_size_when_known() {
613 let card = FileCard {
614 name: "a.pdf".into(),
615 kind: FileKind::Pdf,
616 content_type: None,
617 size: Some(2048),
618 open_url: String::new(),
619 };
620 assert_eq!(file_subtitle(&card), "PDF document \u{b7} 2 KB");
621 let unknown = FileCard { size: None, ..card };
622 assert_eq!(file_subtitle(&unknown), "PDF document");
623 }
624}