BlueGit

ict rusty-teams

Files

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

attachment_tray.rs

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