BlueGit

ict rusty-teams

Files

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

attachment_tray.rs

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