BlueGit

ict rusty-teams

Files

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

attachment_tray.rs

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