1use std::cell::Cell;
69use std::collections::{HashMap, HashSet};
70use std::fmt;
71use std::io::Cursor;
72
73use cosmic::widget::image::Handle;
74use tokio::sync::mpsc;
75
76use crate::http;
77use crate::requests::Requests;
78use crate::views::components::{LIST_MAX_WIDTH, POPUP_MAX_WIDTH};
79
80const MAX_DOWNLOAD_BYTES: usize = 16 * 1024 * 1024;
82
83const MAX_DECODED_BYTES: u64 = 64 * 1024 * 1024;
85
86const MAX_IN_FLIGHT: usize = 8;
88
89const REQUEST_QUEUE: usize = 64;
93
94pub const DEFAULT_BUDGET_BYTES: usize = 256 * 1024 * 1024;
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
99pub enum ImageShape {
100 Original,
102 Circle,
104 Strip,
107 Thumbnail,
110}
111
112pub const STRIP_ASPECT: u32 = 3;
115
116pub const THUMBNAIL_ASPECT: (u32, u32) = (16, 9);
119
120pub const LARGEST_AVATAR: f32 = 64.0;
122
123const WIDEST_THUMBNAIL: f32 = 320.0;
127
128pub const SCALE_UNKNOWN: f32 = 2.0;
133
134impl ImageShape {
135 fn widest(self) -> f32 {
138 match self {
139 Self::Original => LIST_MAX_WIDTH,
140 Self::Circle => LARGEST_AVATAR,
141 Self::Strip => POPUP_MAX_WIDTH,
142 Self::Thumbnail => WIDEST_THUMBNAIL,
143 }
144 }
145}
146
147#[derive(Debug, Clone, PartialEq, Eq, Hash)]
150pub struct ImageRequest {
151 pub url: String,
152 pub shape: ImageShape,
153}
154
155#[derive(Clone)]
157pub struct LoadedImage {
158 pub handle: Handle,
160 pub width: u32,
164 pub height: u32,
165}
166
167impl LoadedImage {
168 fn bytes(&self) -> usize {
170 match &self.handle {
171 Handle::Rgba { pixels, .. } => pixels.len(),
172 _ => self.width as usize * self.height as usize * 4,
173 }
174 }
175}
176
177impl fmt::Debug for LoadedImage {
178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179 write!(f, "LoadedImage({}x{})", self.width, self.height)
180 }
181}
182
183fn circle(pixels: &image::RgbaImage) -> image::RgbaImage {
186 let (width, height) = pixels.dimensions();
187 let side = width.min(height);
188 let mut square = image::imageops::crop_imm(pixels, (width - side) / 2, (height - side) / 2, side, side).to_image();
189
190 let radius = side as f32 / 2.0;
191 for (x, y, pixel) in square.enumerate_pixels_mut() {
192 let distance = ((x as f32 + 0.5 - radius).powi(2) + (y as f32 + 0.5 - radius).powi(2)).sqrt();
195 let coverage = (radius - distance + 0.5).clamp(0.0, 1.0);
196 pixel.0[3] = (f32::from(pixel.0[3]) * coverage).round() as u8;
197 }
198 square
199}
200
201fn middle(pixels: &image::RgbaImage, (across, down): (u32, u32)) -> image::RgbaImage {
205 let (width, height) = pixels.dimensions();
206 let (wide, tall) = if u64::from(width) * u64::from(down) >= u64::from(height) * u64::from(across) {
207 ((height / down).max(1) * across, height)
208 } else {
209 (width, (width / across).max(1) * down)
210 };
211 let (wide, tall) = (wide.min(width), tall.min(height));
212 image::imageops::crop_imm(pixels, (width - wide) / 2, (height - tall) / 2, wide, tall).to_image()
213}
214
215fn kept_size((width, height): (u32, u32), shape: ImageShape, scale: f32) -> (u32, u32) {
228 let in_proportion =
229 |across: u32| ((u64::from(height) * u64::from(across) + u64::from(width) / 2) / u64::from(width).max(1)).max(1) as u32;
230 let widest = (shape.widest() * scale).round().max(1.0) as u32;
231 let cut = match shape {
232 ImageShape::Original => {
233 let across = ((width as f32).min(shape.widest()) * scale).round().max(1.0) as u32;
234 return (across, in_proportion(across));
235 }
236 ImageShape::Circle => (1, 1),
237 ImageShape::Strip => (STRIP_ASPECT, 1),
238 ImageShape::Thumbnail => THUMBNAIL_ASPECT,
239 };
240 if width <= widest {
241 return (width, height);
242 }
243 match widest / cut.0 {
245 0 => (widest, in_proportion(widest)),
246 times => (times * cut.0, times * cut.1),
247 }
248}
249
250fn sized(mut pixels: image::RgbaImage, shape: ImageShape, scale: f32) -> image::RgbaImage {
257 let (width, height) = pixels.dimensions();
258 if width == 0 || height == 0 {
259 return pixels;
260 }
261 let (across, down) = kept_size((width, height), shape, scale);
262 if (across, down) == (width, height) {
263 return pixels;
264 }
265
266 let see_through = pixels.pixels().any(|pixel| pixel.0[3] != u8::MAX);
267 if see_through {
268 for pixel in pixels.pixels_mut() {
269 let alpha = u16::from(pixel.0[3]);
270 for channel in &mut pixel.0[..3] {
271 *channel = ((u16::from(*channel) * alpha + 127) / 255) as u8;
272 }
273 }
274 }
275 let mut pixels = image::imageops::resize(&pixels, across, down, image::imageops::FilterType::CatmullRom);
276 if see_through {
277 for pixel in pixels.pixels_mut() {
278 let alpha = u16::from(pixel.0[3]);
279 for channel in &mut pixel.0[..3] {
280 *channel = (u16::from(*channel) * 255 + alpha / 2).checked_div(alpha).unwrap_or(0).min(255) as u8;
282 }
283 }
284 }
285 pixels
286}
287
288fn decode(bytes: &[u8], shape: ImageShape, max_decoded_bytes: u64, scale: f32) -> Result<LoadedImage, String> {
294 let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|e| e.to_string())?;
295 let mut limits = image::Limits::default();
296 limits.max_alloc = Some(max_decoded_bytes);
297 reader.limits(limits);
298 let pixels = reader.decode().map_err(|e| e.to_string())?.into_rgba8();
299 let pixels = match shape {
303 ImageShape::Original => pixels,
304 ImageShape::Circle => middle(&pixels, (1, 1)),
305 ImageShape::Strip => middle(&pixels, (STRIP_ASPECT, 1)),
306 ImageShape::Thumbnail => middle(&pixels, THUMBNAIL_ASPECT),
307 };
308 let (width, height) = pixels.dimensions();
309 let pixels = sized(pixels, shape, scale);
310 let pixels = if shape == ImageShape::Circle { circle(&pixels) } else { pixels };
311 let (across, down) = pixels.dimensions();
312 Ok(LoadedImage { handle: Handle::from_rgba(across, down, pixels.into_raw()), width, height })
313}
314
315pub async fn fetch(http: reqwest::Client, request: ImageRequest, scale: f32) -> Result<LoadedImage, String> {
318 let ImageRequest { url, shape } = request;
319 let bytes = http::get(&http, &url, MAX_DOWNLOAD_BYTES).await?;
320 tokio::task::spawn_blocking(move || decode(&bytes, shape, MAX_DECODED_BYTES, scale)).await.map_err(|e| e.to_string())?
321}
322
323fn encoded_png(picture: &image::DynamicImage) -> Result<Vec<u8>, String> {
326 use image::codecs::png::{CompressionType, FilterType, PngEncoder};
327
328 let mut png = Vec::new();
329 let encoder = PngEncoder::new_with_quality(&mut png, CompressionType::Fast, FilterType::Adaptive);
330 picture.write_with_encoder(encoder).map_err(|e| e.to_string())?;
331 Ok(png)
332}
333
334pub fn as_png(bytes: &[u8]) -> Result<Vec<u8>, String> {
339 use image::ImageDecoder;
340 use image::metadata::Orientation;
341
342 let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|e| e.to_string())?;
343 let format = reader.format();
344 let mut limits = image::Limits::default();
345 limits.max_alloc = Some(MAX_DECODED_BYTES);
346 reader.limits(limits);
347 let mut decoder = reader.into_decoder().map_err(|e| e.to_string())?;
348 let orientation = decoder.orientation().map_err(|e| e.to_string())?;
349 if format == Some(image::ImageFormat::Png) && orientation == Orientation::NoTransforms {
350 return Ok(bytes.to_vec());
351 }
352 let mut picture = image::DynamicImage::from_decoder(decoder).map_err(|e| e.to_string())?;
353 picture.apply_orientation(orientation);
354 encoded_png(&picture)
355}
356
357pub fn shown_as_png(loaded: &LoadedImage) -> Result<Vec<u8>, String> {
360 let Handle::Rgba { width, height, pixels, .. } = &loaded.handle else {
361 return Err("its pixels are not kept".to_string());
362 };
363 let pixels = image::RgbaImage::from_raw(*width, *height, pixels.to_vec()).ok_or("its pixels are not all there")?;
364 encoded_png(&image::DynamicImage::ImageRgba8(pixels))
365}
366
367pub async fn fetch_as_png(http: &reqwest::Client, url: &str) -> Result<Vec<u8>, String> {
369 let bytes = http::get(http, url, MAX_DOWNLOAD_BYTES).await?;
370 tokio::task::spawn_blocking(move || as_png(&bytes)).await.map_err(|e| e.to_string())?
371}
372
373pub enum ImageState<'a> {
375 Ready(&'a LoadedImage),
376 Loading,
378 Failed,
380}
381
382struct Entry {
383 image: LoadedImage,
384 shown: Cell<u64>,
386}
387
388pub struct ImageStore {
390 loaded: HashMap<ImageRequest, Entry>,
391 failed: HashSet<ImageRequest>,
392 requests: Requests<ImageRequest>,
394 clock: Cell<u64>,
396 bytes: usize,
398 budget: usize,
399}
400
401impl ImageStore {
402 pub fn new(budget: usize) -> (Self, mpsc::Receiver<ImageRequest>) {
405 let (requests, receiver) = Requests::new(REQUEST_QUEUE, MAX_IN_FLIGHT);
406 let store = Self { loaded: HashMap::new(), failed: HashSet::new(), requests, clock: Cell::new(0), bytes: 0, budget };
407 (store, receiver)
408 }
409
410 pub fn get(&self, url: &str, shape: ImageShape) -> ImageState<'_> {
413 let request = ImageRequest { url: url.to_string(), shape };
414 if let Some(entry) = self.loaded.get(&request) {
415 let now = self.clock.get() + 1;
416 self.clock.set(now);
417 entry.shown.set(now);
418 return ImageState::Ready(&entry.image);
419 }
420 if self.failed.contains(&request) {
421 return ImageState::Failed;
422 }
423 self.requests.ask(&request);
424 ImageState::Loading
425 }
426
427 pub fn begin(&mut self, request: &ImageRequest) -> bool {
432 let wanted = !self.loaded.contains_key(request) && !self.failed.contains(request);
433 self.requests.begin(request, wanted)
434 }
435
436 pub fn finish(&mut self, request: ImageRequest, result: Result<LoadedImage, String>) {
440 self.requests.end(&request);
441 match result {
442 Ok(image) => {
443 self.bytes += image.bytes();
444 let now = self.clock.get() + 1;
445 self.clock.set(now);
446 if let Some(replaced) = self.loaded.insert(request.clone(), Entry { image, shown: Cell::new(now) }) {
447 self.bytes -= replaced.image.bytes();
448 }
449 self.evict(&request);
450 }
451 Err(_) => {
452 self.failed.insert(request);
453 }
454 }
455 }
456
457 fn evict(&mut self, keep: &ImageRequest) {
460 while self.bytes > self.budget {
461 let oldest = self
462 .loaded
463 .iter()
464 .filter(|(request, _)| *request != keep)
465 .min_by_key(|(_, entry)| entry.shown.get())
466 .map(|(request, _)| request.clone());
467 let Some(request) = oldest else {
468 break;
469 };
470 if let Some(entry) = self.loaded.remove(&request) {
471 self.bytes -= entry.image.bytes();
472 }
473 }
474 }
475}
476
477#[cfg(test)]
478mod tests {
479 use super::{
480 ImageRequest, ImageShape, ImageState, ImageStore, LARGEST_AVATAR, LoadedImage, MAX_IN_FLIGHT, STRIP_ASPECT,
481 THUMBNAIL_ASPECT, as_png, circle, decode, middle, shown_as_png, sized,
482 };
483 use crate::views::components::LIST_MAX_WIDTH;
484 use cosmic::widget::image::Handle;
485
486 fn picture(side: u32) -> LoadedImage {
488 LoadedImage { handle: Handle::from_rgba(side, side, vec![0; (side * side * 4) as usize]), width: side, height: side }
489 }
490
491 fn original(url: &str) -> ImageRequest {
492 ImageRequest { url: url.to_string(), shape: ImageShape::Original }
493 }
494
495 fn is_ready(store: &ImageStore, url: &str) -> bool {
496 matches!(store.get(url, ImageShape::Original), ImageState::Ready(_))
497 }
498
499 fn is_loading(store: &ImageStore, url: &str) -> bool {
500 matches!(store.get(url, ImageShape::Original), ImageState::Loading)
501 }
502
503 fn load(store: &mut ImageStore, url: &str, side: u32) {
505 store.begin(&original(url));
506 store.finish(original(url), Ok(picture(side)));
507 }
508
509 fn png(width: u32, height: u32) -> Vec<u8> {
511 let mut bytes = Vec::new();
512 image::RgbaImage::from_pixel(width, height, image::Rgba([200, 30, 30, 255]))
513 .write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png)
514 .unwrap();
515 bytes
516 }
517
518 #[test]
519 fn a_picture_not_there_is_asked_for_once() {
520 let (mut store, mut requests) = ImageStore::new(1_000);
521
522 for _ in 0..3 {
524 assert!(is_loading(&store, "https://a"));
525 }
526 assert_eq!(requests.try_recv().ok(), Some(original("https://a")));
527 assert!(requests.try_recv().is_err(), "asked once");
528
529 assert!(store.begin(&original("https://a")));
531 assert!(is_loading(&store, "https://a"));
532 assert!(requests.try_recv().is_err());
533 assert!(!store.begin(&original("https://a")), "a second request for it starts nothing");
534
535 store.finish(original("https://a"), Ok(picture(4)));
536 assert!(is_ready(&store, "https://a"));
537 }
538
539 #[test]
540 fn the_same_address_in_another_form_is_another_picture() {
541 let (mut store, mut requests) = ImageStore::new(1_000);
542 load(&mut store, "https://a", 4);
543
544 assert!(matches!(store.get("https://a", ImageShape::Circle), ImageState::Loading));
546 assert_eq!(requests.try_recv().ok(), Some(ImageRequest { url: "https://a".into(), shape: ImageShape::Circle }));
547 assert!(is_ready(&store, "https://a"));
548 }
549
550 #[test]
551 fn a_picture_that_failed_is_not_tried_again() {
552 let (mut store, mut requests) = ImageStore::new(1_000);
553 assert!(store.begin(&original("https://broken")));
554 store.finish(original("https://broken"), Err("404".into()));
555
556 assert!(matches!(store.get("https://broken", ImageShape::Original), ImageState::Failed));
557 assert!(requests.try_recv().is_err());
558 assert!(!store.begin(&original("https://broken")));
559 }
560
561 #[test]
562 fn only_so_many_load_at_once_and_the_rest_ask_again() {
563 let (mut store, mut requests) = ImageStore::new(1_000);
564 for n in 0..MAX_IN_FLIGHT {
565 assert!(store.begin(&original(&format!("https://{n}"))));
566 }
567
568 assert!(is_loading(&store, "https://late"));
570 assert_eq!(requests.try_recv().ok(), Some(original("https://late")));
571 assert!(!store.begin(&original("https://late")));
572
573 assert!(is_loading(&store, "https://late"));
576 assert_eq!(requests.try_recv().ok(), Some(original("https://late")));
577 store.finish(original("https://0"), Ok(picture(1)));
578 assert!(store.begin(&original("https://late")));
579 }
580
581 #[test]
582 fn over_budget_the_pictures_least_recently_shown_go_first() {
583 let (mut store, _requests) = ImageStore::new(150);
585 load(&mut store, "https://a", 4);
586 load(&mut store, "https://b", 4);
587 assert!(is_ready(&store, "https://a"));
589
590 load(&mut store, "https://c", 4);
591
592 assert!(is_ready(&store, "https://a"));
593 assert!(is_ready(&store, "https://c"));
594 assert!(is_loading(&store, "https://b"), "dropped, and asked for again when shown");
595 }
596
597 #[test]
598 fn a_picture_larger_than_the_budget_is_still_shown() {
599 let (mut store, _requests) = ImageStore::new(10);
600 load(&mut store, "https://big", 4);
601 assert!(is_ready(&store, "https://big"));
602 }
603
604 #[test]
605 fn a_picture_is_decoded_from_its_bytes() {
606 let decoded = decode(&png(3, 2), ImageShape::Original, 1_000, 1.0).unwrap();
607 assert_eq!((decoded.width, decoded.height), (3, 2));
608 }
609
610 fn kept(loaded: &LoadedImage) -> (u32, u32) {
612 match &loaded.handle {
613 Handle::Rgba { width, height, .. } => (*width, *height),
614 _ => panic!("pixels are what is kept"),
615 }
616 }
617
618 #[test]
619 fn a_picture_is_kept_at_the_size_it_is_shown_at_and_laid_out_by_its_own() {
620 let row = LIST_MAX_WIDTH as u32;
621 let decoded = |width, height, scale| decode(&png(width, height), ImageShape::Original, 1 << 26, scale).unwrap();
622
623 let wide = decoded(row * 4, row * 2, 1.0);
626 assert_eq!(kept(&wide), (row, row / 2));
627 assert_eq!(
628 kept(&decoded(row * 4, row * 2, 1.7)),
629 ((row as f32 * 1.7).round() as u32, (row as f32 * 1.7 / 2.0).round() as u32)
630 );
631 assert_eq!((wide.width, wide.height), (row * 4, row * 2));
634
635 assert_eq!(kept(&decoded(200, 100, 1.0)), (200, 100));
638 let narrow = decoded(200, 100, 1.5);
639 assert_eq!(kept(&narrow), (300, 150));
640 assert_eq!((narrow.width, narrow.height), (200, 100));
641 assert_eq!(kept(&decoded(row, 10, 1.0)), (row, 10));
643 assert_eq!(kept(&decoded(row * 100, 1, 1.0)), (row, 1));
645 }
646
647 #[test]
648 fn the_other_shapes_are_made_no_larger_than_they_are_ever_shown() {
649 let largest = LARGEST_AVATAR as u32;
650 let avatar = |side, scale| kept(&decode(&png(side, side), ImageShape::Circle, 1 << 26, scale).unwrap());
651 assert_eq!(avatar(1_000, 1.0), (largest, largest));
652 assert_eq!(avatar(1_000, 2.0), (largest * 2, largest * 2));
653 assert_eq!(avatar(40, 1.0), (40, 40));
655 assert_eq!(avatar(40, 2.0), (40, 40));
656
657 for scale in [1.0, 1.25, 1.7, 2.0] {
661 let (across, down) = kept(&decode(&png(3_000, 3_000), ImageShape::Strip, 1 << 26, scale).unwrap());
662 assert_eq!(across, down * STRIP_ASPECT, "at {scale}");
663 assert!(
664 across as f32 <= 640.0 * scale && across as f32 > 640.0 * scale - STRIP_ASPECT as f32 - 1.0,
665 "at {scale}: {across}"
666 );
667 let (across, down) = kept(&decode(&png(3_000, 3_000), ImageShape::Thumbnail, 1 << 26, scale).unwrap());
668 assert_eq!(across * THUMBNAIL_ASPECT.1, down * THUMBNAIL_ASPECT.0, "at {scale}");
669 }
670
671 let round = decode(&png(1_000, 1_000), ImageShape::Circle, 1 << 26, 1.0).unwrap();
674 let Handle::Rgba { pixels, .. } = &round.handle else { panic!("pixels are what is kept") };
675 let alpha = |x: u32, y: u32| pixels[((y * largest + x) * 4 + 3) as usize];
676 assert_eq!(alpha(0, 0), 0);
677 assert_eq!(alpha(largest / 2, largest / 2), 255);
678 assert_eq!(alpha(1, largest / 2), 255, "one pixel in from the edge is inside the circle");
679 }
680
681 #[test]
682 fn what_is_behind_a_see_through_pixel_does_not_darken_what_is_made_smaller() {
683 let logo = image::RgbaImage::from_fn(LIST_MAX_WIDTH as u32 * 4, 8, |x, _| {
686 if x < LIST_MAX_WIDTH as u32 * 2 { image::Rgba([255, 255, 255, 255]) } else { image::Rgba([0, 0, 0, 0]) }
687 });
688 let small = sized(logo, ImageShape::Original, 1.0);
689 assert_eq!(small.width(), LIST_MAX_WIDTH as u32);
690 for pixel in small.pixels().filter(|pixel| pixel.0[3] > 8) {
692 assert!(pixel.0[..3].iter().all(|&channel| channel >= 250), "{:?}", pixel.0);
693 }
694 assert!(small.pixels().any(|pixel| pixel.0[3] == 255) && small.pixels().any(|pixel| pixel.0[3] == 0));
695 }
696
697 #[test]
698 fn the_budget_counts_the_pixels_kept_not_the_pictures_own() {
699 let row = LIST_MAX_WIDTH as u32;
701 let big = decode(&png(row * 4, row * 4), ImageShape::Original, 1 << 28, 1.0).unwrap();
702 assert_eq!(big.bytes(), (row * row * 4) as usize);
703 }
704
705 #[test]
706 fn a_picture_that_would_decode_too_large_is_refused() {
707 let file = png(100, 100);
709 assert!(file.len() < 1_000, "one colour compresses to almost nothing");
710 assert!(decode(&file, ImageShape::Original, 39_999, 1.0).is_err());
711 assert!(decode(&file, ImageShape::Original, 40_000, 1.0).is_ok());
712 }
713
714 #[test]
715 fn bytes_that_are_not_a_picture_are_refused() {
716 assert!(decode(b"<html>not found</html>", ImageShape::Original, 1_000, 1.0).is_err());
717 assert!(decode(&[], ImageShape::Original, 1_000, 1.0).is_err());
718 }
719
720 #[test]
721 fn an_avatar_is_the_middle_square_made_round() {
722 let wide = image::RgbaImage::from_fn(300, 100, |x, _| match x / 100 {
724 0 => image::Rgba([255, 0, 0, 255]),
725 1 => image::Rgba([0, 255, 0, 255]),
726 _ => image::Rgba([0, 0, 255, 255]),
727 });
728
729 let round = circle(&wide);
730
731 assert_eq!(round.dimensions(), (100, 100), "the middle square");
732 assert_eq!(round.get_pixel(50, 50).0, [0, 255, 0, 255], "the middle of the picture, opaque");
733 assert_eq!(round.get_pixel(2, 50).0, [0, 255, 0, 255], "the circle reaches the edge of the square");
734 for corner in [(0, 0), (99, 0), (0, 99), (99, 99)] {
735 assert_eq!(round.get_pixel(corner.0, corner.1).0[3], 0, "corner {corner:?} is outside the circle");
736 }
737
738 let decoded = decode(&png(40, 90), ImageShape::Circle, 1_000_000, 1.0).unwrap();
740 assert_eq!((decoded.width, decoded.height), (40, 40));
741 }
742
743 #[test]
744 fn a_strip_is_the_middle_of_the_picture_three_times_as_wide_as_tall() {
745 let tall = image::RgbaImage::from_fn(300, 900, |_, y| match y / 300 {
747 0 => image::Rgba([255, 0, 0, 255]),
748 1 => image::Rgba([0, 255, 0, 255]),
749 _ => image::Rgba([0, 0, 255, 255]),
750 });
751 let strip = |pixels: &image::RgbaImage| middle(pixels, (STRIP_ASPECT, 1));
752 let cut = strip(&tall);
753 assert_eq!(cut.dimensions(), (300, 100), "top and bottom cut off");
754 assert_eq!(cut.get_pixel(150, 0).0, [0, 255, 0, 255], "the middle of the picture");
755 assert_eq!(cut.get_pixel(150, 99).0, [0, 255, 0, 255]);
756
757 assert_eq!(strip(&image::RgbaImage::new(1_000, 100)).dimensions(), (300, 100));
759 assert_eq!(strip(&image::RgbaImage::new(1_500, 500)).dimensions(), (1_500, 500));
760 assert_eq!(strip(&image::RgbaImage::new(2, 5)).dimensions(), (2, 1));
762
763 let decoded = decode(&png(90, 90), ImageShape::Strip, 1_000_000, 1.0).unwrap();
765 assert_eq!((decoded.width, decoded.height), (90, 30));
766 }
767
768 #[test]
769 fn a_thumbnail_is_the_middle_of_the_picture_in_its_own_proportions() {
770 let thumbnail = |width, height| middle(&image::RgbaImage::new(width, height), THUMBNAIL_ASPECT).dimensions();
771 assert_eq!(thumbnail(1_200, 630), (1_120, 630));
773 assert_eq!(thumbnail(400, 400), (400, 225));
775 assert_eq!(thumbnail(320, 1_000), (320, 180));
776 assert_eq!(thumbnail(1_280, 720), (1_280, 720));
778 assert_eq!(thumbnail(3, 2), (3, 2));
779
780 let decoded = decode(&png(160, 160), ImageShape::Thumbnail, 1_000_000, 1.0).unwrap();
781 assert_eq!((decoded.width, decoded.height), (160, 90));
782 }
783
784 #[test]
785 fn a_picture_for_the_clipboard_is_a_png_the_way_up_it_says_it_is() {
786 use image::{DynamicImage, ImageFormat, Rgb, RgbImage};
787 use std::io::Cursor;
788
789 let picture = DynamicImage::ImageRgb8(RgbImage::from_fn(3, 2, |x, y| Rgb([(x * 80) as u8, (y * 120) as u8, 200])));
791 let encoded = |format: ImageFormat| {
792 let mut bytes = Vec::new();
793 picture.write_to(&mut Cursor::new(&mut bytes), format).unwrap();
794 bytes
795 };
796 let read = |png: &[u8]| image::load_from_memory_with_format(png, ImageFormat::Png).unwrap();
797
798 let png = encoded(ImageFormat::Png);
800 assert_eq!(as_png(&png).unwrap(), png);
801 let from_webp = read(&as_png(&encoded(ImageFormat::WebP)).unwrap());
803 assert_eq!(from_webp.to_rgb8(), picture.to_rgb8());
804
805 let jpeg = encoded(ImageFormat::Jpeg);
808 let exif =
809 [&[0xFF, 0xE1, 0, 34][..], b"Exif\0\0MM\0\x2A\0\0\0\x08\0\x01\x01\x12\0\x03\0\0\0\x01\0\x06\0\0\0\0\0\0"].concat();
810 let sideways = [&jpeg[..20], &exif, &jpeg[20..]].concat();
811 let upright = read(&as_png(&sideways).unwrap());
812 assert_eq!((upright.width(), upright.height()), (2, 3));
813 let as_it_is = read(&as_png(&jpeg).unwrap());
814 assert_eq!((as_it_is.width(), as_it_is.height()), (3, 2));
815
816 assert!(as_png(b"not a picture").is_err());
817 }
818
819 #[test]
820 fn what_is_shown_of_a_picture_is_a_png_of_the_pixels_kept() {
821 let pixels: Vec<u8> = (0..2 * 3 * 4).map(|nth| nth as u8 * 10).collect();
822 let loaded = LoadedImage { handle: Handle::from_rgba(2, 3, pixels.clone()), width: 20, height: 30 };
823 let png = shown_as_png(&loaded).unwrap();
824 let read = image::load_from_memory_with_format(&png, image::ImageFormat::Png).unwrap();
825 assert_eq!((read.width(), read.height()), (2, 3));
826 assert_eq!(read.into_rgba8().into_raw(), pixels);
827 }
828}