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