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