BlueGit

ict rusty-teams

Files

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

attachment_tray.rs

attachment_tray.rs 49.8 KiB Download Raw
1use std::io::Cursor;
2use std::path::{Path, PathBuf};
3use std::rc::Rc;
4use std::sync::Arc;
5
6use gpui_kit::assets::IconName;
7use gpui_kit::component::{h_flex, v_flex};
8use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::*;
10use teams_core::{FileKind, FileReference, UploadedFile};
11
12use super::attachments::file_badge;
13use super::widgets::icon;
14use crate::format;
15use crate::inline_image::{InlineFormat, image_dimensions, sniff_inline_format};
16pub use crate::outgoing::{InlineImage, OutgoingFile, OutgoingImage};
17use crate::remote_image::{RemoteImage, image_source};
18use crate::theme;
19
20pub const MAX_ATTACHMENTS: usize = 10;
21pub const INLINE_IMAGE_MAX_BYTES: u64 = 1024 * 1024;
22pub const INLINE_TOTAL_MAX_BYTES: u64 = 5 * 512 * 1024;
23pub const MAX_FILE_BYTES: u64 = 250 * 1024 * 1024;
24pub const FILES_LATER_NOTICE: &str = "Files can be added once the chat exists.";
25const PASTED_IMAGE_STEM: &str = "pasted-image";
26const PREVIEW_HEIGHT: f32 = 120.;
27const PREVIEW_GAP: f32 = 4.;
28const PREVIEW_RADIUS: f32 = 10.;
29const CHIP_WIDTH: f32 = 220.;
30const CHIP_HEIGHT: f32 = 52.;
31const CHIP_BADGE_SIZE: f32 = 30.;
32const REMOVE_SIZE: f32 = 18.;
33const CHIP_REMOVE_SIZE: f32 = 28.;
34const TRAY_GAP: f32 = 8.;
35const PROGRESS_HEIGHT: f32 = 2.;
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum Classification {
39 Inline(InlineFormat),
40 File { sent_as_file: bool },
41}
42
43/// `inline_used` is the raw bytes of the images already inline in the tray.
44pub fn classify(name: &str, bytes: &[u8], inline_used: u64) -> Classification {
45 let size = bytes.len() as u64;
46 match sniff_inline_format(bytes) {
47 Some(format)
48 if size <= INLINE_IMAGE_MAX_BYTES && inline_used + size <= INLINE_TOTAL_MAX_BYTES =>
49 {
50 Classification::Inline(format)
51 }
52 Some(_) => Classification::File { sent_as_file: true },
53 None => Classification::File {
54 sent_as_file: FileKind::from_name(name) == FileKind::Image,
55 },
56 }
57}
58
59pub fn inline_image(name: String, bytes: Vec<u8>) -> Option<InlineImage> {
60 let format = sniff_inline_format(&bytes)?;
61 let dimensions = image_dimensions(format, &bytes);
62 Some(InlineImage {
63 name,
64 image: Arc::new(Image::from_bytes(format.image_format(), bytes)),
65 dimensions,
66 })
67}
68
69pub fn limit_notice(dropped: usize) -> String {
70 let files = if dropped == 1 {
71 "1 file was".to_owned()
72 } else {
73 format!("{dropped} files were")
74 };
75 format!("Up to {MAX_ATTACHMENTS} attachments per message. {files} not added.")
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub enum UploadState {
80 Uploading(u8),
81 Done(DoneFile),
82 Failed,
83 Sharing(UploadedFile),
84 ShareFailed(UploadedFile),
85}
86
87/// `uploaded` is known for files the app uploaded, so an unsent one can be deleted again.
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct DoneFile {
90 pub reference: FileReference,
91 pub uploaded: Option<UploadedFile>,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub enum UploadResult {
96 Done(DoneFile),
97 ShareFailed(UploadedFile),
98 Failed,
99}
100
101impl UploadState {
102 fn uploaded(&self) -> Option<UploadedFile> {
103 match self {
104 UploadState::Done(done) => done.uploaded.clone(),
105 UploadState::Sharing(uploaded) | UploadState::ShareFailed(uploaded) => {
106 Some(uploaded.clone())
107 }
108 _ => None,
109 }
110 }
111}
112
113#[derive(Debug, Clone)]
114#[allow(clippy::large_enum_variant)]
115pub enum ItemKind {
116 Reading,
117 Image {
118 image: Arc<Image>,
119 dimensions: Option<(u32, u32)>,
120 },
121 Remote(RemoteImage),
122 File {
123 bytes: Arc<Vec<u8>>,
124 upload: UploadState,
125 sent_as_file: bool,
126 },
127}
128
129#[derive(Debug, Clone)]
130pub struct TrayItem {
131 pub id: u64,
132 pub name: String,
133 pub size: u64,
134 pub kind: ItemKind,
135}
136
137impl ItemKind {
138 /// Shown inline in the text instead of as a chip.
139 fn is_object(&self) -> bool {
140 matches!(self, ItemKind::Image { .. } | ItemKind::Remote(_))
141 }
142}
143
144impl TrayItem {
145 fn blocks_send(&self) -> bool {
146 match &self.kind {
147 ItemKind::Reading => true,
148 ItemKind::Image { .. } | ItemKind::Remote(_) => false,
149 ItemKind::File { upload, .. } => !matches!(upload, UploadState::Done(_)),
150 }
151 }
152}
153
154#[derive(Debug, Clone)]
155pub enum PreviewImage {
156 Inline {
157 image: Arc<Image>,
158 dimensions: Option<(u32, u32)>,
159 },
160 Remote(RemoteImage),
161}
162
163impl PreviewImage {
164 fn dimensions(&self) -> Option<(u32, u32)> {
165 match self {
166 PreviewImage::Inline { dimensions, .. } => *dimensions,
167 PreviewImage::Remote(remote) => Some((remote.width, remote.height)),
168 }
169 }
170}
171
172pub type RemoveImage = Rc<dyn Fn(&mut Window, &mut App)>;
173
174#[derive(Debug, Clone)]
175pub enum JobKind {
176 Upload,
177 Share(UploadedFile),
178}
179
180#[derive(Debug, Clone)]
181pub struct UploadJob {
182 pub id: u64,
183 pub name: String,
184 pub bytes: Arc<Vec<u8>>,
185 pub kind: JobKind,
186}
187
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct LoadedFile {
190 pub bytes: Vec<u8>,
191 pub dimensions: Option<(u32, u32)>,
192 pub file_name: Option<String>,
193}
194
195impl LoadedFile {
196 pub fn new(bytes: Vec<u8>) -> Self {
197 let dimensions =
198 sniff_inline_format(&bytes).and_then(|format| image_dimensions(format, &bytes));
199 LoadedFile {
200 bytes,
201 dimensions,
202 file_name: None,
203 }
204 }
205}
206
207#[derive(Debug, Clone, Default)]
208pub struct AttachmentTray {
209 items: Vec<TrayItem>,
210 next_id: u64,
211 notice: Option<String>,
212}
213
214impl AttachmentTray {
215 pub fn items(&self) -> &[TrayItem] {
216 &self.items
217 }
218
219 pub fn has_chips(&self) -> bool {
220 self.items.iter().any(|item| !item.kind.is_object())
221 }
222
223 pub fn image(&self, id: u64) -> Option<PreviewImage> {
224 self.items.iter().find_map(|item| match &item.kind {
225 ItemKind::Image { image, dimensions } if item.id == id => Some(PreviewImage::Inline {
226 image: image.clone(),
227 dimensions: *dimensions,
228 }),
229 ItemKind::Remote(remote) if item.id == id => Some(PreviewImage::Remote(remote.clone())),
230 _ => None,
231 })
232 }
233
234 /// `None` when the tray is full.
235 pub fn add_remote(&mut self, remote: RemoteImage) -> Option<u64> {
236 self.notice = None;
237 if self.items.len() >= MAX_ATTACHMENTS {
238 self.notice = Some(limit_notice(1));
239 return None;
240 }
241 Some(self.push(remote.title.clone(), 0, ItemKind::Remote(remote)))
242 }
243
244 pub fn notice(&self) -> Option<&str> {
245 self.notice.as_deref()
246 }
247
248 pub fn blocks_send(&self) -> bool {
249 self.items.iter().any(TrayItem::blocks_send)
250 }
251
252 fn push(&mut self, name: String, size: u64, kind: ItemKind) -> u64 {
253 self.next_id += 1;
254 self.items.push(TrayItem {
255 id: self.next_id,
256 name,
257 size,
258 kind,
259 });
260 self.next_id
261 }
262
263 /// Items beyond the limit are dropped; the ids returned belong to the first names.
264 pub fn add_pending(&mut self, names: &[String]) -> Vec<u64> {
265 self.notice = None;
266 let accepted = names
267 .len()
268 .min(MAX_ATTACHMENTS.saturating_sub(self.items.len()));
269 let ids = names[..accepted]
270 .iter()
271 .map(|name| self.push(name.clone(), 0, ItemKind::Reading))
272 .collect();
273 if accepted < names.len() {
274 self.notice = Some(limit_notice(names.len() - accepted));
275 }
276 ids
277 }
278
279 /// Returns the upload to start when the item turned out to be a file.
280 pub fn finish_reading(
281 &mut self,
282 id: u64,
283 loaded: LoadedFile,
284 files_allowed: bool,
285 ) -> Option<UploadJob> {
286 let position = self
287 .items
288 .iter()
289 .position(|item| item.id == id && matches!(item.kind, ItemKind::Reading))?;
290 let name = loaded
291 .file_name
292 .clone()
293 .unwrap_or_else(|| self.items[position].name.clone());
294 let size = loaded.bytes.len() as u64;
295 match classify(&name, &loaded.bytes, self.inline_bytes()) {
296 Classification::Inline(format) => {
297 let item = &mut self.items[position];
298 item.name = name;
299 item.size = size;
300 item.kind = ItemKind::Image {
301 image: Arc::new(Image::from_bytes(format.image_format(), loaded.bytes)),
302 dimensions: loaded.dimensions,
303 };
304 None
305 }
306 Classification::File { .. } if !files_allowed => {
307 self.items.remove(position);
308 self.notice = Some(FILES_LATER_NOTICE.to_owned());
309 None
310 }
311 Classification::File { sent_as_file } => {
312 let bytes = Arc::new(loaded.bytes);
313 let item = &mut self.items[position];
314 item.name = name.clone();
315 item.size = size;
316 item.kind = ItemKind::File {
317 bytes: bytes.clone(),
318 upload: UploadState::Uploading(0),
319 sent_as_file,
320 };
321 Some(UploadJob {
322 id,
323 name,
324 bytes,
325 kind: JobKind::Upload,
326 })
327 }
328 }
329 }
330
331 pub fn fail_reading(&mut self, id: u64, message: String) {
332 let before = self.items.len();
333 self.items.retain(|item| item.id != id);
334 if self.items.len() != before {
335 self.notice = Some(message);
336 }
337 }
338
339 pub fn set_progress(&mut self, id: u64, percent: u8) {
340 if let Some(ItemKind::File { upload, .. }) = self.kind_of_mut(id)
341 && matches!(upload, UploadState::Uploading(_))
342 {
343 *upload = UploadState::Uploading(percent.min(100));
344 }
345 }
346
347 /// The bytes are on the server; from here a remove or switch must delete the item.
348 /// Returns the file back when its item is gone, so the caller can delete it.
349 pub fn mark_uploaded(&mut self, id: u64, uploaded: UploadedFile) -> Option<UploadedFile> {
350 if !self.items.iter().any(|item| item.id == id) {
351 return Some(uploaded);
352 }
353 if let Some(ItemKind::File { upload, .. }) = self.kind_of_mut(id)
354 && matches!(upload, UploadState::Uploading(_))
355 {
356 *upload = UploadState::Sharing(uploaded);
357 }
358 None
359 }
360
361 /// Returns the uploaded file of a result whose item is gone, so the caller can delete it.
362 pub fn finish_upload(&mut self, id: u64, result: UploadResult) -> Option<UploadedFile> {
363 if !self.items.iter().any(|item| item.id == id) {
364 return match result {
365 UploadResult::Done(done) => done.uploaded,
366 UploadResult::ShareFailed(uploaded) => Some(uploaded),
367 UploadResult::Failed => None,
368 };
369 }
370 if let Some(ItemKind::File { upload, .. }) = self.kind_of_mut(id)
371 && matches!(upload, UploadState::Uploading(_) | UploadState::Sharing(_))
372 {
373 *upload = match result {
374 UploadResult::Done(done) => UploadState::Done(done),
375 UploadResult::ShareFailed(uploaded) => UploadState::ShareFailed(uploaded),
376 UploadResult::Failed => UploadState::Failed,
377 };
378 }
379 None
380 }
381
382 pub fn retry(&mut self, id: u64) -> Option<UploadJob> {
383 self.notice = None;
384 let item = self.items.iter_mut().find(|item| item.id == id)?;
385 let ItemKind::File { bytes, upload, .. } = &mut item.kind else {
386 return None;
387 };
388 match upload.clone() {
389 UploadState::Failed => *upload = UploadState::Uploading(0),
390 UploadState::ShareFailed(uploaded) => *upload = UploadState::Sharing(uploaded),
391 _ => return None,
392 }
393 let kind = match upload {
394 UploadState::Sharing(uploaded) => JobKind::Share(uploaded.clone()),
395 _ => JobKind::Upload,
396 };
397 Some(UploadJob {
398 id,
399 name: item.name.clone(),
400 bytes: bytes.clone(),
401 kind,
402 })
403 }
404
405 /// Returns the uploaded file of the removed item, which was never sent.
406 pub fn remove(&mut self, id: u64) -> Option<UploadedFile> {
407 self.notice = None;
408 let position = self.items.iter().position(|item| item.id == id)?;
409 match self.items.remove(position).kind {
410 ItemKind::File { upload, .. } => upload.uploaded(),
411 _ => None,
412 }
413 }
414
415 /// Returns the uploaded files that were dropped unsent.
416 pub fn clear(&mut self) -> Vec<UploadedFile> {
417 self.notice = None;
418 self.items
419 .drain(..)
420 .filter_map(|item| match item.kind {
421 ItemKind::File { upload, .. } => upload.uploaded(),
422 _ => None,
423 })
424 .collect()
425 }
426
427 pub fn keep_images_only(&mut self) -> Vec<UploadedFile> {
428 self.notice = None;
429 let (images, others): (Vec<_>, Vec<_>) =
430 self.items.drain(..).partition(|item| item.kind.is_object());
431 self.items = images;
432 others
433 .into_iter()
434 .filter_map(|item| match item.kind {
435 ItemKind::File { upload, .. } => upload.uploaded(),
436 _ => None,
437 })
438 .collect()
439 }
440
441 fn inline_bytes(&self) -> u64 {
442 self.items
443 .iter()
444 .filter(|item| matches!(item.kind, ItemKind::Image { .. }))
445 .map(|item| item.size)
446 .sum()
447 }
448
449 pub fn restore(&mut self, images: &[OutgoingImage], files: &[OutgoingFile]) -> Vec<u64> {
450 self.clear();
451 let image_ids = images
452 .iter()
453 .map(|image| match image {
454 OutgoingImage::Inline(inline) => self.push(
455 inline.name.clone(),
456 inline.image.bytes.len() as u64,
457 ItemKind::Image {
458 image: inline.image.clone(),
459 dimensions: inline.dimensions,
460 },
461 ),
462 OutgoingImage::Remote(remote) => {
463 self.push(remote.title.clone(), 0, ItemKind::Remote(remote.clone()))
464 }
465 })
466 .collect();
467 for file in files {
468 self.push(
469 file.name.clone(),
470 file.size,
471 ItemKind::File {
472 bytes: Arc::new(Vec::new()),
473 upload: UploadState::Done(DoneFile {
474 reference: file.reference.clone(),
475 uploaded: file.uploaded.clone(),
476 }),
477 sent_as_file: false,
478 },
479 );
480 }
481 image_ids
482 }
483
484 pub fn images_in(&self, ids: &[u64]) -> Vec<OutgoingImage> {
485 ids.iter()
486 .filter_map(|id| {
487 let item = self.items.iter().find(|item| item.id == *id)?;
488 match &item.kind {
489 ItemKind::Image { image, dimensions } => {
490 Some(OutgoingImage::Inline(InlineImage {
491 name: item.name.clone(),
492 image: image.clone(),
493 dimensions: *dimensions,
494 }))
495 }
496 ItemKind::Remote(remote) => Some(OutgoingImage::Remote(remote.clone())),
497 _ => None,
498 }
499 })
500 .collect()
501 }
502
503 pub fn discard_images_except(&mut self, kept: &[u64]) {
504 self.items
505 .retain(|item| !item.kind.is_object() || kept.contains(&item.id));
506 }
507
508 pub fn outgoing_files(&self) -> Vec<OutgoingFile> {
509 self.items
510 .iter()
511 .filter_map(|item| match &item.kind {
512 ItemKind::File {
513 upload: UploadState::Done(done),
514 ..
515 } => Some(OutgoingFile {
516 name: item.name.clone(),
517 size: item.size,
518 kind: FileKind::from_name(&item.name),
519 reference: done.reference.clone(),
520 uploaded: done.uploaded.clone(),
521 }),
522 _ => None,
523 })
524 .collect()
525 }
526
527 fn kind_of_mut(&mut self, id: u64) -> Option<&mut ItemKind> {
528 self.items
529 .iter_mut()
530 .find(|item| item.id == id)
531 .map(|item| &mut item.kind)
532 }
533}
534
535pub fn display_name(path: &Path) -> String {
536 path.file_name()
537 .map(|name| name.to_string_lossy().into_owned())
538 .unwrap_or_else(|| path.to_string_lossy().into_owned())
539}
540
541pub fn discard_uploaded(engine: Option<Arc<crate::backend::Engine>>, files: Vec<UploadedFile>) {
542 let Some(engine) = engine else {
543 return;
544 };
545 for file in files {
546 let engine = engine.clone();
547 drop(crate::runtime::spawn(async move {
548 let _ = engine.discard_attachment(&file).await;
549 }));
550 }
551}
552
553pub fn names_of(paths: &[PathBuf]) -> Vec<String> {
554 paths.iter().map(|path| display_name(path)).collect()
555}
556
557pub fn read_attachment(path: &Path) -> Result<LoadedFile, String> {
558 let name = display_name(path);
559 let unreadable = || format!("Could not read {name}.");
560 let metadata = std::fs::metadata(path).map_err(|_| unreadable())?;
561 if !metadata.is_file() {
562 return Err(unreadable());
563 }
564 if metadata.len() > MAX_FILE_BYTES {
565 return Err(format!(
566 "{name} is larger than {} MB.",
567 MAX_FILE_BYTES / (1024 * 1024)
568 ));
569 }
570 let bytes = std::fs::read(path).map_err(|_| unreadable())?;
571 if bytes.is_empty() {
572 return Err(format!("{name} is empty."));
573 }
574 Ok(LoadedFile::new(bytes))
575}
576
577pub fn pasted_image_name() -> String {
578 format!("{PASTED_IMAGE_STEM}.png")
579}
580
581/// Formats the app cannot send inline (bitmaps from the Windows clipboard) become PNG.
582pub fn prepare_pasted_image(pasted: Image) -> Result<LoadedFile, String> {
583 let unreadable = || format!("Could not read {}.", pasted_image_name());
584 let extension = match pasted.format {
585 ImageFormat::Png => "png",
586 ImageFormat::Jpeg => "jpg",
587 ImageFormat::Gif => "gif",
588 ImageFormat::Webp => "webp",
589 ImageFormat::Bmp => {
590 let decoded =
591 image::load_from_memory_with_format(&pasted.bytes, image::ImageFormat::Bmp)
592 .map_err(|_| unreadable())?;
593 let mut png = Vec::new();
594 decoded
595 .write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png)
596 .map_err(|_| unreadable())?;
597 return Ok(LoadedFile {
598 file_name: Some(pasted_image_name()),
599 ..LoadedFile::new(png)
600 });
601 }
602 _ => return Err(unreadable()),
603 };
604 Ok(LoadedFile {
605 file_name: Some(format!("{PASTED_IMAGE_STEM}.{extension}")),
606 ..LoadedFile::new(pasted.bytes)
607 })
608}
609
610#[derive(Debug, Clone, PartialEq)]
611pub enum PasteAction {
612 Text,
613 Files(Vec<PathBuf>),
614 Image(Image),
615}
616
617/// Office and browser copies carry text next to a bitmap; the text is what was meant.
618pub fn paste_action(item: &ClipboardItem) -> PasteAction {
619 let mut pasted = None;
620 for entry in item.entries() {
621 match entry {
622 ClipboardEntry::ExternalPaths(paths) if !paths.paths().is_empty() => {
623 return PasteAction::Files(paths.paths().to_vec());
624 }
625 ClipboardEntry::Image(found)
626 if pasted.is_none() && found.format != ImageFormat::Svg =>
627 {
628 pasted = Some(found.clone());
629 }
630 _ => {}
631 }
632 }
633 let has_text = item.text().is_some_and(|text| !text.trim().is_empty());
634 match pasted {
635 Some(image) if !has_text => PasteAction::Image(image),
636 _ => PasteAction::Text,
637 }
638}
639
640#[derive(Debug, Clone, Copy, PartialEq, Eq)]
641pub enum Tone {
642 Muted,
643 Danger,
644}
645
646#[derive(Debug, Clone, PartialEq, Eq)]
647pub struct ChipState {
648 pub subtitle: String,
649 pub tone: Tone,
650 pub progress: Option<u8>,
651 pub failed: bool,
652}
653
654pub fn chip_state(item: &TrayItem) -> ChipState {
655 let size = format::file_size_label(item.size);
656 let muted = |subtitle: String| ChipState {
657 subtitle,
658 tone: Tone::Muted,
659 progress: None,
660 failed: false,
661 };
662 match &item.kind {
663 ItemKind::Reading => muted("Reading ...".to_owned()),
664 ItemKind::Image { .. } | ItemKind::Remote(_) => muted(size),
665 ItemKind::File {
666 upload,
667 sent_as_file,
668 ..
669 } => match upload {
670 UploadState::Uploading(percent) => ChipState {
671 progress: Some(*percent),
672 ..muted(format!("Uploading {percent} %"))
673 },
674 UploadState::Sharing(_) => ChipState {
675 progress: Some(100),
676 ..muted("Uploading 100 %".to_owned())
677 },
678 UploadState::Done(_) if *sent_as_file => muted(format!("{size}, sent as file")),
679 UploadState::Done(_) => muted(size),
680 UploadState::Failed => ChipState {
681 tone: Tone::Danger,
682 failed: true,
683 ..muted("Upload failed.".to_owned())
684 },
685 UploadState::ShareFailed(_) => ChipState {
686 tone: Tone::Danger,
687 failed: true,
688 ..muted("Sharing failed.".to_owned())
689 },
690 },
691 }
692}
693
694type ItemAction<T> = fn(&mut T, u64, &mut Window, &mut Context<T>);
695
696fn remove_button<T: 'static>(id: u64, remove: ItemAction<T>, cx: &mut Context<T>) -> Stateful<Div> {
697 div()
698 .id(ElementId::Name(format!("attachment-remove-{id}").into()))
699 .size(px(CHIP_REMOVE_SIZE))
700 .flex_none()
701 .flex()
702 .items_center()
703 .justify_center()
704 .rounded(px(7.))
705 .cursor_pointer()
706 .hover(|button| button.bg(theme::popup_hover()))
707 .child(icon(IconName::Close, 14., theme::text_muted()))
708 .on_click(cx.listener(move |this, _, window, cx| remove(this, id, window, cx)))
709}
710
711pub fn preview_size(dimensions: Option<(u32, u32)>, available_width: f32) -> (f32, f32) {
712 let (width, height) = dimensions
713 .filter(|(width, height)| *width > 0 && *height > 0)
714 .map_or((PREVIEW_HEIGHT, PREVIEW_HEIGHT), |(width, height)| {
715 (width as f32, height as f32)
716 });
717 let scale = (PREVIEW_HEIGHT / height)
718 .min(available_width / width)
719 .clamp(0., 1.);
720 (
721 (width * scale).round().max(1.),
722 (height * scale).round().max(1.),
723 )
724}
725
726pub fn preview_row_height(height: f32) -> f32 {
727 height + 2. * PREVIEW_GAP
728}
729
730pub fn inline_preview(
731 id: u64,
732 preview: Option<PreviewImage>,
733 available_width: Pixels,
734 selected: bool,
735 remove: RemoveImage,
736) -> AnyElement {
737 let dimensions = preview.as_ref().and_then(PreviewImage::dimensions);
738 let (width, height) = preview_size(dimensions, f32::from(available_width));
739 let group = SharedString::from(format!("image-preview-{id}"));
740 let frame = div()
741 .relative()
742 .size_full()
743 .rounded(px(PREVIEW_RADIUS))
744 .overflow_hidden()
745 .bg(theme::popup_hover());
746 let frame = match preview {
747 Some(preview) => {
748 let source = match preview {
749 PreviewImage::Inline { image, .. } => ImageSource::from(image),
750 PreviewImage::Remote(remote) => image_source(&remote.url),
751 };
752 frame.child(
753 img(source)
754 .size_full()
755 .rounded(px(PREVIEW_RADIUS))
756 .object_fit(ObjectFit::Cover),
757 )
758 }
759 None => frame,
760 };
761 div()
762 .group(group.clone())
763 .w(px(width))
764 .h(px(preview_row_height(height)))
765 .py(px(PREVIEW_GAP))
766 .child(
767 frame
768 .when(selected, |frame| {
769 frame.child(
770 div()
771 .absolute()
772 .inset_0()
773 .rounded(px(PREVIEW_RADIUS))
774 .border_2()
775 .border_color(theme::accent()),
776 )
777 })
778 .child(
779 div()
780 .id(ElementId::Name(format!("image-remove-{id}").into()))
781 .absolute()
782 .top(px(6.))
783 .right(px(6.))
784 .size(px(REMOVE_SIZE))
785 .flex()
786 .items_center()
787 .justify_center()
788 .rounded_full()
789 .cursor_pointer()
790 .bg(black().opacity(0.6))
791 .opacity(0.)
792 .group_hover(group, |button| button.opacity(1.))
793 .hover(|button| button.bg(black().opacity(0.85)))
794 .child(icon(IconName::Close, 10., white()))
795 .on_mouse_down(MouseButton::Left, |_, window, cx| {
796 window.prevent_default();
797 cx.stop_propagation();
798 })
799 .on_click(move |_, window, cx| remove(window, cx)),
800 ),
801 )
802 .into_any_element()
803}
804
805fn chip<T: 'static>(
806 item: &TrayItem,
807 remove: ItemAction<T>,
808 retry: ItemAction<T>,
809 cx: &mut Context<T>,
810) -> AnyElement {
811 let state = chip_state(item);
812 let id = item.id;
813 let subtitle_color = match state.tone {
814 Tone::Muted => theme::text_muted(),
815 Tone::Danger => theme::red(),
816 };
817 h_flex()
818 .id(ElementId::Name(format!("attachment-{id}").into()))
819 .relative()
820 .w(px(CHIP_WIDTH))
821 .h(px(CHIP_HEIGHT))
822 .flex_none()
823 .gap(px(12.))
824 .px(px(12.))
825 .items_center()
826 .rounded(px(10.))
827 .overflow_hidden()
828 .bg(theme::popup_hover())
829 .border_1()
830 .border_color(if state.failed {
831 theme::red()
832 } else {
833 transparent_black()
834 })
835 .child(file_badge(FileKind::from_name(&item.name), CHIP_BADGE_SIZE))
836 .child(
837 v_flex()
838 .flex_1()
839 .min_w_0()
840 .child(
841 div()
842 .truncate()
843 .text_size(px(12.5))
844 .text_color(theme::text())
845 .child(item.name.clone()),
846 )
847 .child(
848 div()
849 .truncate()
850 .text_size(px(11.))
851 .text_color(subtitle_color)
852 .child(state.subtitle),
853 ),
854 )
855 .when(state.failed, |chip| {
856 chip.child(
857 div()
858 .id(ElementId::Name(format!("attachment-retry-{id}").into()))
859 .flex_none()
860 .text_size(px(12.))
861 .font_weight(FontWeight::SEMIBOLD)
862 .text_color(theme::accent_text())
863 .cursor_pointer()
864 .hover(|button| button.underline())
865 .child("Retry")
866 .on_click(cx.listener(move |this, _, window, cx| retry(this, id, window, cx))),
867 )
868 })
869 .child(remove_button(id, remove, cx))
870 .when_some(state.progress, |chip, percent| {
871 chip.child(
872 div()
873 .absolute()
874 .left_0()
875 .bottom_0()
876 .h(px(PROGRESS_HEIGHT))
877 .w(relative(f32::from(percent) / 100.))
878 .bg(theme::accent()),
879 )
880 })
881 .into_any_element()
882}
883
884pub fn render_tray<T: 'static>(
885 tray: &AttachmentTray,
886 remove: ItemAction<T>,
887 retry: ItemAction<T>,
888 cx: &mut Context<T>,
889) -> Option<Div> {
890 if !tray.has_chips() {
891 return None;
892 }
893 let elements: Vec<AnyElement> = tray
894 .items()
895 .iter()
896 .filter(|item| !item.kind.is_object())
897 .map(|item| chip(item, remove, retry, cx))
898 .collect();
899 Some(
900 h_flex()
901 .w_full()
902 .flex_wrap()
903 .gap(px(TRAY_GAP))
904 .px(px(8.))
905 .pt(px(8.))
906 .pb(px(2.))
907 .children(elements),
908 )
909}
910
911#[cfg(test)]
912mod tests {
913 use std::io::Cursor;
914 use std::path::PathBuf;
915
916 use super::JobKind;
917 use gpui_kit::{ClipboardEntry, ClipboardItem, ExternalPaths, Image, ImageFormat};
918 use teams_core::{FileKind, FileReference, UploadedFile};
919
920 use super::{
921 AttachmentTray, Classification, DoneFile, FILES_LATER_NOTICE, INLINE_IMAGE_MAX_BYTES,
922 INLINE_TOTAL_MAX_BYTES, InlineFormat, ItemKind, LoadedFile, MAX_ATTACHMENTS, OutgoingImage,
923 PasteAction, PreviewImage, RemoteImage, Tone, UploadResult, chip_state, classify,
924 limit_notice, paste_action, pasted_image_name, prepare_pasted_image, preview_size,
925 read_attachment, sniff_inline_format,
926 };
927 use crate::remote_image::RemoteKind;
928
929 const PNG_HEADER: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
930
931 fn png(width: u32, height: u32) -> Vec<u8> {
932 let mut bytes = Vec::new();
933 image::RgbaImage::new(width, height)
934 .write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png)
935 .unwrap();
936 bytes
937 }
938
939 fn padded(mut bytes: Vec<u8>, length: u64) -> Vec<u8> {
940 bytes.resize(length as usize, 0);
941 bytes
942 }
943
944 fn reference(name: &str) -> FileReference {
945 FileReference {
946 attachment_id: format!("id-{name}"),
947 content_url: format!("https://files.example/{name}"),
948 name: name.to_owned(),
949 }
950 }
951
952 fn done(name: &str) -> UploadResult {
953 UploadResult::Done(DoneFile {
954 reference: reference(name),
955 uploaded: None,
956 })
957 }
958
959 fn sample_upload() -> UploadedFile {
960 UploadedFile {
961 drive_id: "d".into(),
962 item_id: "i".into(),
963 name: "plan.pdf".into(),
964 web_url: "https://x".into(),
965 web_dav_url: None,
966 etag: "\"{G},1\"".into(),
967 }
968 }
969
970 fn names(count: usize) -> Vec<String> {
971 (0..count)
972 .map(|index| format!("file-{index}.pdf"))
973 .collect()
974 }
975
976 fn loaded_file(name: &str) -> LoadedFile {
977 LoadedFile {
978 file_name: Some(name.to_owned()),
979 ..LoadedFile::new(b"%PDF-1.7".to_vec())
980 }
981 }
982
983 fn tray_with_file() -> (AttachmentTray, u64) {
984 let mut tray = AttachmentTray::default();
985 let id = tray.add_pending(&["plan.pdf".to_owned()])[0];
986 tray.finish_reading(id, LoadedFile::new(b"%PDF-1.7".to_vec()), true);
987 (tray, id)
988 }
989
990 #[test]
991 fn magic_bytes_decide_the_inline_format() {
992 assert_eq!(sniff_inline_format(&png(1, 1)), Some(InlineFormat::Png));
993 assert_eq!(
994 sniff_inline_format(&[0xFF, 0xD8, 0xFF, 0xE0, 0]),
995 Some(InlineFormat::Jpeg)
996 );
997 assert_eq!(sniff_inline_format(b"GIF89a...."), Some(InlineFormat::Gif));
998 assert_eq!(
999 sniff_inline_format(b"RIFF\x10\0\0\0WEBPVP8 "),
1000 Some(InlineFormat::Webp)
1001 );
1002 assert_eq!(sniff_inline_format(b"BM......"), None);
1003 assert_eq!(sniff_inline_format(b"%PDF-1.7"), None);
1004 assert_eq!(sniff_inline_format(&[]), None);
1005 }
1006
1007 #[test]
1008 fn small_supported_images_are_inline() {
1009 assert_eq!(
1010 classify("shot.png", &png(2, 2), 0),
1011 Classification::Inline(InlineFormat::Png)
1012 );
1013 }
1014
1015 #[test]
1016 fn images_over_one_megabyte_become_files() {
1017 let at_limit = padded(PNG_HEADER.to_vec(), INLINE_IMAGE_MAX_BYTES);
1018 let over_limit = padded(PNG_HEADER.to_vec(), INLINE_IMAGE_MAX_BYTES + 1);
1019 assert_eq!(
1020 classify("a.png", &at_limit, 0),
1021 Classification::Inline(InlineFormat::Png)
1022 );
1023 assert_eq!(
1024 classify("a.png", &over_limit, 0),
1025 Classification::File { sent_as_file: true }
1026 );
1027 }
1028
1029 #[test]
1030 fn the_inline_total_is_capped_and_later_images_become_files() {
1031 let image = padded(PNG_HEADER.to_vec(), INLINE_IMAGE_MAX_BYTES);
1032 assert_eq!(
1033 classify(
1034 "a.png",
1035 &image,
1036 INLINE_TOTAL_MAX_BYTES - INLINE_IMAGE_MAX_BYTES
1037 ),
1038 Classification::Inline(InlineFormat::Png)
1039 );
1040 assert_eq!(
1041 classify(
1042 "a.png",
1043 &image,
1044 INLINE_TOTAL_MAX_BYTES - INLINE_IMAGE_MAX_BYTES + 1
1045 ),
1046 Classification::File { sent_as_file: true }
1047 );
1048 }
1049
1050 #[test]
1051 fn removing_an_inline_image_does_not_reclassify_the_others() {
1052 let big = || LoadedFile::new(padded(PNG_HEADER.to_vec(), INLINE_IMAGE_MAX_BYTES));
1053 let mut tray = AttachmentTray::default();
1054 let ids = tray.add_pending(&names(4));
1055 for id in &ids[..3] {
1056 tray.finish_reading(*id, big(), true);
1057 }
1058 let job = tray.finish_reading(ids[3], big(), true);
1059 assert!(
1060 job.is_some(),
1061 "the fourth 1 MiB image exceeds 2.5 MiB inline"
1062 );
1063 tray.remove(ids[0]);
1064 assert!(matches!(tray.items()[2].kind, ItemKind::File { .. }));
1065 }
1066
1067 #[test]
1068 fn a_failed_share_retries_only_the_share_and_keeps_the_upload() {
1069 let (mut tray, id) = tray_with_file();
1070 let uploaded = sample_upload();
1071 tray.finish_upload(id, UploadResult::ShareFailed(uploaded.clone()));
1072 let state = chip_state(&tray.items()[0]);
1073 assert_eq!(state.subtitle, "Sharing failed.");
1074 assert!(state.failed);
1075 assert!(tray.blocks_send());
1076 let job = tray.retry(id).unwrap();
1077 assert!(matches!(job.kind, JobKind::Share(ref file) if *file == uploaded));
1078 assert_eq!(tray.clear(), vec![uploaded.clone()]);
1079 let (mut tray, id) = tray_with_file();
1080 tray.finish_upload(id, UploadResult::ShareFailed(uploaded.clone()));
1081 tray.retry(id);
1082 tray.finish_upload(id, UploadResult::ShareFailed(uploaded.clone()));
1083 assert_eq!(tray.remove(id), Some(uploaded));
1084 }
1085
1086 #[test]
1087 fn an_item_being_shared_can_be_deleted_by_remove_or_clear() {
1088 let (mut tray, id) = tray_with_file();
1089 tray.mark_uploaded(id, sample_upload());
1090 assert_eq!(chip_state(&tray.items()[0]).subtitle, "Uploading 100 %");
1091 assert!(tray.blocks_send());
1092 tray.set_progress(id, 10);
1093 assert_eq!(chip_state(&tray.items()[0]).progress, Some(100));
1094 assert_eq!(tray.remove(id), Some(sample_upload()));
1095
1096 let (mut tray, id) = tray_with_file();
1097 tray.mark_uploaded(id, sample_upload());
1098 tray.finish_upload(id, UploadResult::ShareFailed(sample_upload()));
1099 assert!(chip_state(&tray.items()[0]).failed);
1100 assert_eq!(tray.keep_images_only(), vec![sample_upload()]);
1101 }
1102
1103 #[test]
1104 fn events_for_a_removed_item_hand_the_upload_back_for_deletion() {
1105 let (mut tray, id) = tray_with_file();
1106 tray.remove(id);
1107 assert_eq!(
1108 tray.mark_uploaded(id, sample_upload()),
1109 Some(sample_upload())
1110 );
1111 let done = UploadResult::Done(DoneFile {
1112 reference: reference("plan.pdf"),
1113 uploaded: Some(sample_upload()),
1114 });
1115 assert_eq!(tray.finish_upload(id, done), Some(sample_upload()));
1116 assert_eq!(
1117 tray.finish_upload(id, UploadResult::ShareFailed(sample_upload())),
1118 Some(sample_upload())
1119 );
1120 assert_eq!(tray.finish_upload(id, UploadResult::Failed), None);
1121 }
1122
1123 #[test]
1124 fn events_for_a_live_item_are_never_handed_back() {
1125 let (mut tray, id) = tray_with_file();
1126 assert_eq!(tray.mark_uploaded(id, sample_upload()), None);
1127 assert_eq!(tray.finish_upload(id, done("plan.pdf")), None);
1128 assert_eq!(tray.finish_upload(id, done("plan.pdf")), None);
1129 }
1130
1131 #[test]
1132 fn removing_or_clearing_reports_the_uploads_that_were_never_sent() {
1133 let (mut tray, id) = tray_with_file();
1134 tray.finish_upload(
1135 id,
1136 UploadResult::Done(DoneFile {
1137 reference: reference("plan.pdf"),
1138 uploaded: Some(sample_upload()),
1139 }),
1140 );
1141 assert_eq!(tray.clear(), vec![sample_upload()]);
1142 let (mut other, other_id) = tray_with_file();
1143 assert_eq!(other.remove(other_id), None);
1144 }
1145
1146 #[test]
1147 fn other_image_formats_become_files_with_the_note() {
1148 assert_eq!(
1149 classify("scan.bmp", b"BM......", 0),
1150 Classification::File { sent_as_file: true }
1151 );
1152 assert_eq!(
1153 classify("photo.HEIC", b"....ftypheic", 0),
1154 Classification::File { sent_as_file: true }
1155 );
1156 assert_eq!(
1157 classify("plan.pdf", b"%PDF-1.7", 0),
1158 Classification::File {
1159 sent_as_file: false
1160 }
1161 );
1162 }
1163
1164 #[test]
1165 fn dimensions_come_from_the_headers() {
1166 assert_eq!(LoadedFile::new(png(7, 3)).dimensions, Some((7, 3)));
1167 let mut gif = b"GIF89a".to_vec();
1168 gif.extend_from_slice(&[10, 0, 20, 0]);
1169 assert_eq!(LoadedFile::new(gif).dimensions, Some((10, 20)));
1170 assert_eq!(LoadedFile::new(b"%PDF".to_vec()).dimensions, None);
1171 }
1172
1173 #[test]
1174 fn the_tenth_attachment_fits_and_the_rest_are_dropped() {
1175 let mut tray = AttachmentTray::default();
1176 assert_eq!(tray.add_pending(&names(4)).len(), 4);
1177 let ids = tray.add_pending(&names(9));
1178 assert_eq!(ids.len(), 6);
1179 assert_eq!(tray.items().len(), MAX_ATTACHMENTS);
1180 assert_eq!(
1181 tray.notice(),
1182 Some("Up to 10 attachments per message. 3 files were not added.")
1183 );
1184 }
1185
1186 #[test]
1187 fn one_dropped_file_reads_in_the_singular() {
1188 assert_eq!(
1189 limit_notice(1),
1190 "Up to 10 attachments per message. 1 file was not added."
1191 );
1192 }
1193
1194 #[test]
1195 fn the_limit_notice_clears_on_the_next_change() {
1196 let mut tray = AttachmentTray::default();
1197 let ids = tray.add_pending(&names(12));
1198 assert!(tray.notice().is_some());
1199 tray.remove(ids[0]);
1200 assert_eq!(tray.notice(), None);
1201 tray.add_pending(&names(3));
1202 assert!(tray.notice().is_some());
1203 tray.clear();
1204 assert_eq!(tray.notice(), None);
1205 }
1206
1207 #[test]
1208 fn a_file_starts_uploading_and_an_image_does_not() {
1209 let mut tray = AttachmentTray::default();
1210 let ids = tray.add_pending(&["a.pdf".to_owned(), "b.png".to_owned()]);
1211 let job = tray.finish_reading(ids[0], LoadedFile::new(b"%PDF".to_vec()), true);
1212 assert_eq!(job.as_ref().map(|job| job.name.as_str()), Some("a.pdf"));
1213 assert!(
1214 tray.finish_reading(ids[1], LoadedFile::new(png(2, 2)), true)
1215 .is_none()
1216 );
1217 assert!(matches!(tray.items()[1].kind, ItemKind::Image { .. }));
1218 assert!(tray.blocks_send());
1219 }
1220
1221 #[test]
1222 fn a_pasted_name_replaces_the_placeholder() {
1223 let mut tray = AttachmentTray::default();
1224 let id = tray.add_pending(&[pasted_image_name()])[0];
1225 let loaded = LoadedFile {
1226 file_name: Some("pasted-image.jpg".into()),
1227 ..LoadedFile::new(vec![0xFF, 0xD8, 0xFF, 0xE0])
1228 };
1229 tray.finish_reading(id, loaded, true);
1230 assert_eq!(tray.items()[0].name, "pasted-image.jpg");
1231 }
1232
1233 #[test]
1234 fn files_are_refused_while_the_chat_does_not_exist() {
1235 let mut tray = AttachmentTray::default();
1236 let ids = tray.add_pending(&["a.pdf".to_owned(), "b.png".to_owned()]);
1237 assert!(
1238 tray.finish_reading(ids[0], loaded_file("a.pdf"), false)
1239 .is_none()
1240 );
1241 tray.finish_reading(ids[1], LoadedFile::new(png(2, 2)), false);
1242 assert_eq!(tray.items().len(), 1);
1243 assert_eq!(tray.notice(), Some(FILES_LATER_NOTICE));
1244 assert!(!tray.blocks_send());
1245 }
1246
1247 #[test]
1248 fn upload_progress_then_done_unblocks_sending() {
1249 let (mut tray, id) = tray_with_file();
1250 tray.set_progress(id, 42);
1251 assert_eq!(chip_state(&tray.items()[0]).subtitle, "Uploading 42 %");
1252 assert_eq!(chip_state(&tray.items()[0]).progress, Some(42));
1253 assert!(tray.blocks_send());
1254 tray.finish_upload(id, done("plan.pdf"));
1255 assert!(!tray.blocks_send());
1256 assert_eq!(tray.outgoing_files().len(), 1);
1257 assert_eq!(
1258 tray.outgoing_files()[0].kind,
1259 FileKind::from_name("plan.pdf")
1260 );
1261 }
1262
1263 #[test]
1264 fn progress_after_the_upload_ended_is_ignored() {
1265 let (mut tray, id) = tray_with_file();
1266 tray.finish_upload(id, done("plan.pdf"));
1267 tray.set_progress(id, 10);
1268 tray.finish_upload(id, UploadResult::Failed);
1269 assert!(!tray.blocks_send());
1270 }
1271
1272 #[test]
1273 fn a_failed_upload_blocks_sending_until_it_is_retried_or_removed() {
1274 let (mut tray, id) = tray_with_file();
1275 tray.finish_upload(id, UploadResult::Failed);
1276 let state = chip_state(&tray.items()[0]);
1277 assert_eq!(state.subtitle, "Upload failed.");
1278 assert_eq!(state.tone, Tone::Danger);
1279 assert!(state.failed);
1280 assert!(tray.blocks_send());
1281 assert!(tray.outgoing_files().is_empty());
1282
1283 let job = tray.retry(id).expect("failed uploads can be retried");
1284 assert_eq!(job.name, "plan.pdf");
1285 assert_eq!(chip_state(&tray.items()[0]).subtitle, "Uploading 0 %");
1286 assert!(tray.retry(id).is_none());
1287
1288 tray.finish_upload(id, UploadResult::Failed);
1289 tray.remove(id);
1290 assert!(!tray.blocks_send());
1291 }
1292
1293 #[test]
1294 fn a_result_for_a_removed_item_is_dropped() {
1295 let (mut tray, id) = tray_with_file();
1296 tray.remove(id);
1297 tray.finish_upload(id, done("plan.pdf"));
1298 assert!(tray.items().is_empty());
1299 }
1300
1301 #[test]
1302 fn done_chips_show_the_size_and_the_file_note() {
1303 let mut tray = AttachmentTray::default();
1304 let id = tray.add_pending(&["scan.bmp".to_owned()])[0];
1305 tray.finish_reading(id, LoadedFile::new(b"BM....".to_vec()), true);
1306 tray.finish_upload(id, done("scan.bmp"));
1307 assert_eq!(chip_state(&tray.items()[0]).subtitle, "6 B, sent as file");
1308 let (mut other, other_id) = tray_with_file();
1309 other.finish_upload(other_id, done("plan.pdf"));
1310 assert_eq!(chip_state(&other.items()[0]).subtitle, "8 B");
1311 }
1312
1313 #[test]
1314 fn restore_brings_back_images_and_uploaded_files() {
1315 let mut source = AttachmentTray::default();
1316 let ids = source.add_pending(&["a.png".to_owned(), "b.pdf".to_owned()]);
1317 source.finish_reading(ids[0], LoadedFile::new(png(4, 2)), true);
1318 source.finish_reading(ids[1], LoadedFile::new(b"%PDF".to_vec()), true);
1319 source.finish_upload(ids[1], done("b.pdf"));
1320 let (images, files) = (source.images_in(&ids[..1]), source.outgoing_files());
1321
1322 let mut restored = AttachmentTray::default();
1323 let image_ids = restored.restore(&images, &files);
1324 assert_eq!(image_ids.len(), 1);
1325 assert_eq!(restored.images_in(&image_ids), images);
1326 assert_eq!(restored.outgoing_files(), files);
1327 assert!(!restored.blocks_send());
1328 }
1329
1330 fn gif(title: &str) -> RemoteImage {
1331 RemoteImage {
1332 kind: RemoteKind::Gif,
1333 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
1334 title: title.into(),
1335 width: 200,
1336 height: 100,
1337 }
1338 }
1339
1340 #[test]
1341 fn a_remote_image_is_an_object_without_a_chip_and_never_blocks_sending() {
1342 let mut tray = AttachmentTray::default();
1343 let id = tray.add_remote(gif("Wave")).unwrap();
1344 assert!(!tray.has_chips());
1345 assert!(!tray.blocks_send());
1346 assert!(matches!(tray.image(id), Some(PreviewImage::Remote(_))));
1347 let images = tray.images_in(&[id]);
1348 assert_eq!(images, vec![OutgoingImage::Remote(gif("Wave"))]);
1349 let mut restored = AttachmentTray::default();
1350 let ids = restored.restore(&images, &[]);
1351 assert_eq!(restored.images_in(&ids), images);
1352 assert_eq!(tray.keep_images_only(), Vec::new());
1353 assert_eq!(tray.items().len(), 1);
1354 }
1355
1356 #[test]
1357 fn a_full_tray_refuses_another_remote_image() {
1358 let mut tray = AttachmentTray::default();
1359 for _ in 0..MAX_ATTACHMENTS {
1360 assert!(tray.add_remote(gif("Wave")).is_some());
1361 }
1362 assert!(tray.add_remote(gif("Wave")).is_none());
1363 assert!(tray.notice().is_some());
1364 }
1365
1366 #[test]
1367 fn images_come_back_in_the_order_asked_for_and_only_when_known() {
1368 let mut tray = AttachmentTray::default();
1369 let ids = tray.add_pending(&["a.png".to_owned(), "b.png".to_owned()]);
1370 tray.finish_reading(ids[0], LoadedFile::new(png(2, 2)), true);
1371 tray.finish_reading(ids[1], LoadedFile::new(png(4, 4)), true);
1372 let images = tray.images_in(&[ids[1], 99, ids[0]]);
1373 assert_eq!(images.len(), 2);
1374 let dimensions: Vec<_> = images
1375 .iter()
1376 .map(|image| match image {
1377 OutgoingImage::Inline(inline) => inline.dimensions,
1378 OutgoingImage::Remote(_) => None,
1379 })
1380 .collect();
1381 assert_eq!(dimensions, [Some((4, 4)), Some((2, 2))]);
1382 assert!(!tray.has_chips());
1383 tray.discard_images_except(&[ids[1]]);
1384 assert_eq!(tray.items().len(), 1);
1385 assert!(tray.image(ids[1]).is_some());
1386 assert!(tray.image(ids[0]).is_none());
1387 }
1388
1389 #[test]
1390 fn previews_are_at_most_120_high_and_fit_the_row() {
1391 assert_eq!(preview_size(Some((400, 300)), 800.), (160., 120.));
1392 assert_eq!(preview_size(Some((40, 30)), 800.), (40., 30.));
1393 assert_eq!(preview_size(Some((1000, 100)), 250.), (250., 25.));
1394 assert_eq!(preview_size(None, 800.), (120., 120.));
1395 assert_eq!(preview_size(Some((400, 300)), 0.), (1., 1.));
1396 }
1397
1398 #[test]
1399 fn switching_chats_for_a_draft_keeps_only_images() {
1400 let mut tray = AttachmentTray::default();
1401 let ids = tray.add_pending(&["a.png".to_owned(), "b.pdf".to_owned()]);
1402 tray.finish_reading(ids[0], LoadedFile::new(png(2, 2)), true);
1403 tray.finish_reading(ids[1], LoadedFile::new(b"%PDF".to_vec()), true);
1404 tray.keep_images_only();
1405 assert_eq!(tray.items().len(), 1);
1406 assert!(matches!(tray.items()[0].kind, ItemKind::Image { .. }));
1407 }
1408
1409 #[test]
1410 fn a_failed_read_removes_the_item_and_says_why() {
1411 let mut tray = AttachmentTray::default();
1412 let id = tray.add_pending(&["gone.txt".to_owned()])[0];
1413 tray.fail_reading(id, "Could not read gone.txt.".to_owned());
1414 assert!(tray.items().is_empty());
1415 assert_eq!(tray.notice(), Some("Could not read gone.txt."));
1416 }
1417
1418 #[test]
1419 fn reading_items_block_sending() {
1420 let mut tray = AttachmentTray::default();
1421 tray.add_pending(&["a.pdf".to_owned()]);
1422 assert!(tray.blocks_send());
1423 assert_eq!(chip_state(&tray.items()[0]).subtitle, "Reading ...");
1424 }
1425
1426 #[test]
1427 fn files_are_read_from_disk_with_their_limits() {
1428 let directory = tempfile::tempdir().unwrap();
1429 let file = directory.path().join("note.txt");
1430 std::fs::write(&file, b"hello").unwrap();
1431 let empty = directory.path().join("empty.txt");
1432 std::fs::write(&empty, b"").unwrap();
1433
1434 assert_eq!(read_attachment(&file).unwrap().bytes, b"hello");
1435 assert_eq!(read_attachment(&empty).unwrap_err(), "empty.txt is empty.");
1436 assert!(
1437 read_attachment(directory.path())
1438 .unwrap_err()
1439 .ends_with('.')
1440 );
1441 assert_eq!(
1442 read_attachment(&directory.path().join("missing.txt")).unwrap_err(),
1443 "Could not read missing.txt."
1444 );
1445 }
1446
1447 fn clipboard(entries: Vec<ClipboardEntry>) -> ClipboardItem {
1448 ClipboardItem { entries }
1449 }
1450
1451 fn pasted_png() -> Image {
1452 Image::from_bytes(ImageFormat::Png, png(2, 2))
1453 }
1454
1455 #[test]
1456 fn pasting_an_image_alone_adds_an_image() {
1457 let item = clipboard(vec![ClipboardEntry::Image(pasted_png())]);
1458 assert_eq!(paste_action(&item), PasteAction::Image(pasted_png()));
1459 }
1460
1461 #[test]
1462 fn pasting_copied_files_adds_those_files() {
1463 let paths = ExternalPaths(vec![PathBuf::from("/a/b.pdf")].into_iter().collect());
1464 let item = clipboard(vec![ClipboardEntry::ExternalPaths(paths)]);
1465 assert_eq!(
1466 paste_action(&item),
1467 PasteAction::Files(vec![PathBuf::from("/a/b.pdf")])
1468 );
1469 }
1470
1471 #[test]
1472 fn pasting_text_or_text_with_a_bitmap_stays_text() {
1473 assert_eq!(
1474 paste_action(&ClipboardItem::new_string("hi".into())),
1475 PasteAction::Text
1476 );
1477 let both = clipboard(vec![
1478 ClipboardEntry::from("cells".to_owned()),
1479 ClipboardEntry::Image(pasted_png()),
1480 ]);
1481 assert_eq!(paste_action(&both), PasteAction::Text);
1482 assert_eq!(paste_action(&clipboard(Vec::new())), PasteAction::Text);
1483 }
1484
1485 #[test]
1486 fn a_pasted_bitmap_becomes_a_png() {
1487 let mut bmp = Vec::new();
1488 image::RgbaImage::new(3, 2)
1489 .write_to(&mut Cursor::new(&mut bmp), image::ImageFormat::Bmp)
1490 .unwrap();
1491 let loaded = prepare_pasted_image(Image::from_bytes(ImageFormat::Bmp, bmp)).unwrap();
1492 assert_eq!(sniff_inline_format(&loaded.bytes), Some(InlineFormat::Png));
1493 assert_eq!(loaded.dimensions, Some((3, 2)));
1494 assert_eq!(loaded.file_name.as_deref(), Some("pasted-image.png"));
1495 }
1496
1497 #[test]
1498 fn a_pasted_png_keeps_its_bytes() {
1499 let loaded = prepare_pasted_image(pasted_png()).unwrap();
1500 assert_eq!(loaded.bytes, png(2, 2));
1501 assert_eq!(loaded.file_name.as_deref(), Some("pasted-image.png"));
1502 }
1503}