BlueGit

ict rusty-teams

Files

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

attachment_tray.rs

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