BlueGit

ict rusty-teams

Files

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

attachment_tray.rs

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