BlueGit

ict rusty-teams

Files

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

attachment_tray.rs

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