Skip to main content

cosmic_applet_avestruz/
images.rs

1// SPDX-License-Identifier: MIT
2
3//! Pictures from the web: avatars, the images in notes, and the pictures
4//! across profiles.
5//!
6//! A view asks the [`ImageStore`] for a picture by its address. If it is
7//! there, the view gets it; if not, the view gets told it is loading, and the
8//! store asks for it (see [`Requests`]): the app hears of it as a
9//! [`Message::LoadImage`](crate::messages::Message::LoadImage). Only rows on
10//! screen are ever built, so only pictures on screen are ever asked for.
11//!
12//! An avatar is asked for as a [`ImageShape::Circle`]: cut to its middle
13//! square and made round in its own pixels when it is decoded. The renderer
14//! could round and crop it at draw time, but iced's CPU renderer does neither
15//! reliably for a picture that isn't square. The picture across a profile is
16//! asked for as a [`ImageShape::Strip`] and the one beside a link's preview
17//! as a [`ImageShape::Thumbnail`], and they are cut the same way for the same
18//! reason.
19//!
20//! A picture is kept at the size it is shown at, in the screen's own
21//! pixels, and not as it came (see [`sized`]). What draws a frame is a CPU
22//! renderer, and scaling a picture is the dearest thing it does: a
23//! photograph of twelve million pixels, scaled into a row on every frame of
24//! a scrolling list, costs more than everything else in the frame put
25//! together. Scaled once, when it is decoded, it is copied into the frame
26//! pixel for pixel (see [`Picture`](crate::views::components::Picture)).
27//! Nothing shows a picture larger than its row, so nothing is lost by it.
28//!
29//! What a picture takes is bounded three ways: by that size, by a limit on
30//! how large one may decode before it is made smaller, and by a budget on
31//! the bytes kept, with the pictures least recently shown dropped first. A
32//! dropped picture is fetched again if it comes back into view; there is no
33//! disk cache yet.
34//!
35//! Addresses come from whoever wrote a profile or a note. They are fetched
36//! as everything is (see [`crate::http`]), and both the download and the
37//! decoded picture are capped.
38//!
39//! ```mermaid
40//! flowchart TD
41//!     url["An address, and the shape wanted"] --> fetch["Fetched: https only, so many bytes at the most"]
42//!     fetch --> decode["Decoded off the main thread, unless it would decode too large"]
43//!     decode --> shape{"The shape wanted"}
44//!     shape -->|"Original"| size
45//!     shape -->|"Circle"| circle["Cut to its middle square, and made round"]
46//!     shape -->|"Strip"| strip["Cut to its middle, three times as wide as tall"]
47//!     shape -->|"Thumbnail"| thumb["Cut to its middle, in a thumbnail's proportions"]
48//!     circle --> size
49//!     strip --> size
50//!     thumb --> size["Made the size it is shown at, in the screen's pixels"]
51//!     size --> keep["Kept, by address and shape"]
52//!     keep --> budget{"Over the budget of decoded bytes?"}
53//!     budget -->|"yes"| drop["The ones least recently shown are dropped, until it is met"]
54//!     budget -->|"no"| done["Shown"]
55//!     drop --> done
56//! ```
57//!
58//! | Limit | Value | Constant |
59//! |---|---|---|
60//! | One download | 16 MiB | [`MAX_DOWNLOAD_BYTES`] |
61//! | One picture, decoded | 64 MiB | [`MAX_DECODED_BYTES`] |
62//! | All pictures, as kept | 256 MiB | [`DEFAULT_BUDGET_BYTES`] |
63//! | Fetches at once | 8 | [`MAX_IN_FLIGHT`] |
64//!
65//! A picture that failed is remembered as failed for the run, and is not
66//! asked for again.
67
68use 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
80/// How large a picture may be to download.
81const MAX_DOWNLOAD_BYTES: usize = 16 * 1024 * 1024;
82
83/// How large a picture may be once decoded (four bytes a pixel): 4096×4096.
84const MAX_DECODED_BYTES: u64 = 64 * 1024 * 1024;
85
86/// How many pictures may be on their way at once.
87const MAX_IN_FLIGHT: usize = 8;
88
89/// How many requests may wait between a view asking and the app answering.
90/// A request that doesn't fit is dropped: a picture still on screen is asked
91/// for again the next time the view is built.
92const REQUEST_QUEUE: usize = 64;
93
94/// How many decoded bytes the store keeps before dropping pictures.
95pub const DEFAULT_BUDGET_BYTES: usize = 256 * 1024 * 1024;
96
97/// The form a picture is wanted in.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
99pub enum ImageShape {
100    /// As it came.
101    Original,
102    /// Its middle square, round: an avatar.
103    Circle,
104    /// Its middle, [`STRIP_ASPECT`] times as wide as it is tall: the
105    /// picture across a profile.
106    Strip,
107    /// Its middle, in the proportions of [`THUMBNAIL_ASPECT`]: the picture
108    /// beside the preview of a link.
109    Thumbnail,
110}
111
112/// How many times as wide as it is tall a [`ImageShape::Strip`] is: what
113/// such pictures are made for.
114pub const STRIP_ASPECT: u32 = 3;
115
116/// How wide a [`ImageShape::Thumbnail`] is for how tall: near what pages
117/// make the pictures they are shared with.
118pub const THUMBNAIL_ASPECT: (u32, u32) = (16, 9);
119
120/// How wide the largest avatar is shown, in points: the one on a profile.
121pub const LARGEST_AVATAR: f32 = 64.0;
122
123/// How wide the picture beside a link's preview is shown at the most, in
124/// points. It is as wide as its card is tall allows, which goes by the
125/// size text is set in: this is past what any size makes it.
126const WIDEST_THUMBNAIL: f32 = 320.0;
127
128/// How many of the screen's pixels a point is taken to be while the
129/// screen has not said: more than most are, so that a picture made for it
130/// is sharp on any. It is then scaled as it is drawn, which costs what
131/// sizing it is there to save, until the screen has answered.
132pub const SCALE_UNKNOWN: f32 = 2.0;
133
134impl ImageShape {
135    /// How wide a picture of this shape is shown at the most, in points:
136    /// no view has more room for one.
137    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/// A picture a view wants: where it is, and in what form. The same address
148/// in two forms is two pictures.
149#[derive(Debug, Clone, PartialEq, Eq, Hash)]
150pub struct ImageRequest {
151    pub url: String,
152    pub shape: ImageShape,
153}
154
155/// A picture ready to draw.
156#[derive(Clone)]
157pub struct LoadedImage {
158    /// Its pixels, as many as it takes where it is shown: see [`sized`].
159    pub handle: Handle,
160    /// How large the picture itself is, in the shape it was asked for in:
161    /// what it is laid out by. A picture is shown no wider than this many
162    /// points, and as tall as its proportions make it.
163    pub width: u32,
164    pub height: u32,
165}
166
167impl LoadedImage {
168    /// The bytes the pixels kept take.
169    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
183/// The middle square of `pixels`, with everything outside the circle that
184/// fits it made transparent, and the circle's edge softened over one pixel.
185fn 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        // How far the pixel's centre is inside the circle, in pixels: all
193        // the way in is opaque, one pixel out is gone.
194        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
201/// The middle of `pixels`, `across` wide for every `down` tall: the sides
202/// cut off a picture that is wider than that, the top and bottom off one
203/// that is taller.
204fn 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
215/// How many pixels a picture of `width` by `height` pixels, of the shape
216/// `shape`, is kept at on a screen of `scale` pixels to the point: as many
217/// as it takes where it is shown, in its own proportions.
218///
219/// A picture in a note is shown as wide as its row, and no wider than it
220/// is itself, counting a pixel of it as a point: it is kept at that many
221/// points' worth of pixels, which makes a narrow picture larger on a
222/// screen of more than a pixel to the point, as drawing it there always
223/// did. The other shapes are shown at sizes of their views' choosing, and
224/// are only ever made smaller: no larger than the largest of those takes,
225/// and in exactly the proportions they are cut to, which is what the room
226/// kept for them while they load is in.
227fn 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    // Whole times what it is cut to, where there is room for that.
244    match widest / cut.0 {
245        0 => (widest, in_proportion(widest)),
246        times => (times * cut.0, times * cut.1),
247    }
248}
249
250/// `pixels`, a picture of the shape `shape`, made the size it is shown at
251/// on a screen of `scale` pixels to the point (see [`kept_size`]).
252///
253/// Colours are weighed by how opaque they are while the picture is made
254/// another size: what is behind a see-through pixel is no part of the
255/// picture, and would otherwise darken the edge of what is in front of it.
256fn 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                // Of a pixel that is wholly see-through, no colour is left to tell.
281                *channel = (u16::from(*channel) * 255 + alpha / 2).checked_div(alpha).unwrap_or(0).min(255) as u8;
282            }
283        }
284    }
285    pixels
286}
287
288/// Decode `bytes` into pixels in the form `shape`, at the size they are
289/// shown at on a screen of `scale` pixels to the point, refusing a picture
290/// that would decode larger than `max_decoded_bytes`. The format is told
291/// from the bytes themselves, not from the address or what the server
292/// called it.
293fn 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    // Cut to its shape first, and made round last: the edge of an avatar
300    // is softened over one pixel of the picture kept, not of the one that
301    // came.
302    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
315/// Fetch and decode the picture `request` asks for, for a screen of `scale`
316/// pixels to the point.
317pub 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
323/// `picture` as a PNG, written quickly rather than small: it is on its
324/// way to a clipboard, not to a disk.
325fn 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
334/// The picture `bytes` are, as a PNG, which is what a picture on a
335/// clipboard is taken as everywhere: itself, if it is one already;
336/// otherwise decoded, turned the way up it says it is, and encoded. An
337/// animated picture is its first frame.
338pub 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
357/// The picture `loaded` shows, as a PNG: the pixels kept of it, which are
358/// as many as it takes where it is shown, and may be fewer than it has.
359pub 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
367/// What is at `url`, a picture, as a PNG (see [`as_png`]).
368pub 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
373/// What the store has to say about a picture.
374pub enum ImageState<'a> {
375    Ready(&'a LoadedImage),
376    /// Asked for, or about to be.
377    Loading,
378    /// It could not be fetched or decoded, and won't be tried again this run.
379    Failed,
380}
381
382struct Entry {
383    image: LoadedImage,
384    /// When it was last shown, on the store's clock.
385    shown: Cell<u64>,
386}
387
388/// The pictures loaded so far, by address and form. See the [module docs](self).
389pub struct ImageStore {
390    loaded: HashMap<ImageRequest, Entry>,
391    failed: HashSet<ImageRequest>,
392    /// The asking for those that are neither.
393    requests: Requests<ImageRequest>,
394    /// Ticks each time a picture is shown.
395    clock: Cell<u64>,
396    /// The decoded bytes held, and how many may be.
397    bytes: usize,
398    budget: usize,
399}
400
401impl ImageStore {
402    /// An empty store keeping at most `budget` decoded bytes, and the
403    /// receiving end of its requests.
404    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    /// The picture at `url`, in the form `shape`, if it is loaded; otherwise
411    /// ask for it.
412    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    /// A request reached the app. Returns whether to start loading the
428    /// picture: not if it is loaded, failed or on its way already, and not
429    /// while [`MAX_IN_FLIGHT`] others are. A request turned away for that
430    /// last reason is simply asked again by the next view that needs it.
431    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    /// The load `request` started ended. A picture is kept, dropping the
437    /// ones least recently shown if the budget is exceeded; a failure is
438    /// remembered.
439    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    /// Drop the pictures least recently shown until the budget is met,
458    /// sparing `keep`, which has just arrived.
459    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    /// A picture of `side`×`side` pixels: `side * side * 4` bytes.
487    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    /// Load `url` into `store`: begun, and finished with a `side`×`side` picture.
504    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    /// A PNG of `width`×`height` pixels of one colour.
510    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        // A view is built several times before the app gets to the request.
523        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        // On its way: still loading, and not asked for again.
530        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        // Loaded as it came; wanted round, it is asked for again.
545        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        // One more is asked for and turned away...
569        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        // ...so the next view that needs it asks again, and once there is
574        // room it starts.
575        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        // Room for two 4×4 pictures (64 bytes each), not three.
584        let (mut store, _requests) = ImageStore::new(150);
585        load(&mut store, "https://a", 4);
586        load(&mut store, "https://b", 4);
587        // `a` is on screen again; `b` hasn't been shown since it arrived.
588        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    /// How many pixels a decoded picture is kept at.
611    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        // Wider than its row: as many pixels as the row is across on the
624        // screen, and as many down as its proportions make that.
625        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        // What it is laid out by is its own size, whatever is kept of it:
632        // its row is as tall as it was when its note said how large it is.
633        assert_eq!((wide.width, wide.height), (row * 4, row * 2));
634
635        // Narrower: shown a point to the pixel, so kept as it came where a
636        // point is a pixel, and as large as it is drawn where it is more.
637        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        // Exactly its row's width, a pixel to the point: nothing to do.
642        assert_eq!(kept(&decoded(row, 10, 1.0)), (row, 10));
643        // However thin, something is kept of it.
644        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        // Smaller than that already: kept as it came, on any screen.
654        assert_eq!(avatar(40, 1.0), (40, 40));
655        assert_eq!(avatar(40, 2.0), (40, 40));
656
657        // A strip and a thumbnail stay exactly the shape they are cut to,
658        // which the room kept for them while they load is in, whatever
659        // the screen: nothing moves when they arrive.
660        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        // Made round after it is made small: the corners are see-through,
672        // and the edge is one pixel of what is kept.
673        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        // White, opaque on the left half; black, and wholly see-through, on
684        // the right: what a logo on no ground looks like in a file.
685        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        // Wherever anything of the picture is left, it is as white as it was.
691        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        // Sixteen times the row's pixels as it came; one row's worth kept.
700        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        // 100×100 pixels are 40,000 bytes decoded, however small the file.
708        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        // Wide: red on the left third, green in the middle, blue on the right.
723        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        // Decoding as an avatar does the same.
739        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        // Tall: red on top, green in the middle, blue at the bottom.
746        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        // Wider than a strip: the sides go. Already a strip: nothing does.
758        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        // Too small to cut anything from.
761        assert_eq!(strip(&image::RgbaImage::new(2, 5)).dimensions(), (2, 1));
762
763        // Decoding as a strip does the same.
764        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        // As pages make the pictures they are shared with: a little wide.
772        assert_eq!(thumbnail(1_200, 630), (1_120, 630));
773        // Square, and tall: the top and bottom go.
774        assert_eq!(thumbnail(400, 400), (400, 225));
775        assert_eq!(thumbnail(320, 1_000), (320, 180));
776        // Already so: nothing goes. Too small to cut anything from: nothing can.
777        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        // Three wide and two tall, each pixel a colour of its own.
790        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        // A PNG is itself.
799        let png = encoded(ImageFormat::Png);
800        assert_eq!(as_png(&png).unwrap(), png);
801        // What is no PNG is made one, with the same pixels.
802        let from_webp = read(&as_png(&encoded(ImageFormat::WebP)).unwrap());
803        assert_eq!(from_webp.to_rgb8(), picture.to_rgb8());
804
805        // A JPEG that says it lies on its side is turned upright: after
806        // its JFIF header, an EXIF block that says so and nothing else.
807        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}