BlueGit

ict rusty-teams

Files

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

attachment_tray.rs

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