BlueGit

ict rusty-teams

Files

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

attachments.rs

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