BlueGit

ict rusty-teams

Files

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

attachment_tray.rs

attachment_tray.rs 54.8 KiB Download Raw
1use std::io::Cursor;
2use std::path::{Path, PathBuf};
3use std::rc::Rc;
4use std::sync::Arc;
5
6use gpui_kit::assets::IconName;
7use gpui_kit::component::{h_flex, v_flex};
8use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::*;
10use teams_core::{FileKind, FileReference, UploadedFile};
11
12use super::attachments::{file_badge, kind_description};
13use super::widgets::icon;
14use crate::format;
15use crate::inline_image::{InlineFormat, image_dimensions, sniff_inline_format};
16pub use crate::outgoing::{InlineImage, OutgoingFile, OutgoingImage};
17use crate::remote_image::{RemoteImage, image_source};
18use crate::theme;
19
20pub const MAX_ATTACHMENTS: usize = 10;
21pub const INLINE_IMAGE_MAX_BYTES: u64 = 1024 * 1024;
22pub const INLINE_TOTAL_MAX_BYTES: u64 = 5 * 512 * 1024;
23pub const MAX_FILE_BYTES: u64 = 250 * 1024 * 1024;
24pub const FILES_LATER_NOTICE: &str = "Files can be added once the chat exists.";
25pub const NOT_SHARED_NOTICE: &str =
26 "Your organization does not allow sharing with this chat. People may need to request access.";
27const PASTED_IMAGE_STEM: &str = "pasted-image";
28const PREVIEW_HEIGHT: f32 = 120.;
29const PREVIEW_GAP: f32 = 4.;
30const PREVIEW_RADIUS: f32 = 10.;
31const CHIP_WIDTH: f32 = 220.;
32const CHIP_HEIGHT: f32 = 52.;
33const CHIP_BADGE_SIZE: f32 = 30.;
34const REMOVE_SIZE: f32 = 18.;
35const CHIP_REMOVE_SIZE: f32 = 28.;
36const TRAY_GAP: f32 = 8.;
37const PROGRESS_HEIGHT: f32 = 2.;
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum Classification {
41 Inline(InlineFormat),
42 File { sent_as_file: bool },
43}
44
45/// `inline_used` is the raw bytes of the images already inline in the tray.
46pub fn classify(name: &str, bytes: &[u8], inline_used: u64) -> Classification {
47 let size = bytes.len() as u64;
48 match sniff_inline_format(bytes) {
49 Some(format)
50 if size <= INLINE_IMAGE_MAX_BYTES && inline_used + size <= INLINE_TOTAL_MAX_BYTES =>
51 {
52 Classification::Inline(format)
53 }
54 Some(_) => Classification::File { sent_as_file: true },
55 None => Classification::File {
56 sent_as_file: FileKind::from_name(name) == FileKind::Image,
57 },
58 }
59}
60
61pub fn inline_image(name: String, bytes: Vec<u8>) -> Option<InlineImage> {
62 let format = sniff_inline_format(&bytes)?;
63 let dimensions = image_dimensions(format, &bytes);
64 Some(InlineImage {
65 name,
66 image: Arc::new(Image::from_bytes(format.image_format(), bytes)),
67 dimensions,
68 })
69}
70
71pub fn limit_notice(dropped: usize) -> String {
72 let files = if dropped == 1 {
73 "1 file was".to_owned()
74 } else {
75 format!("{dropped} files were")
76 };
77 format!("Up to {MAX_ATTACHMENTS} attachments per message. {files} not added.")
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub enum UploadState {
82 Uploading(u8),
83 Done(DoneFile),
84 Failed,
85 Sharing(UploadedFile),
86 ShareFailed(UploadedFile),
87}
88
89/// `uploaded` is known for files the app uploaded, so an unsent one can be deleted again.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct DoneFile {
92 pub reference: FileReference,
93 pub uploaded: Option<UploadedFile>,
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub enum UploadResult {
98 Done(DoneFile),
99 /// Sent without access for the chat members, like Teams does for a guest's file that the
100 /// home tenant may not share outside.
101 NotShared(DoneFile),
102 ShareFailed(UploadedFile),
103 Failed,
104}
105
106/// How a share ended, separate from the Graph error so the tray can be tested without a session.
107pub(crate) enum ShareEnd {
108 Linked(Option<String>),
109 Denied,
110 Failed,
111}
112
113pub(crate) fn result_of_share(
114 uploaded: UploadedFile,
115 mut reference: FileReference,
116 end: ShareEnd,
117) -> UploadResult {
118 match end {
119 ShareEnd::Linked(link) => {
120 if let Some(link) = link.filter(|link| !link.is_empty()) {
121 reference.content_url = link;
122 }
123 UploadResult::Done(DoneFile {
124 reference,
125 uploaded: Some(uploaded),
126 })
127 }
128 ShareEnd::Denied => UploadResult::NotShared(DoneFile {
129 reference,
130 uploaded: Some(uploaded),
131 }),
132 ShareEnd::Failed => UploadResult::ShareFailed(uploaded),
133 }
134}
135
136impl UploadState {
137 fn uploaded(&self) -> Option<UploadedFile> {
138 match self {
139 UploadState::Done(done) => done.uploaded.clone(),
140 UploadState::Sharing(uploaded) | UploadState::ShareFailed(uploaded) => {
141 Some(uploaded.clone())
142 }
143 _ => None,
144 }
145 }
146}
147
148#[derive(Debug, Clone)]
149#[allow(clippy::large_enum_variant)]
150pub enum ItemKind {
151 Reading,
152 Image {
153 image: Arc<Image>,
154 dimensions: Option<(u32, u32)>,
155 },
156 Remote(RemoteImage),
157 File {
158 bytes: Arc<Vec<u8>>,
159 upload: UploadState,
160 sent_as_file: bool,
161 },
162}
163
164#[derive(Debug, Clone)]
165pub struct TrayItem {
166 pub id: u64,
167 pub name: String,
168 pub size: u64,
169 pub kind: ItemKind,
170}
171
172impl ItemKind {
173 /// Shown inline in the text instead of as a chip.
174 fn is_object(&self) -> bool {
175 matches!(self, ItemKind::Image { .. } | ItemKind::Remote(_))
176 }
177
178 fn is_custom_emoji(&self) -> bool {
179 matches!(self, ItemKind::Remote(remote) if remote.is_custom_emoji())
180 }
181}
182
183impl AttachmentTray {
184 pub fn attachment_count(&self) -> usize {
185 self.items
186 .iter()
187 .filter(|item| !item.kind.is_custom_emoji())
188 .count()
189 }
190}
191
192impl TrayItem {
193 fn blocks_send(&self) -> bool {
194 match &self.kind {
195 ItemKind::Reading => true,
196 ItemKind::Image { .. } | ItemKind::Remote(_) => false,
197 ItemKind::File { upload, .. } => !matches!(upload, UploadState::Done(_)),
198 }
199 }
200}
201
202#[derive(Debug, Clone)]
203pub enum PreviewImage {
204 Inline {
205 image: Arc<Image>,
206 dimensions: Option<(u32, u32)>,
207 },
208 Remote(RemoteImage),
209}
210
211impl PreviewImage {
212 fn dimensions(&self) -> Option<(u32, u32)> {
213 match self {
214 PreviewImage::Inline { dimensions, .. } => *dimensions,
215 PreviewImage::Remote(remote) => Some((remote.width, remote.height)),
216 }
217 }
218}
219
220pub type RemoveImage = Rc<dyn Fn(&mut Window, &mut App)>;
221
222#[derive(Debug, Clone)]
223pub enum JobKind {
224 Upload,
225 Share(UploadedFile),
226}
227
228#[derive(Debug, Clone)]
229pub struct UploadJob {
230 pub id: u64,
231 pub name: String,
232 pub bytes: Arc<Vec<u8>>,
233 pub kind: JobKind,
234}
235
236#[derive(Debug, Clone, PartialEq, Eq)]
237pub struct LoadedFile {
238 pub bytes: Vec<u8>,
239 pub dimensions: Option<(u32, u32)>,
240 pub file_name: Option<String>,
241}
242
243impl LoadedFile {
244 pub fn new(bytes: Vec<u8>) -> Self {
245 let dimensions =
246 sniff_inline_format(&bytes).and_then(|format| image_dimensions(format, &bytes));
247 LoadedFile {
248 bytes,
249 dimensions,
250 file_name: None,
251 }
252 }
253}
254
255#[derive(Debug, Clone, Default)]
256pub struct AttachmentTray {
257 items: Vec<TrayItem>,
258 next_id: u64,
259 notice: Option<String>,
260}
261
262impl AttachmentTray {
263 pub fn items(&self) -> &[TrayItem] {
264 &self.items
265 }
266
267 pub fn has_chips(&self) -> bool {
268 self.items.iter().any(|item| !item.kind.is_object())
269 }
270
271 pub fn image(&self, id: u64) -> Option<PreviewImage> {
272 self.items.iter().find_map(|item| match &item.kind {
273 ItemKind::Image { image, dimensions } if item.id == id => Some(PreviewImage::Inline {
274 image: image.clone(),
275 dimensions: *dimensions,
276 }),
277 ItemKind::Remote(remote) if item.id == id => Some(PreviewImage::Remote(remote.clone())),
278 _ => None,
279 })
280 }
281
282 /// `None` when the tray is full.
283 pub fn add_remote(&mut self, remote: RemoteImage) -> Option<u64> {
284 self.notice = None;
285 if !remote.is_custom_emoji() && self.attachment_count() >= MAX_ATTACHMENTS {
286 self.notice = Some(limit_notice(1));
287 return None;
288 }
289 Some(self.push(remote.title.clone(), 0, ItemKind::Remote(remote)))
290 }
291
292 pub fn notice(&self) -> Option<&str> {
293 self.notice.as_deref()
294 }
295
296 pub fn blocks_send(&self) -> bool {
297 self.items.iter().any(TrayItem::blocks_send)
298 }
299
300 fn push(&mut self, name: String, size: u64, kind: ItemKind) -> u64 {
301 self.next_id += 1;
302 self.items.push(TrayItem {
303 id: self.next_id,
304 name,
305 size,
306 kind,
307 });
308 self.next_id
309 }
310
311 /// A file already in the cloud goes out by reference; it was never uploaded, so removing it deletes nothing.
312 pub fn add_cloud_file(
313 &mut self,
314 name: String,
315 size: u64,
316 reference: FileReference,
317 ) -> Option<u64> {
318 self.notice = None;
319 if self.attachment_count() >= MAX_ATTACHMENTS {
320 self.notice = Some(limit_notice(1));
321 return None;
322 }
323 let kind = ItemKind::File {
324 bytes: Arc::new(Vec::new()),
325 upload: UploadState::Done(DoneFile {
326 reference,
327 uploaded: None,
328 }),
329 sent_as_file: false,
330 };
331 Some(self.push(name, size, kind))
332 }
333
334 pub fn set_notice(&mut self, notice: String) {
335 self.notice = Some(notice);
336 }
337
338 /// Items beyond the limit are dropped; the ids returned belong to the first names.
339 pub fn add_pending(&mut self, names: &[String]) -> Vec<u64> {
340 self.notice = None;
341 let accepted = names
342 .len()
343 .min(MAX_ATTACHMENTS.saturating_sub(self.attachment_count()));
344 let ids = names[..accepted]
345 .iter()
346 .map(|name| self.push(name.clone(), 0, ItemKind::Reading))
347 .collect();
348 if accepted < names.len() {
349 self.notice = Some(limit_notice(names.len() - accepted));
350 }
351 ids
352 }
353
354 /// Returns the upload to start when the item turned out to be a file.
355 pub fn finish_reading(
356 &mut self,
357 id: u64,
358 loaded: LoadedFile,
359 files_allowed: bool,
360 ) -> Option<UploadJob> {
361 let position = self
362 .items
363 .iter()
364 .position(|item| item.id == id && matches!(item.kind, ItemKind::Reading))?;
365 let name = loaded
366 .file_name
367 .clone()
368 .unwrap_or_else(|| self.items[position].name.clone());
369 let size = loaded.bytes.len() as u64;
370 match classify(&name, &loaded.bytes, self.inline_bytes()) {
371 Classification::Inline(format) => {
372 let item = &mut self.items[position];
373 item.name = name;
374 item.size = size;
375 item.kind = ItemKind::Image {
376 image: Arc::new(Image::from_bytes(format.image_format(), loaded.bytes)),
377 dimensions: loaded.dimensions,
378 };
379 None
380 }
381 Classification::File { .. } if !files_allowed => {
382 self.items.remove(position);
383 self.notice = Some(FILES_LATER_NOTICE.to_owned());
384 None
385 }
386 Classification::File { sent_as_file } => {
387 let bytes = Arc::new(loaded.bytes);
388 let item = &mut self.items[position];
389 item.name = name.clone();
390 item.size = size;
391 item.kind = ItemKind::File {
392 bytes: bytes.clone(),
393 upload: UploadState::Uploading(0),
394 sent_as_file,
395 };
396 Some(UploadJob {
397 id,
398 name,
399 bytes,
400 kind: JobKind::Upload,
401 })
402 }
403 }
404 }
405
406 pub fn fail_reading(&mut self, id: u64, message: String) {
407 let before = self.items.len();
408 self.items.retain(|item| item.id != id);
409 if self.items.len() != before {
410 self.notice = Some(message);
411 }
412 }
413
414 pub fn set_progress(&mut self, id: u64, percent: u8) {
415 if let Some(ItemKind::File { upload, .. }) = self.kind_of_mut(id)
416 && matches!(upload, UploadState::Uploading(_))
417 {
418 *upload = UploadState::Uploading(percent.min(100));
419 }
420 }
421
422 /// The bytes are on the server; from here a remove or switch must delete the item.
423 /// Returns the file back when its item is gone, so the caller can delete it.
424 pub fn mark_uploaded(&mut self, id: u64, uploaded: UploadedFile) -> Option<UploadedFile> {
425 if !self.items.iter().any(|item| item.id == id) {
426 return Some(uploaded);
427 }
428 if let Some(ItemKind::File { upload, .. }) = self.kind_of_mut(id)
429 && matches!(upload, UploadState::Uploading(_))
430 {
431 *upload = UploadState::Sharing(uploaded);
432 }
433 None
434 }
435
436 /// Returns the uploaded file of a result whose item is gone, so the caller can delete it.
437 pub fn finish_upload(&mut self, id: u64, result: UploadResult) -> Option<UploadedFile> {
438 if !self.items.iter().any(|item| item.id == id) {
439 return match result {
440 UploadResult::Done(done) | UploadResult::NotShared(done) => done.uploaded,
441 UploadResult::ShareFailed(uploaded) => Some(uploaded),
442 UploadResult::Failed => None,
443 };
444 }
445 let not_shared = matches!(result, UploadResult::NotShared(_));
446 if let Some(ItemKind::File { upload, .. }) = self.kind_of_mut(id)
447 && matches!(upload, UploadState::Uploading(_) | UploadState::Sharing(_))
448 {
449 *upload = match result {
450 UploadResult::Done(done) | UploadResult::NotShared(done) => UploadState::Done(done),
451 UploadResult::ShareFailed(uploaded) => UploadState::ShareFailed(uploaded),
452 UploadResult::Failed => UploadState::Failed,
453 };
454 if not_shared {
455 self.notice = Some(NOT_SHARED_NOTICE.to_owned());
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 = if item.size == 0 {
735 kind_description(FileKind::from_name(&item.name)).to_owned()
736 } else {
737 format::file_size_label(item.size)
738 };
739 let muted = |subtitle: String| ChipState {
740 subtitle,
741 tone: Tone::Muted,
742 progress: None,
743 failed: false,
744 };
745 match &item.kind {
746 ItemKind::Reading => muted("Reading ...".to_owned()),
747 ItemKind::Image { .. } | ItemKind::Remote(_) => muted(size),
748 ItemKind::File {
749 upload,
750 sent_as_file,
751 ..
752 } => match upload {
753 UploadState::Uploading(percent) => ChipState {
754 progress: Some(*percent),
755 ..muted(format!("Uploading {percent} %"))
756 },
757 UploadState::Sharing(_) => ChipState {
758 progress: Some(100),
759 ..muted("Uploading 100 %".to_owned())
760 },
761 UploadState::Done(_) if *sent_as_file => muted(format!("{size}, sent as file")),
762 UploadState::Done(_) => muted(size),
763 UploadState::Failed => ChipState {
764 tone: Tone::Danger,
765 failed: true,
766 ..muted("Upload failed.".to_owned())
767 },
768 UploadState::ShareFailed(_) => ChipState {
769 tone: Tone::Danger,
770 failed: true,
771 ..muted("Sharing failed.".to_owned())
772 },
773 },
774 }
775}
776
777type ItemAction<T> = fn(&mut T, u64, &mut Window, &mut Context<T>);
778
779fn remove_button<T: 'static>(id: u64, remove: ItemAction<T>, cx: &mut Context<T>) -> Stateful<Div> {
780 div()
781 .id(ElementId::Name(format!("attachment-remove-{id}").into()))
782 .size(px(CHIP_REMOVE_SIZE))
783 .flex_none()
784 .flex()
785 .items_center()
786 .justify_center()
787 .rounded(px(7.))
788 .cursor_pointer()
789 .hover(|button| button.bg(theme::popup_hover()))
790 .child(icon(IconName::Close, 14., theme::text_muted()))
791 .on_click(cx.listener(move |this, _, window, cx| remove(this, id, window, cx)))
792}
793
794pub fn preview_size(dimensions: Option<(u32, u32)>, available_width: f32) -> (f32, f32) {
795 let (width, height) = dimensions
796 .filter(|(width, height)| *width > 0 && *height > 0)
797 .map_or((PREVIEW_HEIGHT, PREVIEW_HEIGHT), |(width, height)| {
798 (width as f32, height as f32)
799 });
800 let scale = (PREVIEW_HEIGHT / height)
801 .min(available_width / width)
802 .clamp(0., 1.);
803 (
804 (width * scale).round().max(1.),
805 (height * scale).round().max(1.),
806 )
807}
808
809pub fn preview_row_height(height: f32) -> f32 {
810 height + 2. * PREVIEW_GAP
811}
812
813pub fn inline_preview(
814 id: u64,
815 preview: Option<PreviewImage>,
816 available_width: Pixels,
817 selected: bool,
818 remove: RemoveImage,
819) -> AnyElement {
820 let dimensions = preview.as_ref().and_then(PreviewImage::dimensions);
821 let (width, height) = preview_size(dimensions, f32::from(available_width));
822 let group = SharedString::from(format!("image-preview-{id}"));
823 let frame = div()
824 .relative()
825 .size_full()
826 .rounded(px(PREVIEW_RADIUS))
827 .overflow_hidden()
828 .bg(theme::popup_hover());
829 let frame = match preview {
830 Some(preview) => {
831 let source = match preview {
832 PreviewImage::Inline { image, .. } => ImageSource::from(image),
833 PreviewImage::Remote(remote) => image_source(&remote.url),
834 };
835 frame.child(
836 img(source)
837 .size_full()
838 .rounded(px(PREVIEW_RADIUS))
839 .object_fit(ObjectFit::Cover),
840 )
841 }
842 None => frame,
843 };
844 div()
845 .group(group.clone())
846 .w(px(width))
847 .h(px(preview_row_height(height)))
848 .py(px(PREVIEW_GAP))
849 .child(
850 frame
851 .when(selected, |frame| {
852 frame.child(
853 div()
854 .absolute()
855 .inset_0()
856 .rounded(px(PREVIEW_RADIUS))
857 .border_2()
858 .border_color(theme::accent()),
859 )
860 })
861 .child(
862 div()
863 .id(ElementId::Name(format!("image-remove-{id}").into()))
864 .absolute()
865 .top(px(6.))
866 .right(px(6.))
867 .size(px(REMOVE_SIZE))
868 .flex()
869 .items_center()
870 .justify_center()
871 .rounded_full()
872 .cursor_pointer()
873 .bg(black().opacity(0.6))
874 .opacity(0.)
875 .group_hover(group, |button| button.opacity(1.))
876 .hover(|button| button.bg(black().opacity(0.85)))
877 .child(icon(IconName::Close, 10., white()))
878 .on_mouse_down(MouseButton::Left, |_, window, cx| {
879 window.prevent_default();
880 cx.stop_propagation();
881 })
882 .on_click(move |_, window, cx| remove(window, cx)),
883 ),
884 )
885 .into_any_element()
886}
887
888fn chip<T: 'static>(
889 item: &TrayItem,
890 remove: ItemAction<T>,
891 retry: ItemAction<T>,
892 cx: &mut Context<T>,
893) -> AnyElement {
894 let state = chip_state(item);
895 let id = item.id;
896 let subtitle_color = match state.tone {
897 Tone::Muted => theme::text_muted(),
898 Tone::Danger => theme::red(),
899 };
900 h_flex()
901 .id(ElementId::Name(format!("attachment-{id}").into()))
902 .relative()
903 .w(px(CHIP_WIDTH))
904 .h(px(CHIP_HEIGHT))
905 .flex_none()
906 .gap(px(12.))
907 .px(px(12.))
908 .items_center()
909 .rounded(px(10.))
910 .overflow_hidden()
911 .bg(theme::popup_hover())
912 .border_1()
913 .border_color(if state.failed {
914 theme::red()
915 } else {
916 transparent_black()
917 })
918 .child(file_badge(FileKind::from_name(&item.name), CHIP_BADGE_SIZE))
919 .child(
920 v_flex()
921 .flex_1()
922 .min_w_0()
923 .child(
924 div()
925 .truncate()
926 .text_size(px(12.5))
927 .text_color(theme::text())
928 .child(item.name.clone()),
929 )
930 .child(
931 div()
932 .truncate()
933 .text_size(px(11.))
934 .text_color(subtitle_color)
935 .child(state.subtitle),
936 ),
937 )
938 .when(state.failed, |chip| {
939 chip.child(
940 div()
941 .id(ElementId::Name(format!("attachment-retry-{id}").into()))
942 .flex_none()
943 .text_size(px(12.))
944 .font_weight(FontWeight::SEMIBOLD)
945 .text_color(theme::accent_text())
946 .cursor_pointer()
947 .hover(|button| button.underline())
948 .child("Retry")
949 .on_click(cx.listener(move |this, _, window, cx| retry(this, id, window, cx))),
950 )
951 })
952 .child(remove_button(id, remove, cx))
953 .when_some(state.progress, |chip, percent| {
954 chip.child(
955 div()
956 .absolute()
957 .left_0()
958 .bottom_0()
959 .h(px(PROGRESS_HEIGHT))
960 .w(relative(f32::from(percent) / 100.))
961 .bg(theme::accent()),
962 )
963 })
964 .into_any_element()
965}
966
967pub fn render_tray<T: 'static>(
968 tray: &AttachmentTray,
969 remove: ItemAction<T>,
970 retry: ItemAction<T>,
971 cx: &mut Context<T>,
972) -> Option<Div> {
973 if !tray.has_chips() {
974 return None;
975 }
976 let elements: Vec<AnyElement> = tray
977 .items()
978 .iter()
979 .filter(|item| !item.kind.is_object())
980 .map(|item| chip(item, remove, retry, cx))
981 .collect();
982 Some(
983 h_flex()
984 .w_full()
985 .flex_wrap()
986 .gap(px(TRAY_GAP))
987 .px(px(8.))
988 .pt(px(8.))
989 .pb(px(2.))
990 .children(elements),
991 )
992}
993
994#[cfg(test)]
995mod tests {
996 use std::io::Cursor;
997 use std::path::PathBuf;
998
999 use super::JobKind;
1000 use gpui_kit::{ClipboardEntry, ClipboardItem, ExternalPaths, Image, ImageFormat};
1001 use teams_core::{FileKind, FileReference, UploadedFile};
1002
1003 use super::{
1004 AttachmentTray, Classification, DoneFile, FILES_LATER_NOTICE, INLINE_IMAGE_MAX_BYTES,
1005 INLINE_TOTAL_MAX_BYTES, InlineFormat, ItemKind, LoadedFile, MAX_ATTACHMENTS,
1006 NOT_SHARED_NOTICE, OutgoingImage, PasteAction, PreviewImage, RemoteImage, ShareEnd, Tone,
1007 UploadResult, chip_state, classify, limit_notice, paste_action, pasted_image_name,
1008 prepare_pasted_image, preview_size, read_attachment, result_of_share, sniff_inline_format,
1009 };
1010 use crate::remote_image::RemoteKind;
1011
1012 const PNG_HEADER: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
1013
1014 fn png(width: u32, height: u32) -> Vec<u8> {
1015 let mut bytes = Vec::new();
1016 image::RgbaImage::new(width, height)
1017 .write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png)
1018 .unwrap();
1019 bytes
1020 }
1021
1022 fn padded(mut bytes: Vec<u8>, length: u64) -> Vec<u8> {
1023 bytes.resize(length as usize, 0);
1024 bytes
1025 }
1026
1027 fn reference(name: &str) -> FileReference {
1028 FileReference {
1029 attachment_id: format!("id-{name}"),
1030 content_url: format!("https://files.example/{name}"),
1031 name: name.to_owned(),
1032 }
1033 }
1034
1035 fn done(name: &str) -> UploadResult {
1036 UploadResult::Done(DoneFile {
1037 reference: reference(name),
1038 uploaded: None,
1039 })
1040 }
1041
1042 fn sample_upload() -> UploadedFile {
1043 UploadedFile {
1044 drive_id: "d".into(),
1045 item_id: "i".into(),
1046 name: "plan.pdf".into(),
1047 web_url: "https://x".into(),
1048 web_dav_url: None,
1049 etag: "\"{G},1\"".into(),
1050 home_drive: false,
1051 }
1052 }
1053
1054 fn names(count: usize) -> Vec<String> {
1055 (0..count)
1056 .map(|index| format!("file-{index}.pdf"))
1057 .collect()
1058 }
1059
1060 fn loaded_file(name: &str) -> LoadedFile {
1061 LoadedFile {
1062 file_name: Some(name.to_owned()),
1063 ..LoadedFile::new(b"%PDF-1.7".to_vec())
1064 }
1065 }
1066
1067 fn tray_with_file() -> (AttachmentTray, u64) {
1068 let mut tray = AttachmentTray::default();
1069 let id = tray.add_pending(&["plan.pdf".to_owned()])[0];
1070 tray.finish_reading(id, LoadedFile::new(b"%PDF-1.7".to_vec()), true);
1071 (tray, id)
1072 }
1073
1074 #[test]
1075 fn magic_bytes_decide_the_inline_format() {
1076 assert_eq!(sniff_inline_format(&png(1, 1)), Some(InlineFormat::Png));
1077 assert_eq!(
1078 sniff_inline_format(&[0xFF, 0xD8, 0xFF, 0xE0, 0]),
1079 Some(InlineFormat::Jpeg)
1080 );
1081 assert_eq!(sniff_inline_format(b"GIF89a...."), Some(InlineFormat::Gif));
1082 assert_eq!(
1083 sniff_inline_format(b"RIFF\x10\0\0\0WEBPVP8 "),
1084 Some(InlineFormat::Webp)
1085 );
1086 assert_eq!(sniff_inline_format(b"BM......"), None);
1087 assert_eq!(sniff_inline_format(b"%PDF-1.7"), None);
1088 assert_eq!(sniff_inline_format(&[]), None);
1089 }
1090
1091 #[test]
1092 fn small_supported_images_are_inline() {
1093 assert_eq!(
1094 classify("shot.png", &png(2, 2), 0),
1095 Classification::Inline(InlineFormat::Png)
1096 );
1097 }
1098
1099 #[test]
1100 fn images_over_one_megabyte_become_files() {
1101 let at_limit = padded(PNG_HEADER.to_vec(), INLINE_IMAGE_MAX_BYTES);
1102 let over_limit = padded(PNG_HEADER.to_vec(), INLINE_IMAGE_MAX_BYTES + 1);
1103 assert_eq!(
1104 classify("a.png", &at_limit, 0),
1105 Classification::Inline(InlineFormat::Png)
1106 );
1107 assert_eq!(
1108 classify("a.png", &over_limit, 0),
1109 Classification::File { sent_as_file: true }
1110 );
1111 }
1112
1113 #[test]
1114 fn the_inline_total_is_capped_and_later_images_become_files() {
1115 let image = padded(PNG_HEADER.to_vec(), INLINE_IMAGE_MAX_BYTES);
1116 assert_eq!(
1117 classify(
1118 "a.png",
1119 &image,
1120 INLINE_TOTAL_MAX_BYTES - INLINE_IMAGE_MAX_BYTES
1121 ),
1122 Classification::Inline(InlineFormat::Png)
1123 );
1124 assert_eq!(
1125 classify(
1126 "a.png",
1127 &image,
1128 INLINE_TOTAL_MAX_BYTES - INLINE_IMAGE_MAX_BYTES + 1
1129 ),
1130 Classification::File { sent_as_file: true }
1131 );
1132 }
1133
1134 #[test]
1135 fn removing_an_inline_image_does_not_reclassify_the_others() {
1136 let big = || LoadedFile::new(padded(PNG_HEADER.to_vec(), INLINE_IMAGE_MAX_BYTES));
1137 let mut tray = AttachmentTray::default();
1138 let ids = tray.add_pending(&names(4));
1139 for id in &ids[..3] {
1140 tray.finish_reading(*id, big(), true);
1141 }
1142 let job = tray.finish_reading(ids[3], big(), true);
1143 assert!(
1144 job.is_some(),
1145 "the fourth 1 MiB image exceeds 2.5 MiB inline"
1146 );
1147 tray.remove(ids[0]);
1148 assert!(matches!(tray.items()[2].kind, ItemKind::File { .. }));
1149 }
1150
1151 #[test]
1152 fn a_cloud_file_is_ready_at_once_and_removing_it_deletes_nothing() {
1153 let mut tray = AttachmentTray::default();
1154 let id = tray
1155 .add_cloud_file("plan.pdf".into(), 12, reference("plan.pdf"))
1156 .unwrap();
1157 assert!(!tray.blocks_send());
1158 assert_eq!(tray.outgoing_files()[0].reference, reference("plan.pdf"));
1159 assert!(tray.retry(id).is_none());
1160 assert_eq!(tray.remove(id), None);
1161 }
1162
1163 #[test]
1164 fn a_failed_share_retries_only_the_share_and_keeps_the_upload() {
1165 let (mut tray, id) = tray_with_file();
1166 let uploaded = sample_upload();
1167 tray.finish_upload(id, UploadResult::ShareFailed(uploaded.clone()));
1168 let state = chip_state(&tray.items()[0]);
1169 assert_eq!(state.subtitle, "Sharing failed.");
1170 assert!(state.failed);
1171 assert!(tray.blocks_send());
1172 let job = tray.retry(id).unwrap();
1173 assert!(matches!(job.kind, JobKind::Share(ref file) if *file == uploaded));
1174 assert_eq!(tray.clear(), vec![uploaded.clone()]);
1175 let (mut tray, id) = tray_with_file();
1176 tray.finish_upload(id, UploadResult::ShareFailed(uploaded.clone()));
1177 tray.retry(id);
1178 tray.finish_upload(id, UploadResult::ShareFailed(uploaded.clone()));
1179 assert_eq!(tray.remove(id), Some(uploaded));
1180 }
1181
1182 #[test]
1183 fn an_item_being_shared_can_be_deleted_by_remove_or_clear() {
1184 let (mut tray, id) = tray_with_file();
1185 tray.mark_uploaded(id, sample_upload());
1186 assert_eq!(chip_state(&tray.items()[0]).subtitle, "Uploading 100 %");
1187 assert!(tray.blocks_send());
1188 tray.set_progress(id, 10);
1189 assert_eq!(chip_state(&tray.items()[0]).progress, Some(100));
1190 assert_eq!(tray.remove(id), Some(sample_upload()));
1191
1192 let (mut tray, id) = tray_with_file();
1193 tray.mark_uploaded(id, sample_upload());
1194 tray.finish_upload(id, UploadResult::ShareFailed(sample_upload()));
1195 assert!(chip_state(&tray.items()[0]).failed);
1196 assert_eq!(tray.keep_images_only(), vec![sample_upload()]);
1197 }
1198
1199 #[test]
1200 fn events_for_a_removed_item_hand_the_upload_back_for_deletion() {
1201 let (mut tray, id) = tray_with_file();
1202 tray.remove(id);
1203 assert_eq!(
1204 tray.mark_uploaded(id, sample_upload()),
1205 Some(sample_upload())
1206 );
1207 let done = UploadResult::Done(DoneFile {
1208 reference: reference("plan.pdf"),
1209 uploaded: Some(sample_upload()),
1210 });
1211 assert_eq!(tray.finish_upload(id, done), Some(sample_upload()));
1212 assert_eq!(
1213 tray.finish_upload(id, UploadResult::ShareFailed(sample_upload())),
1214 Some(sample_upload())
1215 );
1216 assert_eq!(tray.finish_upload(id, UploadResult::Failed), None);
1217 }
1218
1219 #[test]
1220 fn events_for_a_live_item_are_never_handed_back() {
1221 let (mut tray, id) = tray_with_file();
1222 assert_eq!(tray.mark_uploaded(id, sample_upload()), None);
1223 assert_eq!(tray.finish_upload(id, done("plan.pdf")), None);
1224 assert_eq!(tray.finish_upload(id, done("plan.pdf")), None);
1225 }
1226
1227 #[test]
1228 fn removing_or_clearing_reports_the_uploads_that_were_never_sent() {
1229 let (mut tray, id) = tray_with_file();
1230 tray.finish_upload(
1231 id,
1232 UploadResult::Done(DoneFile {
1233 reference: reference("plan.pdf"),
1234 uploaded: Some(sample_upload()),
1235 }),
1236 );
1237 assert_eq!(tray.clear(), vec![sample_upload()]);
1238 let (mut other, other_id) = tray_with_file();
1239 assert_eq!(other.remove(other_id), None);
1240 }
1241
1242 #[test]
1243 fn other_image_formats_become_files_with_the_note() {
1244 assert_eq!(
1245 classify("scan.bmp", b"BM......", 0),
1246 Classification::File { sent_as_file: true }
1247 );
1248 assert_eq!(
1249 classify("photo.HEIC", b"....ftypheic", 0),
1250 Classification::File { sent_as_file: true }
1251 );
1252 assert_eq!(
1253 classify("plan.pdf", b"%PDF-1.7", 0),
1254 Classification::File {
1255 sent_as_file: false
1256 }
1257 );
1258 }
1259
1260 #[test]
1261 fn dimensions_come_from_the_headers() {
1262 assert_eq!(LoadedFile::new(png(7, 3)).dimensions, Some((7, 3)));
1263 let mut gif = b"GIF89a".to_vec();
1264 gif.extend_from_slice(&[10, 0, 20, 0]);
1265 assert_eq!(LoadedFile::new(gif).dimensions, Some((10, 20)));
1266 assert_eq!(LoadedFile::new(b"%PDF".to_vec()).dimensions, None);
1267 }
1268
1269 #[test]
1270 fn the_tenth_attachment_fits_and_the_rest_are_dropped() {
1271 let mut tray = AttachmentTray::default();
1272 assert_eq!(tray.add_pending(&names(4)).len(), 4);
1273 let ids = tray.add_pending(&names(9));
1274 assert_eq!(ids.len(), 6);
1275 assert_eq!(tray.items().len(), MAX_ATTACHMENTS);
1276 assert_eq!(
1277 tray.notice(),
1278 Some("Up to 10 attachments per message. 3 files were not added.")
1279 );
1280 }
1281
1282 #[test]
1283 fn one_dropped_file_reads_in_the_singular() {
1284 assert_eq!(
1285 limit_notice(1),
1286 "Up to 10 attachments per message. 1 file was not added."
1287 );
1288 }
1289
1290 #[test]
1291 fn the_limit_notice_clears_on_the_next_change() {
1292 let mut tray = AttachmentTray::default();
1293 let ids = tray.add_pending(&names(12));
1294 assert!(tray.notice().is_some());
1295 tray.remove(ids[0]);
1296 assert_eq!(tray.notice(), None);
1297 tray.add_pending(&names(3));
1298 assert!(tray.notice().is_some());
1299 tray.clear();
1300 assert_eq!(tray.notice(), None);
1301 }
1302
1303 #[test]
1304 fn a_file_starts_uploading_and_an_image_does_not() {
1305 let mut tray = AttachmentTray::default();
1306 let ids = tray.add_pending(&["a.pdf".to_owned(), "b.png".to_owned()]);
1307 let job = tray.finish_reading(ids[0], LoadedFile::new(b"%PDF".to_vec()), true);
1308 assert_eq!(job.as_ref().map(|job| job.name.as_str()), Some("a.pdf"));
1309 assert!(
1310 tray.finish_reading(ids[1], LoadedFile::new(png(2, 2)), true)
1311 .is_none()
1312 );
1313 assert!(matches!(tray.items()[1].kind, ItemKind::Image { .. }));
1314 assert!(tray.blocks_send());
1315 }
1316
1317 #[test]
1318 fn a_pasted_name_replaces_the_placeholder() {
1319 let mut tray = AttachmentTray::default();
1320 let id = tray.add_pending(&[pasted_image_name()])[0];
1321 let loaded = LoadedFile {
1322 file_name: Some("pasted-image.jpg".into()),
1323 ..LoadedFile::new(vec![0xFF, 0xD8, 0xFF, 0xE0])
1324 };
1325 tray.finish_reading(id, loaded, true);
1326 assert_eq!(tray.items()[0].name, "pasted-image.jpg");
1327 }
1328
1329 #[test]
1330 fn files_are_refused_while_the_chat_does_not_exist() {
1331 let mut tray = AttachmentTray::default();
1332 let ids = tray.add_pending(&["a.pdf".to_owned(), "b.png".to_owned()]);
1333 assert!(
1334 tray.finish_reading(ids[0], loaded_file("a.pdf"), false)
1335 .is_none()
1336 );
1337 tray.finish_reading(ids[1], LoadedFile::new(png(2, 2)), false);
1338 assert_eq!(tray.items().len(), 1);
1339 assert_eq!(tray.notice(), Some(FILES_LATER_NOTICE));
1340 assert!(!tray.blocks_send());
1341 }
1342
1343 #[test]
1344 fn upload_progress_then_done_unblocks_sending() {
1345 let (mut tray, id) = tray_with_file();
1346 tray.set_progress(id, 42);
1347 assert_eq!(chip_state(&tray.items()[0]).subtitle, "Uploading 42 %");
1348 assert_eq!(chip_state(&tray.items()[0]).progress, Some(42));
1349 assert!(tray.blocks_send());
1350 tray.finish_upload(id, done("plan.pdf"));
1351 assert!(!tray.blocks_send());
1352 assert_eq!(tray.outgoing_files().len(), 1);
1353 assert_eq!(
1354 tray.outgoing_files()[0].kind,
1355 FileKind::from_name("plan.pdf")
1356 );
1357 }
1358
1359 #[test]
1360 fn progress_after_the_upload_ended_is_ignored() {
1361 let (mut tray, id) = tray_with_file();
1362 tray.finish_upload(id, done("plan.pdf"));
1363 tray.set_progress(id, 10);
1364 tray.finish_upload(id, UploadResult::Failed);
1365 assert!(!tray.blocks_send());
1366 }
1367
1368 #[test]
1369 fn only_a_denied_share_sends_the_file_with_the_notice() {
1370 let uploaded = sample_upload();
1371 let reference = reference("plan.pdf");
1372 let denied = result_of_share(uploaded.clone(), reference.clone(), ShareEnd::Denied);
1373 assert!(matches!(denied, UploadResult::NotShared(_)));
1374 let failed = result_of_share(uploaded.clone(), reference.clone(), ShareEnd::Failed);
1375 assert!(matches!(failed, UploadResult::ShareFailed(_)));
1376 let UploadResult::Done(done) = result_of_share(
1377 uploaded,
1378 reference,
1379 ShareEnd::Linked(Some("https://files.example/share".into())),
1380 ) else {
1381 panic!("a sharing link finishes the upload");
1382 };
1383 assert_eq!(done.reference.content_url, "https://files.example/share");
1384 }
1385
1386 #[test]
1387 fn a_file_that_could_not_be_shared_still_goes_out_with_a_notice() {
1388 let (mut tray, id) = tray_with_file();
1389 let UploadResult::Done(done) = done("plan.pdf") else {
1390 unreachable!()
1391 };
1392 tray.finish_upload(id, UploadResult::NotShared(done));
1393 assert!(!tray.blocks_send());
1394 assert_eq!(tray.outgoing_files().len(), 1);
1395 assert_eq!(tray.notice(), Some(NOT_SHARED_NOTICE));
1396 }
1397
1398 #[test]
1399 fn a_failed_upload_blocks_sending_until_it_is_retried_or_removed() {
1400 let (mut tray, id) = tray_with_file();
1401 tray.finish_upload(id, UploadResult::Failed);
1402 let state = chip_state(&tray.items()[0]);
1403 assert_eq!(state.subtitle, "Upload failed.");
1404 assert_eq!(state.tone, Tone::Danger);
1405 assert!(state.failed);
1406 assert!(tray.blocks_send());
1407 assert!(tray.outgoing_files().is_empty());
1408
1409 let job = tray.retry(id).expect("failed uploads can be retried");
1410 assert_eq!(job.name, "plan.pdf");
1411 assert_eq!(chip_state(&tray.items()[0]).subtitle, "Uploading 0 %");
1412 assert!(tray.retry(id).is_none());
1413
1414 tray.finish_upload(id, UploadResult::Failed);
1415 tray.remove(id);
1416 assert!(!tray.blocks_send());
1417 }
1418
1419 #[test]
1420 fn a_result_for_a_removed_item_is_dropped() {
1421 let (mut tray, id) = tray_with_file();
1422 tray.remove(id);
1423 tray.finish_upload(id, done("plan.pdf"));
1424 assert!(tray.items().is_empty());
1425 }
1426
1427 #[test]
1428 fn done_chips_show_the_size_and_the_file_note() {
1429 let mut tray = AttachmentTray::default();
1430 let id = tray.add_pending(&["scan.bmp".to_owned()])[0];
1431 tray.finish_reading(id, LoadedFile::new(b"BM....".to_vec()), true);
1432 tray.finish_upload(id, done("scan.bmp"));
1433 assert_eq!(chip_state(&tray.items()[0]).subtitle, "6 B, sent as file");
1434 let (mut other, other_id) = tray_with_file();
1435 other.finish_upload(other_id, done("plan.pdf"));
1436 assert_eq!(chip_state(&other.items()[0]).subtitle, "8 B");
1437 }
1438
1439 #[test]
1440 fn restore_brings_back_images_and_uploaded_files() {
1441 let mut source = AttachmentTray::default();
1442 let ids = source.add_pending(&["a.png".to_owned(), "b.pdf".to_owned()]);
1443 source.finish_reading(ids[0], LoadedFile::new(png(4, 2)), true);
1444 source.finish_reading(ids[1], LoadedFile::new(b"%PDF".to_vec()), true);
1445 source.finish_upload(ids[1], done("b.pdf"));
1446 let (images, files) = (source.images_in(&ids[..1]), source.outgoing_files());
1447
1448 let mut restored = AttachmentTray::default();
1449 let image_ids = restored.restore(&images, &files);
1450 assert_eq!(image_ids.len(), 1);
1451 assert_eq!(restored.images_in(&image_ids), images);
1452 assert_eq!(restored.outgoing_files(), files);
1453 assert!(!restored.blocks_send());
1454 }
1455
1456 fn gif(title: &str) -> RemoteImage {
1457 RemoteImage {
1458 kind: RemoteKind::Gif,
1459 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
1460 title: title.into(),
1461 width: 200,
1462 height: 100,
1463 }
1464 }
1465
1466 #[test]
1467 fn a_remote_image_is_an_object_without_a_chip_and_never_blocks_sending() {
1468 let mut tray = AttachmentTray::default();
1469 let id = tray.add_remote(gif("Wave")).unwrap();
1470 assert!(!tray.has_chips());
1471 assert!(!tray.blocks_send());
1472 assert!(matches!(tray.image(id), Some(PreviewImage::Remote(_))));
1473 let images = tray.images_in(&[id]);
1474 assert_eq!(images, vec![OutgoingImage::Remote(gif("Wave"))]);
1475 let mut restored = AttachmentTray::default();
1476 let ids = restored.restore(&images, &[]);
1477 assert_eq!(restored.images_in(&ids), images);
1478 assert_eq!(tray.keep_images_only(), Vec::new());
1479 assert_eq!(tray.items().len(), 1);
1480 }
1481
1482 #[test]
1483 fn a_full_tray_refuses_another_remote_image() {
1484 let mut tray = AttachmentTray::default();
1485 for _ in 0..MAX_ATTACHMENTS {
1486 assert!(tray.add_remote(gif("Wave")).is_some());
1487 }
1488 assert!(tray.add_remote(gif("Wave")).is_none());
1489 assert!(tray.notice().is_some());
1490 }
1491
1492 fn org_emoji() -> RemoteImage {
1493 RemoteImage::custom_emoji(&teams_core::OrgEmoji {
1494 id: "em-1".into(),
1495 document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(),
1496 name: "ship-it".into(),
1497 keywords: vec![],
1498 source: None,
1499 })
1500 }
1501
1502 #[test]
1503 fn a_full_tray_still_accepts_a_custom_emoji() {
1504 let mut tray = AttachmentTray::default();
1505 for _ in 0..MAX_ATTACHMENTS {
1506 assert!(tray.add_remote(gif("Wave")).is_some());
1507 }
1508 assert!(tray.add_remote(org_emoji()).is_some());
1509 assert!(tray.add_remote(gif("Wave")).is_none());
1510 }
1511
1512 #[test]
1513 fn images_come_back_in_the_order_asked_for_and_only_when_known() {
1514 let mut tray = AttachmentTray::default();
1515 let ids = tray.add_pending(&["a.png".to_owned(), "b.png".to_owned()]);
1516 tray.finish_reading(ids[0], LoadedFile::new(png(2, 2)), true);
1517 tray.finish_reading(ids[1], LoadedFile::new(png(4, 4)), true);
1518 let images = tray.images_in(&[ids[1], 99, ids[0]]);
1519 assert_eq!(images.len(), 2);
1520 let dimensions: Vec<_> = images
1521 .iter()
1522 .map(|image| match image {
1523 OutgoingImage::Inline(inline) => inline.dimensions,
1524 OutgoingImage::Remote(_) => None,
1525 })
1526 .collect();
1527 assert_eq!(dimensions, [Some((4, 4)), Some((2, 2))]);
1528 assert!(!tray.has_chips());
1529 tray.discard_images_except(&[ids[1]]);
1530 assert_eq!(tray.items().len(), 1);
1531 assert!(tray.image(ids[1]).is_some());
1532 assert!(tray.image(ids[0]).is_none());
1533 }
1534
1535 #[test]
1536 fn previews_are_at_most_120_high_and_fit_the_row() {
1537 assert_eq!(preview_size(Some((400, 300)), 800.), (160., 120.));
1538 assert_eq!(preview_size(Some((40, 30)), 800.), (40., 30.));
1539 assert_eq!(preview_size(Some((1000, 100)), 250.), (250., 25.));
1540 assert_eq!(preview_size(None, 800.), (120., 120.));
1541 assert_eq!(preview_size(Some((400, 300)), 0.), (1., 1.));
1542 }
1543
1544 #[test]
1545 fn switching_chats_for_a_draft_keeps_only_images() {
1546 let mut tray = AttachmentTray::default();
1547 let ids = tray.add_pending(&["a.png".to_owned(), "b.pdf".to_owned()]);
1548 tray.finish_reading(ids[0], LoadedFile::new(png(2, 2)), true);
1549 tray.finish_reading(ids[1], LoadedFile::new(b"%PDF".to_vec()), true);
1550 tray.keep_images_only();
1551 assert_eq!(tray.items().len(), 1);
1552 assert!(matches!(tray.items()[0].kind, ItemKind::Image { .. }));
1553 }
1554
1555 #[test]
1556 fn a_failed_read_removes_the_item_and_says_why() {
1557 let mut tray = AttachmentTray::default();
1558 let id = tray.add_pending(&["gone.txt".to_owned()])[0];
1559 tray.fail_reading(id, "Could not read gone.txt.".to_owned());
1560 assert!(tray.items().is_empty());
1561 assert_eq!(tray.notice(), Some("Could not read gone.txt."));
1562 }
1563
1564 #[test]
1565 fn reading_items_block_sending() {
1566 let mut tray = AttachmentTray::default();
1567 tray.add_pending(&["a.pdf".to_owned()]);
1568 assert!(tray.blocks_send());
1569 assert_eq!(chip_state(&tray.items()[0]).subtitle, "Reading ...");
1570 }
1571
1572 #[test]
1573 fn files_are_read_from_disk_with_their_limits() {
1574 let directory = tempfile::tempdir().unwrap();
1575 let file = directory.path().join("note.txt");
1576 std::fs::write(&file, b"hello").unwrap();
1577 let empty = directory.path().join("empty.txt");
1578 std::fs::write(&empty, b"").unwrap();
1579
1580 assert_eq!(read_attachment(&file).unwrap().bytes, b"hello");
1581 assert_eq!(read_attachment(&empty).unwrap_err(), "empty.txt is empty.");
1582 assert!(
1583 read_attachment(directory.path())
1584 .unwrap_err()
1585 .ends_with('.')
1586 );
1587 assert_eq!(
1588 read_attachment(&directory.path().join("missing.txt")).unwrap_err(),
1589 "Could not read missing.txt."
1590 );
1591 }
1592
1593 fn clipboard(entries: Vec<ClipboardEntry>) -> ClipboardItem {
1594 ClipboardItem { entries }
1595 }
1596
1597 fn pasted_png() -> Image {
1598 Image::from_bytes(ImageFormat::Png, png(2, 2))
1599 }
1600
1601 #[test]
1602 fn pasting_an_image_alone_adds_an_image() {
1603 let item = clipboard(vec![ClipboardEntry::Image(pasted_png())]);
1604 assert_eq!(paste_action(&item), PasteAction::Image(pasted_png()));
1605 }
1606
1607 #[test]
1608 fn pasting_copied_files_adds_those_files() {
1609 let paths = ExternalPaths(vec![PathBuf::from("/a/b.pdf")].into_iter().collect());
1610 let item = clipboard(vec![ClipboardEntry::ExternalPaths(paths)]);
1611 assert_eq!(
1612 paste_action(&item),
1613 PasteAction::Files(vec![PathBuf::from("/a/b.pdf")])
1614 );
1615 }
1616
1617 #[test]
1618 fn pasting_text_or_text_with_a_bitmap_stays_text() {
1619 assert_eq!(
1620 paste_action(&ClipboardItem::new_string("hi".into())),
1621 PasteAction::Text
1622 );
1623 let both = clipboard(vec![
1624 ClipboardEntry::from("cells".to_owned()),
1625 ClipboardEntry::Image(pasted_png()),
1626 ]);
1627 assert_eq!(paste_action(&both), PasteAction::Text);
1628 assert_eq!(paste_action(&clipboard(Vec::new())), PasteAction::Text);
1629 }
1630
1631 #[test]
1632 fn a_pasted_bitmap_becomes_a_png() {
1633 let mut bmp = Vec::new();
1634 image::RgbaImage::new(3, 2)
1635 .write_to(&mut Cursor::new(&mut bmp), image::ImageFormat::Bmp)
1636 .unwrap();
1637 let loaded = prepare_pasted_image(Image::from_bytes(ImageFormat::Bmp, bmp)).unwrap();
1638 assert_eq!(sniff_inline_format(&loaded.bytes), Some(InlineFormat::Png));
1639 assert_eq!(loaded.dimensions, Some((3, 2)));
1640 assert_eq!(loaded.file_name.as_deref(), Some("pasted-image.png"));
1641 }
1642
1643 #[test]
1644 fn a_pasted_png_keeps_its_bytes() {
1645 let loaded = prepare_pasted_image(pasted_png()).unwrap();
1646 assert_eq!(loaded.bytes, png(2, 2));
1647 assert_eq!(loaded.file_name.as_deref(), Some("pasted-image.png"));
1648 }
1649}