Skip to main content

fleuron/
images.rs

1//! Image sizing, and the contour a sheet asks to be traced.
2//!
3//! Layout needs one thing from an image — how big it is — and getting
4//! it by decoding would put a pixel buffer in the layout pass. So the
5//! engine reads the header: PNG's `IHDR` and `pHYs`, JPEG's `SOFn` and
6//! JFIF density, GIF's screen descriptor, WebP's chunk headers, and
7//! the `width`, `height` and `viewBox` of an SVG's root element. The
8//! file is kept as it arrived, and a painter is what decodes it.
9//!
10//! A url reaches the table from two places. The content tree names
11//! one for every image the manuscript places, and the style tree
12//! names one for every box the sheet puts art behind, so probing
13//! takes both.
14//!
15//! One thing else decodes it: `shape-outside: auto`, which sets prose
16//! around the shape of an image rather than around its box. That is
17//! not reachable from where probing happens, because probing has not
18//! seen the style tree, so it is a stage of its own. [`Contours`] is
19//! what that stage keeps: it walks the cascade for the nodes that ask
20//! for a traced contour, and traces each asset once.
21//!
22//! The engine opens nothing itself, the same as with fonts. Whatever string
23//! the content tree writes is the name an image is matched under. It
24//! never has to be a real URL; the host is what turns a name into
25//! bytes.
26
27use std::collections::{BTreeMap, BTreeSet};
28use std::hash::{DefaultHasher, Hash, Hasher};
29
30use serde::{Deserialize, Serialize};
31
32use crate::Warning;
33use crate::content::{Block, Book};
34use crate::style::{ComputedStyle, ShapeOutside, StyleTree, Url};
35
36/// Resolves image urls to bytes.
37///
38/// The whole file, not a prefix: the header sizes the box and the
39/// same bytes are what a painter embeds.
40pub trait ImageLoader {
41    /// The bytes behind one url, or `None` when the host cannot
42    /// resolve it.
43    fn load(&self, url: &str) -> Option<Vec<u8>>;
44}
45
46/// A loader that resolves nothing.
47pub struct NoImages;
48
49impl ImageLoader for NoImages {
50    fn load(&self, _url: &str) -> Option<Vec<u8>> {
51        None
52    }
53}
54
55/// The images a host already handed over answer by the url they
56/// were registered under, with the bytes as they arrived.
57impl ImageLoader for Assets {
58    fn load(&self, url: &str) -> Option<Vec<u8>> {
59        let (index, _) = self.lookup(url)?;
60        self.bytes(index).map(<[u8]>::to_vec)
61    }
62}
63
64/// What CSS calls one pixel: 1/96th of an inch. An image whose header
65/// declares no resolution is measured at this one.
66pub const CSS_DPI: f32 = 96.0;
67
68/// An image's own idea of its size: pixels, and the resolution they
69/// are meant to be shown at.
70///
71/// A vector image has no pixels. Its `width` and `height` are its
72/// size in CSS pixels to the nearest whole one, and the resolution
73/// carries the remainder, so [`Intrinsic::size`] is exact.
74#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
75pub struct Intrinsic {
76    /// Width in pixels.
77    pub width: u32,
78    /// Height in pixels.
79    pub height: u32,
80    /// Horizontal resolution in pixels per inch.
81    pub dpi_x: f32,
82    /// Vertical resolution in pixels per inch.
83    pub dpi_y: f32,
84    /// Whether the file gives a size. False for a vector image that
85    /// gives a ratio alone: `width` and `height` are then the two
86    /// sides of the ratio, and what sizes the image is the box it is
87    /// placed in.
88    pub sized: bool,
89}
90
91impl Intrinsic {
92    /// The intrinsic size in points, at the header's own resolution.
93    /// For an image with a ratio and no size, the two sides of the
94    /// ratio.
95    pub fn size(self) -> (f32, f32) {
96        (
97            self.width as f32 / self.dpi_x * 72.0,
98            self.height as f32 / self.dpi_y * 72.0,
99        )
100    }
101
102    /// The size the image takes where no sheet gives it one, in a
103    /// box `measure` wide. An image with a ratio and no size fills
104    /// the width, as CSS has a replaced element do.
105    pub fn size_within(self, measure: f32) -> (f32, f32) {
106        let (width, height) = self.size();
107        if self.sized || width <= 0.0 {
108            return (width, height);
109        }
110        (measure, measure * height / width)
111    }
112}
113
114/// One image the book refers to, sized from its header.
115///
116/// What `DrawItem::Image.asset` indexes, and all the display structure
117/// says about an image: painters take the url back to their own
118/// pixels.
119#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
120pub struct Asset {
121    /// The url the content tree named it by.
122    pub url: String,
123    /// What the header says it is.
124    pub intrinsic: Intrinsic,
125}
126
127/// Every image one book refers to, probed once and indexed.
128///
129/// `DrawItem::Image.asset` indexes this: layout places an image by
130/// number, and painters resolve the number back to bytes.
131#[derive(Debug, Default)]
132pub struct Assets {
133    assets: Vec<Asset>,
134    /// The file each asset was probed from, in the same order.
135    /// Layout read the header out of these; the PDF writer embeds
136    /// them.
137    files: Vec<Vec<u8>>,
138    /// A hash of each file, in the same order: what tells a url
139    /// registered again with the same bytes from one registered
140    /// again with different ones.
141    hashes: Vec<u64>,
142    /// Urls that were offered and could not be sized, so that a url
143    /// nothing has ever answered for can be told apart from one
144    /// already complained about.
145    refused: BTreeSet<String>,
146    warnings: Vec<Warning>,
147}
148
149/// What registering an image did.
150#[derive(Debug, Clone, Copy, PartialEq)]
151pub enum Added {
152    /// The bytes already registered at this url, unchanged.
153    Unchanged(u32),
154    /// New bytes at this index: the url's first registration, or
155    /// different bytes replacing what was there. `previous` is the
156    /// intrinsic size that answered for it before, `None` for a
157    /// fresh url — what a session reads to decide whether the box an
158    /// image takes moved.
159    Replaced {
160        /// The index the bytes answer for.
161        index: u32,
162        /// What the same index reported before, if anything did.
163        previous: Option<Intrinsic>,
164        /// What it reports now.
165        current: Intrinsic,
166    },
167    /// The bytes did not probe: no size could be read from them.
168    Refused,
169}
170
171/// What one file hashes to, for telling a registration of the same
172/// bytes from one of different bytes at the same url.
173fn content_hash(bytes: &[u8]) -> u64 {
174    let mut hasher = DefaultHasher::new();
175    bytes.hash(&mut hasher);
176    hasher.finish()
177}
178
179impl Assets {
180    /// No images at all: what a host with no loader supplies.
181    pub fn none() -> Assets {
182        Assets::default()
183    }
184
185    /// Probes every image the book places and every image its sheet
186    /// puts behind a box, the manuscript's own first. A url the
187    /// loader cannot resolve, or bytes no probe recognises, is a
188    /// diagnostic and no asset.
189    ///
190    /// A sheet that names no background image offers the loader
191    /// nothing beyond what the manuscript named.
192    pub fn probe(book: &Book, styles: &StyleTree, loader: &dyn ImageLoader) -> Assets {
193        let mut assets = Assets::default();
194        for section in &book.sections {
195            assets.walk(&section.blocks, loader);
196        }
197        for background in backgrounds(styles) {
198            assets.take(background, loader);
199        }
200        assets
201    }
202
203    /// Registers one image the host handed over, and what that did:
204    /// the same bytes it already had, new bytes at a fresh or
205    /// existing index, or bytes no probe recognises.
206    ///
207    /// This is the door for a host that pushes: a worker has no
208    /// loader to reach back through, so images cross the wall the
209    /// way font files do. A url pushed again with the bytes it
210    /// already answers for costs nothing; pushed again with
211    /// different bytes, it replaces them in place, keeping the index
212    /// `DrawItem::Image.asset` already names.
213    pub fn add(&mut self, url: &str, bytes: Vec<u8>) -> Added {
214        let hash = content_hash(&bytes);
215        if let Some(index) = self.assets.iter().position(|asset| asset.url == url) {
216            if self.hashes[index] == hash {
217                return Added::Unchanged(index as u32);
218            }
219            return match probe(&bytes) {
220                Some(intrinsic) => {
221                    let previous = self.assets[index].intrinsic;
222                    self.assets[index] = Asset {
223                        url: url.to_string(),
224                        intrinsic,
225                    };
226                    self.files[index] = bytes;
227                    self.hashes[index] = hash;
228                    self.refused.remove(url);
229                    Added::Replaced {
230                        index: index as u32,
231                        previous: Some(previous),
232                        current: intrinsic,
233                    }
234                }
235                None => {
236                    self.refuse(url, None);
237                    Added::Refused
238                }
239            };
240        }
241        match probe(&bytes) {
242            Some(intrinsic) => {
243                self.refused.remove(url);
244                self.assets.push(Asset {
245                    url: url.to_string(),
246                    intrinsic,
247                });
248                self.files.push(bytes);
249                self.hashes.push(hash);
250                Added::Replaced {
251                    index: self.assets.len() as u32 - 1,
252                    previous: None,
253                    current: intrinsic,
254                }
255            }
256            None => {
257                self.refuse(url, None);
258                Added::Refused
259            }
260        }
261    }
262
263    /// The asset registered for a url, and its index.
264    pub fn lookup(&self, url: &str) -> Option<(u32, Intrinsic)> {
265        self.assets
266            .iter()
267            .position(|asset| asset.url == url)
268            .map(|index| (index as u32, self.assets[index].intrinsic))
269    }
270
271    /// Whether a url has been probed: an asset came of it, or a
272    /// complaint about why none did. A url nobody offered is neither,
273    /// and is what layout reports.
274    pub fn probed(&self, url: &str) -> bool {
275        self.refused.contains(url) || self.lookup(url).is_some()
276    }
277
278    /// Every asset, in the order `DrawItem::Image.asset` indexes them.
279    pub fn assets(&self) -> &[Asset] {
280        &self.assets
281    }
282
283    /// The file one asset was probed from: the bytes a painter
284    /// embeds, unchanged from what the host handed over.
285    pub fn bytes(&self, index: u32) -> Option<&[u8]> {
286        self.files.get(index as usize).map(Vec::as_slice)
287    }
288
289    /// What one asset's file hashes to: what tells a trace of the
290    /// bytes an index holds now from a trace of the bytes it held
291    /// before.
292    pub fn digest(&self, index: u32) -> Option<u64> {
293        self.hashes.get(index as usize).copied()
294    }
295
296    /// What probing had to complain about.
297    pub fn warnings(&self) -> &[Warning] {
298        &self.warnings
299    }
300
301    fn refuse(&mut self, url: &str, origin: Option<String>) {
302        if self.refused.insert(url.to_string()) {
303            self.warnings.push(Warning {
304                message: format!("Image {url} has no size in it. The image is skipped."),
305                origin,
306            });
307        }
308    }
309
310    /// Probes one url the sheet named, at the position it was
311    /// written.
312    fn take(&mut self, url: &Url, loader: &dyn ImageLoader) {
313        if self.probed(&url.value) {
314            return;
315        }
316        match loader.load(&url.value) {
317            Some(bytes) => match probe(&bytes) {
318                Some(intrinsic) => {
319                    self.assets.push(Asset {
320                        url: url.value.clone(),
321                        intrinsic,
322                    });
323                    self.hashes.push(content_hash(&bytes));
324                    self.files.push(bytes);
325                }
326                None => self.refuse(&url.value, url.origin.clone()),
327            },
328            None => self.refuse(&url.value, url.origin.clone()),
329        }
330    }
331
332    fn walk(&mut self, blocks: &[Block], loader: &dyn ImageLoader) {
333        for block in blocks {
334            match block {
335                Block::Image { url, position, .. } => {
336                    if self.probed(url) {
337                        continue;
338                    }
339                    let origin = Some(crate::content::origin(None, *position));
340                    match loader.load(url) {
341                        Some(bytes) => match probe(&bytes) {
342                            Some(intrinsic) => {
343                                self.assets.push(Asset {
344                                    url: url.clone(),
345                                    intrinsic,
346                                });
347                                self.hashes.push(content_hash(&bytes));
348                                self.files.push(bytes);
349                            }
350                            None => self.refuse(url, origin),
351                        },
352                        None => self.refuse(url, origin),
353                    }
354                }
355                Block::Blockquote { blocks, .. } => self.walk(blocks, loader),
356                Block::Table { head, body, .. } => {
357                    for blocks in crate::content::cell_blocks(head, body) {
358                        self.walk(blocks, loader);
359                    }
360                }
361                _ => {}
362            }
363        }
364    }
365}
366
367/// Every image a book's sheet puts behind a box: one per block style
368/// and one per page master, in a stable order.
369pub fn backgrounds(styles: &StyleTree) -> Vec<&Url> {
370    styles
371        .styles()
372        .iter()
373        .filter_map(|style| style.background.image.as_ref())
374        .chain(
375            styles
376                .masters()
377                .iter()
378                .filter_map(|master| master.style.background.image.as_ref()),
379        )
380        .collect()
381}
382
383/// Every contour a book's sheet asked for, traced once and kept by
384/// asset.
385///
386/// This is the trace stage. Nothing is traced because it is an image.
387/// It is traced because a rule that matched it resolved to
388/// `shape-outside: auto`, and that is not reachable from where
389/// probing happens: probing takes a book and a loader, and neither
390/// has seen the style tree.
391///
392/// The stage sits above line breaking, because a contour that moved
393/// is a measure that moved. It keeps what an earlier run traced, so a
394/// sheet edit that leaves the contours where they were decodes
395/// nothing.
396#[derive(Debug, Default)]
397pub struct Contours {
398    traced: BTreeMap<u32, Traced>,
399    warned: BTreeSet<String>,
400    warnings: Vec<Warning>,
401}
402
403/// Whether one node's styling asks for a contour the flow can read.
404///
405/// Both halves matter. A sheet that names `auto` on an element it
406/// leaves in the flow asks for a contour nothing sets beside, and an
407/// image is not decoded to answer that.
408fn traceable(style: &ComputedStyle) -> bool {
409    style.shape_outside == ShapeOutside::Auto && style.excludes()
410}
411
412/// One asset's trace, and the bytes it was traced from.
413#[derive(Debug)]
414struct Traced {
415    digest: u64,
416    contour: Option<Contour>,
417}
418
419impl Contours {
420    /// Nothing traced: what a book whose sheet names no contour
421    /// carries.
422    pub fn none() -> Contours {
423        Contours::default()
424    }
425
426    /// Traces every asset the cascade asks for and this table does not
427    /// already answer for, and reports how many images it decoded.
428    ///
429    /// A book whose sheet names no contour decodes nothing, and so
430    /// does one whose contours are all traced already.
431    pub fn update(&mut self, book: &Book, styles: &StyleTree, assets: &Assets) -> u32 {
432        fn walk(
433            contours: &mut Contours,
434            blocks: &[Block],
435            source: Option<&str>,
436            styles: &StyleTree,
437            assets: &Assets,
438            traced: &mut u32,
439        ) {
440            for block in blocks {
441                match block {
442                    Block::Blockquote { blocks, .. } => {
443                        walk(contours, blocks, source, styles, assets, traced)
444                    }
445                    Block::Table { head, body, .. } => {
446                        for blocks in crate::content::cell_blocks(head, body) {
447                            walk(contours, blocks, source, styles, assets, traced);
448                        }
449                    }
450                    Block::Image {
451                        id, url, position, ..
452                    } if traceable(styles.style(*id)) => {
453                        let Some(((index, _), digest)) = assets
454                            .lookup(url)
455                            .and_then(|found| Some((found, assets.digest(found.0)?)))
456                        else {
457                            continue;
458                        };
459                        let kept = contours
460                            .traced
461                            .get(&index)
462                            .is_some_and(|kept| kept.digest == digest);
463                        if !kept {
464                            let contour = assets.bytes(index).and_then(trace);
465                            *traced += 1;
466                            contours.traced.insert(index, Traced { digest, contour });
467                        }
468                        if contours.get(index).is_none() && contours.warned.insert(url.clone()) {
469                            let origin = crate::content::origin(source, *position);
470                            contours.warnings.push(Warning {
471                                message: format!(
472                                    "Missing alpha channel in {url}. Text wraps around the \
473                                     image rectangle."
474                                ),
475                                origin: (!origin.is_empty()).then_some(origin),
476                            });
477                        }
478                    }
479                    _ => {}
480                }
481            }
482        }
483        // The warnings are this run's: a sheet that stopped asking
484        // for a contour leaves none behind.
485        self.warnings.clear();
486        self.warned.clear();
487        let mut traced = 0;
488        for section in &book.sections {
489            walk(
490                self,
491                &section.blocks,
492                section.source.as_deref(),
493                styles,
494                assets,
495                &mut traced,
496            );
497        }
498        traced
499    }
500
501    /// The contour one asset traced to, and `None` where it traced to
502    /// nothing or was never asked for.
503    pub fn get(&self, asset: u32) -> Option<&Contour> {
504        self.traced.get(&asset)?.contour.as_ref()
505    }
506
507    /// Whether this table holds a trace of one asset, whatever the
508    /// trace found.
509    pub fn traces(&self, asset: u32) -> bool {
510        self.traced.contains_key(&asset)
511    }
512
513    /// What tracing had to complain about.
514    pub fn warnings(&self) -> &[Warning] {
515        &self.warnings
516    }
517}
518
519/// The outline prose sets around, in the image's own box.
520///
521/// A ring is a closed loop of points, `(0, 0)` at the top left of the
522/// image and `(1, 1)` at its bottom right. An image whose alpha
523/// leaves two shapes with clear space between them traces to two
524/// rings, and the prose sets through the space.
525#[derive(Debug, Clone, PartialEq)]
526pub struct Contour {
527    /// The rings, each closed by its own first point.
528    pub rings: Vec<Vec<[f32; 2]>>,
529}
530
531/// How many rows a trace reports, so that the outline one image
532/// traces to is the same size whatever the image's pixel count is.
533const ROWS: u32 = 128;
534
535/// The largest image the tracer decodes. A file above this contributes
536/// its box, because the buffer a decode wants is the picture again in
537/// memory and a contour is not worth that.
538const CEILING: u64 = 32 * 1024 * 1024;
539
540/// The alpha channel of one image, one byte to a pixel.
541struct Mask {
542    width: u32,
543    height: u32,
544    alpha: Vec<u8>,
545}
546
547impl Mask {
548    /// The first and last covered pixel of every row, `None` for a
549    /// row nothing covers.
550    fn rows(&self) -> Vec<Option<(u32, u32)>> {
551        (0..self.height)
552            .map(|y| {
553                let row = &self.alpha[(y * self.width) as usize..][..self.width as usize];
554                let first = row.iter().position(|alpha| *alpha > 0)? as u32;
555                let last = row.iter().rposition(|alpha| *alpha > 0)? as u32;
556                Some((first, last + 1))
557            })
558            .collect()
559    }
560}
561
562/// Traces one image's alpha channel. `None` where the format carries
563/// no alpha, where the file does not decode, or where it is larger
564/// than the tracer decodes.
565///
566/// The outline is reported over a fixed number of bands rather than
567/// over the image's own rows, so two images of the same shape and
568/// different resolutions trace to the same size of outline.
569pub fn trace(bytes: &[u8]) -> Option<Contour> {
570    let mask = mask(bytes)?;
571    let rows = mask.rows();
572    let bands: Vec<Option<(f32, f32)>> = (0..ROWS)
573        .map(|band| {
574            let from = (band as u64 * mask.height as u64 / ROWS as u64) as usize;
575            let to = ((band as u64 + 1) * mask.height as u64 / ROWS as u64).max(from as u64 + 1);
576            rows.get(from..(to as usize).min(rows.len()))?
577                .iter()
578                .flatten()
579                .copied()
580                .reduce(|(left, right), (start, end)| (left.min(start), right.max(end)))
581                .map(|(left, right)| {
582                    (
583                        left as f32 / mask.width as f32,
584                        right as f32 / mask.width as f32,
585                    )
586                })
587        })
588        .collect();
589    Some(Contour {
590        rings: rings(&bands),
591    })
592}
593
594/// One ring for every run of bands the alpha covers, in reading
595/// order. A band nothing covers ends the ring above it, which is what
596/// lets prose set through a gap in the image.
597fn rings(bands: &[Option<(f32, f32)>]) -> Vec<Vec<[f32; 2]>> {
598    let mut rings = Vec::new();
599    let mut run: Vec<(usize, (f32, f32))> = Vec::new();
600    let height = bands.len() as f32;
601    let close = |run: &mut Vec<(usize, (f32, f32))>, rings: &mut Vec<Vec<[f32; 2]>>| {
602        if run.is_empty() {
603            return;
604        }
605        let edge = |side: fn(&(f32, f32)) -> f32, run: &[(usize, (f32, f32))]| {
606            let mut points: Vec<[f32; 2]> = Vec::new();
607            for (band, span) in run {
608                let (top, bottom) = (*band as f32 / height, (*band + 1) as f32 / height);
609                let x = side(span);
610                // A band no wider than the one above it needs no
611                // corner of its own.
612                match points.last_mut() {
613                    Some(last) if last[0] == x => last[1] = bottom,
614                    _ => {
615                        points.push([x, top]);
616                        points.push([x, bottom]);
617                    }
618                }
619            }
620            points
621        };
622        let mut ring = edge(|span| span.0, run);
623        let mut right = edge(|span| span.1, run);
624        right.reverse();
625        ring.append(&mut right);
626        rings.push(ring);
627        run.clear();
628    };
629    for (band, span) in bands.iter().enumerate() {
630        match span {
631            Some(span) => run.push((band, *span)),
632            None => close(&mut run, &mut rings),
633        }
634    }
635    close(&mut run, &mut rings);
636    rings
637}
638
639/// The alpha channel of one file, for the formats that carry one.
640fn mask(bytes: &[u8]) -> Option<Mask> {
641    let intrinsic = probe(bytes)?;
642    if intrinsic.width as u64 * intrinsic.height as u64 > CEILING {
643        return None;
644    }
645    png_mask(bytes)
646        .or_else(|| webp_mask(bytes))
647        .or_else(|| gif_mask(bytes))
648}
649
650/// PNG. `normalize_to_color8` expands a palette and a `tRNS` chunk,
651/// so an alpha channel arrives however the file wrote it.
652fn png_mask(bytes: &[u8]) -> Option<Mask> {
653    let mut decoder = png::Decoder::new(bytes);
654    decoder.set_transformations(png::Transformations::normalize_to_color8());
655    let mut reader = decoder.read_info().ok()?;
656    let (channels, offset) = match reader.output_color_type() {
657        (png::ColorType::Rgba, _) => (4, 3),
658        (png::ColorType::GrayscaleAlpha, _) => (2, 1),
659        _ => return None,
660    };
661    let mut buffer = vec![0u8; reader.output_buffer_size()];
662    let info = reader.next_frame(&mut buffer).ok()?;
663    Some(Mask {
664        width: info.width,
665        height: info.height,
666        alpha: buffer[..(info.width * info.height * channels) as usize]
667            .iter()
668            .skip(offset)
669            .step_by(channels as usize)
670            .copied()
671            .collect(),
672    })
673}
674
675/// WebP, when the file declares an alpha channel.
676fn webp_mask(bytes: &[u8]) -> Option<Mask> {
677    let mut decoder = image_webp::WebPDecoder::new(std::io::Cursor::new(bytes)).ok()?;
678    if !decoder.has_alpha() {
679        return None;
680    }
681    let (width, height) = decoder.dimensions();
682    let mut buffer = vec![0u8; decoder.output_buffer_size()?];
683    decoder.read_image(&mut buffer).ok()?;
684    Some(Mask {
685        width,
686        height,
687        alpha: buffer.iter().skip(3).step_by(4).copied().collect(),
688    })
689}
690
691/// GIF, whose transparency is one palette entry. The first frame is
692/// the image, and a frame smaller than the screen leaves the rest of
693/// it clear.
694fn gif_mask(bytes: &[u8]) -> Option<Mask> {
695    let mut options = gif::DecodeOptions::new();
696    options.set_color_output(gif::ColorOutput::RGBA);
697    let mut decoder = options.read_info(bytes).ok()?;
698    let (width, height) = (decoder.width() as u32, decoder.height() as u32);
699    let frame = decoder.read_next_frame().ok()??;
700    let mut alpha = vec![0u8; (width * height) as usize];
701    for y in 0..frame.height as u32 {
702        for x in 0..frame.width as u32 {
703            let (at_x, at_y) = (x + frame.left as u32, y + frame.top as u32);
704            if at_x >= width || at_y >= height {
705                continue;
706            }
707            alpha[(at_y * width + at_x) as usize] =
708                frame.buffer[((y * frame.width as u32 + x) * 4 + 3) as usize];
709        }
710    }
711    Some(Mask {
712        width,
713        height,
714        alpha,
715    })
716}
717
718/// Reads an image's size from its header. `None` for a format no
719/// probe recognises, or a header too short to read one from.
720pub fn probe(bytes: &[u8]) -> Option<Intrinsic> {
721    png(bytes)
722        .or_else(|| jpeg(bytes))
723        .or_else(|| gif(bytes))
724        .or_else(|| webp(bytes))
725        .or_else(|| svg(bytes))
726}
727
728/// Whether a file is an SVG: its root element is `svg`.
729pub fn is_svg(bytes: &[u8]) -> bool {
730    svg_root(bytes).is_some()
731}
732
733fn be32(bytes: &[u8], at: usize) -> Option<u32> {
734    let slice: [u8; 4] = bytes.get(at..at + 4)?.try_into().ok()?;
735    Some(u32::from_be_bytes(slice))
736}
737
738fn be16(bytes: &[u8], at: usize) -> Option<u16> {
739    let slice: [u8; 2] = bytes.get(at..at + 2)?.try_into().ok()?;
740    Some(u16::from_be_bytes(slice))
741}
742
743fn le16(bytes: &[u8], at: usize) -> Option<u16> {
744    let slice: [u8; 2] = bytes.get(at..at + 2)?.try_into().ok()?;
745    Some(u16::from_le_bytes(slice))
746}
747
748/// PNG: `IHDR` is always the first chunk, and `pHYs` — when it is
749/// there — says how many pixels go to a metre.
750fn png(bytes: &[u8]) -> Option<Intrinsic> {
751    if !bytes.starts_with(b"\x89PNG\r\n\x1a\n") || bytes.get(12..16)? != b"IHDR" {
752        return None;
753    }
754    let mut intrinsic = Intrinsic {
755        width: be32(bytes, 16)?,
756        height: be32(bytes, 20)?,
757        dpi_x: CSS_DPI,
758        dpi_y: CSS_DPI,
759        sized: true,
760    };
761    let mut at = 8usize;
762    while let (Some(length), Some(kind)) = (be32(bytes, at), bytes.get(at + 4..at + 8)) {
763        if kind == b"pHYs" {
764            let data = at + 8;
765            // Unit 1 is the metre; anything else is an aspect ratio
766            // with no absolute size in it.
767            if bytes.get(data + 8) == Some(&1) {
768                let (x, y) = (be32(bytes, data)?, be32(bytes, data + 4)?);
769                if x > 0 && y > 0 {
770                    intrinsic.dpi_x = x as f32 * 0.0254;
771                    intrinsic.dpi_y = y as f32 * 0.0254;
772                }
773            }
774            break;
775        }
776        if kind == b"IDAT" {
777            break;
778        }
779        at = at.checked_add(12)?.checked_add(length as usize)?;
780    }
781    Some(intrinsic)
782}
783
784/// JPEG: walk the marker segments to the frame header, picking up the
785/// JFIF density on the way.
786fn jpeg(bytes: &[u8]) -> Option<Intrinsic> {
787    if !bytes.starts_with(&[0xFF, 0xD8]) {
788        return None;
789    }
790    let (mut dpi_x, mut dpi_y) = (CSS_DPI, CSS_DPI);
791    let mut at = 2usize;
792    loop {
793        if bytes.get(at) != Some(&0xFF) {
794            return None;
795        }
796        let marker = *bytes.get(at + 1)?;
797        // Padding fill bytes, and the standalone markers with no
798        // segment at all.
799        if marker == 0xFF {
800            at += 1;
801            continue;
802        }
803        if (0xD0..=0xD9).contains(&marker) || marker == 0x01 {
804            at += 2;
805            continue;
806        }
807        let length = be16(bytes, at + 2)? as usize;
808        let data = at + 4;
809        if marker == 0xE0 && bytes.get(data..data + 5) == Some(b"JFIF\0") {
810            let (x, y) = (be16(bytes, data + 8)?, be16(bytes, data + 10)?);
811            let per_inch = match bytes.get(data + 7) {
812                Some(1) => Some(1.0),
813                Some(2) => Some(2.54),
814                _ => None,
815            };
816            if let Some(scale) = per_inch
817                && x > 0
818                && y > 0
819            {
820                dpi_x = x as f32 * scale;
821                dpi_y = y as f32 * scale;
822            }
823        }
824        // SOF0-SOF15, less the three markers that share their range
825        // and are not frame headers.
826        if (0xC0..=0xCF).contains(&marker) && !matches!(marker, 0xC4 | 0xC8 | 0xCC) {
827            return Some(Intrinsic {
828                width: be16(bytes, data + 3)? as u32,
829                height: be16(bytes, data + 1)? as u32,
830                dpi_x,
831                dpi_y,
832                sized: true,
833            });
834        }
835        if marker == 0xDA {
836            return None;
837        }
838        at = at.checked_add(2)?.checked_add(length)?;
839    }
840}
841
842/// GIF: the logical screen descriptor, which has no resolution in it.
843fn gif(bytes: &[u8]) -> Option<Intrinsic> {
844    if !bytes.starts_with(b"GIF87a") && !bytes.starts_with(b"GIF89a") {
845        return None;
846    }
847    Some(Intrinsic {
848        width: le16(bytes, 6)? as u32,
849        height: le16(bytes, 8)? as u32,
850        dpi_x: CSS_DPI,
851        dpi_y: CSS_DPI,
852        sized: true,
853    })
854}
855
856/// WebP: the extended header when there is one, the lossy or lossless
857/// frame header otherwise. None of the three records a resolution.
858fn webp(bytes: &[u8]) -> Option<Intrinsic> {
859    if !bytes.starts_with(b"RIFF") || bytes.get(8..12)? != b"WEBP" {
860        return None;
861    }
862    let size = |width: u32, height: u32| {
863        Some(Intrinsic {
864            width,
865            height,
866            dpi_x: CSS_DPI,
867            dpi_y: CSS_DPI,
868            sized: true,
869        })
870    };
871    match bytes.get(12..16)? {
872        b"VP8X" => {
873            let at = 24;
874            let three = |from: usize| -> Option<u32> {
875                let bytes = bytes.get(from..from + 3)?;
876                Some(u32::from(bytes[0]) | u32::from(bytes[1]) << 8 | u32::from(bytes[2]) << 16)
877            };
878            size(three(at)? + 1, three(at + 3)? + 1)
879        }
880        b"VP8 " => {
881            // The keyframe's start code, then the dimensions with two
882            // scale bits above each of them.
883            if bytes.get(23..26)? != [0x9D, 0x01, 0x2A] {
884                return None;
885            }
886            size(
887                (le16(bytes, 26)? & 0x3FFF) as u32,
888                (le16(bytes, 28)? & 0x3FFF) as u32,
889            )
890        }
891        b"VP8L" => {
892            if bytes.get(20) != Some(&0x2F) {
893                return None;
894            }
895            let bits = u32::from_le_bytes(bytes.get(21..25)?.try_into().ok()?);
896            size((bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1)
897        }
898        _ => None,
899    }
900}
901
902/// SVG: the root element's `width` and `height` where they are
903/// absolute lengths, and its `viewBox` for a side they leave out. A
904/// root with a `viewBox` and no size gives a ratio alone.
905fn svg(bytes: &[u8]) -> Option<Intrinsic> {
906    let root = svg_root(bytes)?;
907    let width = attribute(root, "width").and_then(svg_length);
908    let height = attribute(root, "height").and_then(svg_length);
909    let view = attribute(root, "viewBox").and_then(view_box);
910    match (width, height, view) {
911        (Some(width), Some(height), _) => vector(width, height, true),
912        (Some(width), None, Some((across, down))) => vector(width, width * down / across, true),
913        (None, Some(height), Some((across, down))) => vector(height * across / down, height, true),
914        (None, None, Some((across, down))) => vector(across, down, false),
915        _ => None,
916    }
917}
918
919/// A size in CSS pixels as an [`Intrinsic`]. The pixel count is the
920/// nearest whole one, and the resolution makes up the difference.
921fn vector(width: f32, height: f32, sized: bool) -> Option<Intrinsic> {
922    let whole = |side: f32| side.round().max(1.0);
923    let finite = |side: f32| side.is_finite() && side > 0.0;
924    (finite(width) && finite(height)).then(|| Intrinsic {
925        width: whole(width) as u32,
926        height: whole(height) as u32,
927        dpi_x: CSS_DPI * whole(width) / width,
928        dpi_y: CSS_DPI * whole(height) / height,
929        sized,
930    })
931}
932
933/// The attributes of the root element, where that element is `svg`.
934/// An XML declaration, a doctype and comments may come before it.
935fn svg_root(bytes: &[u8]) -> Option<&str> {
936    let after = |rest: &[u8], close: &[u8]| -> Option<usize> {
937        rest.windows(close.len())
938            .position(|window| window == close)
939            .map(|at| at + close.len())
940    };
941    let mut rest = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
942    loop {
943        rest = rest.trim_ascii_start();
944        let skip = if rest.starts_with(b"<?") {
945            after(rest, b"?>")?
946        } else if rest.starts_with(b"<!--") {
947            after(rest, b"-->")?
948        } else if rest.starts_with(b"<!") {
949            // A doctype may hold declarations of its own in brackets.
950            match rest.iter().position(|byte| matches!(byte, b'[' | b'>'))? {
951                at if rest[at] == b'[' => at + after(&rest[at..], b"]>")?,
952                at => at + 1,
953            }
954        } else {
955            break;
956        };
957        rest = &rest[skip..];
958    }
959    let rest = rest.strip_prefix(b"<")?;
960    let name = rest
961        .iter()
962        .position(|byte| byte.is_ascii_whitespace() || matches!(byte, b'>' | b'/'))?;
963    if rest[..name].rsplit(|byte| *byte == b':').next()? != b"svg" {
964        return None;
965    }
966    let mut quote = None;
967    for (at, byte) in rest.iter().enumerate().skip(name) {
968        match (quote, byte) {
969            (Some(open), _) if open == byte => quote = None,
970            (Some(_), _) => {}
971            (None, b'"' | b'\'') => quote = Some(byte),
972            (None, b'>') => return std::str::from_utf8(&rest[name..at]).ok(),
973            (None, _) => {}
974        }
975    }
976    None
977}
978
979/// One attribute's value out of a tag's attributes.
980fn attribute<'a>(mut tag: &'a str, name: &str) -> Option<&'a str> {
981    loop {
982        let (key, rest) = tag.split_once('=')?;
983        let rest = rest.trim_start();
984        let quote = rest.chars().next().filter(|c| matches!(c, '"' | '\''))?;
985        let (value, rest) = rest[1..].split_once(quote)?;
986        if key.trim() == name {
987            return Some(value);
988        }
989        tag = rest;
990    }
991}
992
993/// An absolute SVG length in CSS pixels. A percentage and a length
994/// relative to a font are `None`: neither is a size the file has on
995/// its own.
996fn svg_length(value: &str) -> Option<f32> {
997    let value = value.trim();
998    let number = value.trim_end_matches(|c: char| c.is_ascii_alphabetic() || c == '%');
999    let unit = &value[number.len()..];
1000    let per = [
1001        ("", 1.0),
1002        ("px", 1.0),
1003        ("pt", CSS_DPI / 72.0),
1004        ("pc", CSS_DPI / 6.0),
1005        ("in", CSS_DPI),
1006        ("cm", CSS_DPI / 2.54),
1007        ("mm", CSS_DPI / 25.4),
1008        ("q", CSS_DPI / 101.6),
1009    ]
1010    .into_iter()
1011    .find_map(|(name, per)| unit.eq_ignore_ascii_case(name).then_some(per))?;
1012    let pixels = number.parse::<f32>().ok()? * per;
1013    (pixels.is_finite() && pixels > 0.0).then_some(pixels)
1014}
1015
1016/// The width and height of a `viewBox`.
1017fn view_box(value: &str) -> Option<(f32, f32)> {
1018    let mut numbers = value
1019        .split(|c: char| c.is_ascii_whitespace() || c == ',')
1020        .filter(|part| !part.is_empty())
1021        .map(|part| part.parse::<f32>().ok());
1022    let (_, _, width, height) = (
1023        numbers.next()??,
1024        numbers.next()??,
1025        numbers.next()??,
1026        numbers.next()??,
1027    );
1028    (numbers.next().is_none() && width > 0.0 && height > 0.0).then_some((width, height))
1029}
1030
1031#[cfg(test)]
1032mod tests {
1033    use super::*;
1034    use crate::content::Attributes;
1035
1036    /// A table loads what the host handed over, by its url, and
1037    /// nothing it refused.
1038    #[test]
1039    fn a_table_loads_the_bytes_a_url_was_registered_with() {
1040        let mut assets = Assets::none();
1041        let png = png_bytes(4, 2, None);
1042        assets.add("a.png", png.clone());
1043        assets.add("b.bmp", b"BM....".to_vec());
1044        assert_eq!(ImageLoader::load(&assets, "a.png"), Some(png));
1045        assert_eq!(ImageLoader::load(&assets, "b.bmp"), None);
1046        assert_eq!(ImageLoader::load(&assets, "c.png"), None);
1047    }
1048
1049    /// A PNG header: signature, `IHDR`, and optionally a `pHYs`
1050    /// declaring pixels per metre.
1051    fn png_bytes(width: u32, height: u32, ppm: Option<u32>) -> Vec<u8> {
1052        let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec();
1053        bytes.extend(13u32.to_be_bytes());
1054        bytes.extend(b"IHDR");
1055        bytes.extend(width.to_be_bytes());
1056        bytes.extend(height.to_be_bytes());
1057        bytes.extend([8, 6, 0, 0, 0]);
1058        bytes.extend([0, 0, 0, 0]); // crc
1059        if let Some(ppm) = ppm {
1060            bytes.extend(9u32.to_be_bytes());
1061            bytes.extend(b"pHYs");
1062            bytes.extend(ppm.to_be_bytes());
1063            bytes.extend(ppm.to_be_bytes());
1064            bytes.push(1);
1065            bytes.extend([0, 0, 0, 0]);
1066        }
1067        bytes.extend(0u32.to_be_bytes());
1068        bytes.extend(b"IDAT");
1069        bytes
1070    }
1071
1072    /// A JPEG header: an optional JFIF density, then a baseline frame.
1073    fn jpeg_bytes(width: u16, height: u16, density: Option<u16>) -> Vec<u8> {
1074        let mut bytes = vec![0xFF, 0xD8];
1075        if let Some(density) = density {
1076            bytes.extend([0xFF, 0xE0, 0x00, 0x10]);
1077            bytes.extend(b"JFIF\0");
1078            bytes.extend([1, 2, 1]); // version, units: inches
1079            bytes.extend(density.to_be_bytes());
1080            bytes.extend(density.to_be_bytes());
1081            bytes.extend([0, 0]);
1082        }
1083        bytes.extend([0xFF, 0xC0, 0x00, 0x11, 0x08]);
1084        bytes.extend(height.to_be_bytes());
1085        bytes.extend(width.to_be_bytes());
1086        bytes
1087    }
1088
1089    /// An RGBA PNG whose alpha `covered` decides, pixel by pixel.
1090    fn rgba_png(width: u32, height: u32, covered: impl Fn(u32, u32) -> bool) -> Vec<u8> {
1091        let mut pixels = Vec::with_capacity((width * height * 4) as usize);
1092        for y in 0..height {
1093            for x in 0..width {
1094                pixels.extend([0x33, 0x44, 0x55, if covered(x, y) { 0xFF } else { 0 }]);
1095            }
1096        }
1097        let mut bytes = Vec::new();
1098        let mut encoder = png::Encoder::new(&mut bytes, width, height);
1099        encoder.set_color(png::ColorType::Rgba);
1100        encoder.set_depth(png::BitDepth::Eight);
1101        let mut writer = encoder.write_header().expect("the header writes");
1102        writer.write_image_data(&pixels).expect("the pixels write");
1103        writer.finish().expect("the file closes");
1104        bytes
1105    }
1106
1107    /// The leftmost and rightmost point a contour reaches between two
1108    /// heights, as a fraction of the image's width.
1109    fn span(contour: &Contour, top: f32, bottom: f32) -> Option<(f32, f32)> {
1110        let mut reach: Option<(f32, f32)> = None;
1111        for ring in &contour.rings {
1112            for point in ring {
1113                if point[1] < top || point[1] > bottom {
1114                    continue;
1115                }
1116                reach = Some(match reach {
1117                    None => (point[0], point[0]),
1118                    Some((left, right)) => (left.min(point[0]), right.max(point[0])),
1119                });
1120            }
1121        }
1122        reach
1123    }
1124
1125    /// The alpha channel decides the contour: a shape that covers half
1126    /// of every row traces to a contour half the width of the image,
1127    /// and one that widens down the image traces to a contour that
1128    /// widens with it.
1129    #[test]
1130    fn an_alpha_channel_traces_to_the_shape_it_covers() {
1131        let half = trace(&rgba_png(64, 64, |x, _| x < 32)).expect("a PNG with alpha traces");
1132        assert_eq!(half.rings.len(), 1);
1133        assert_eq!(span(&half, 0.0, 1.0), Some((0.0, 0.5)));
1134
1135        // A wedge: one pixel wide at the top, the whole width at the
1136        // bottom.
1137        let wedge = trace(&rgba_png(64, 64, |x, y| x <= y)).expect("a PNG with alpha traces");
1138        let (_, top) = span(&wedge, 0.0, 0.1).expect("the top of the wedge");
1139        let (_, bottom) = span(&wedge, 0.9, 1.0).expect("the foot of the wedge");
1140        assert!(top < 0.2, "the wedge opens narrow: {top}");
1141        assert!(bottom > 0.9, "and closes wide: {bottom}");
1142    }
1143
1144    /// Clear space across the image ends one ring and opens another,
1145    /// so the prose can set through the gap.
1146    #[test]
1147    fn clear_space_across_an_image_splits_the_contour() {
1148        let split = trace(&rgba_png(64, 64, |_, y| !(24..40).contains(&y)))
1149            .expect("a PNG with alpha traces");
1150        assert_eq!(split.rings.len(), 2, "{:?}", split.rings.len());
1151        assert_eq!(span(&split, 0.4, 0.6), None, "nothing covers the gap");
1152    }
1153
1154    /// An image with nothing in it traces to no rings at all, which is
1155    /// a contour the prose sets straight through.
1156    #[test]
1157    fn an_empty_alpha_channel_traces_to_nothing() {
1158        let empty = trace(&rgba_png(16, 16, |_, _| false)).expect("a PNG with alpha traces");
1159        assert!(empty.rings.is_empty());
1160    }
1161
1162    /// A format that carries no alpha traces to nothing, and its box
1163    /// is what the prose keeps clear of. So do bytes that do not
1164    /// decode.
1165    #[test]
1166    fn a_format_without_alpha_traces_to_nothing() {
1167        assert!(trace(&jpeg_bytes(64, 64, None)).is_none());
1168        assert!(trace(&png_bytes(64, 64, None)).is_none(), "a bare header");
1169        assert!(trace(b"not an image").is_none());
1170        assert!(trace(b"").is_none());
1171    }
1172
1173    /// The same picture in two formats traces to the same contour:
1174    /// the outline is the image's shape, not the file's.
1175    #[test]
1176    fn one_shape_in_two_formats_traces_the_same() {
1177        let png = trace(include_bytes!("../../../fixtures/images/fleuron.png"))
1178            .expect("the ornament traces");
1179        let webp = trace(include_bytes!("../../../fixtures/images/fleuron.webp"))
1180            .expect("the ornament traces");
1181        assert_eq!(png.rings.len(), 1, "the ornament is one shape");
1182        for (top, bottom) in [(0.0, 0.25), (0.25, 0.5), (0.5, 0.75), (0.75, 1.0)] {
1183            let (one, two) = (span(&png, top, bottom), span(&webp, top, bottom));
1184            let (one, two) = (one.expect("the PNG covers it"), two.expect("the WebP does"));
1185            assert!(
1186                (one.0 - two.0).abs() < 0.02 && (one.1 - two.1).abs() < 0.02,
1187                "between {top} and {bottom}: {one:?} against {two:?}",
1188            );
1189        }
1190        // The ornament is set on a clear ground, so its contour is
1191        // narrower than its box.
1192        let widest = (0..8)
1193            .filter_map(|band| span(&png, band as f32 / 8.0, (band as f32 + 1.0) / 8.0))
1194            .fold(0.0f32, |widest, (left, right)| widest.max(right - left));
1195        assert!(widest < 0.95, "the contour is the box: {widest}");
1196    }
1197
1198    /// A GIF's transparent palette entry is an alpha channel like any
1199    /// other.
1200    #[test]
1201    fn a_transparent_palette_entry_traces_like_an_alpha_channel() {
1202        let (width, height) = (32u16, 32u16);
1203        let indices: Vec<u8> = (0..height)
1204            .flat_map(|y| (0..width).map(move |x| u8::from(x >= y)))
1205            .collect();
1206        let mut bytes = Vec::new();
1207        {
1208            let mut encoder =
1209                gif::Encoder::new(&mut bytes, width, height, &[0, 0, 0, 0x33, 0x44, 0x55])
1210                    .expect("the header writes");
1211            let frame = gif::Frame {
1212                width,
1213                height,
1214                buffer: std::borrow::Cow::Borrowed(&indices),
1215                transparent: Some(0),
1216                ..gif::Frame::default()
1217            };
1218            encoder.write_frame(&frame).expect("the frame writes");
1219        }
1220        let traced = trace(&bytes).expect("a GIF with a transparent entry traces");
1221        assert_eq!(traced.rings.len(), 1);
1222        let (left, _) = span(&traced, 0.0, 0.1).expect("the top of the wedge");
1223        let (foot, _) = span(&traced, 0.9, 1.0).expect("the foot of it");
1224        assert!(left < 0.1, "the wedge opens at the left edge: {left}");
1225        assert!(foot > 0.8, "and closes at the right: {foot}");
1226    }
1227
1228    /// Two runs over one image trace the same bytes to the same
1229    /// contour.
1230    #[test]
1231    fn tracing_is_deterministic() {
1232        let bytes = rgba_png(48, 32, |x, y| (x + y) % 17 < 9);
1233        assert_eq!(trace(&bytes), trace(&bytes));
1234    }
1235
1236    /// Every format the probe recognises, read back at its declared size.
1237    #[test]
1238    fn headers_give_up_their_dimensions() {
1239        assert_eq!(
1240            probe(&png_bytes(640, 480, None)).map(|i| (i.width, i.height)),
1241            Some((640, 480)),
1242        );
1243        assert_eq!(
1244            probe(&jpeg_bytes(1200, 900, None)).map(|i| (i.width, i.height)),
1245            Some((1200, 900)),
1246        );
1247        let mut gif = b"GIF89a".to_vec();
1248        gif.extend(320u16.to_le_bytes());
1249        gif.extend(200u16.to_le_bytes());
1250        assert_eq!(probe(&gif).map(|i| (i.width, i.height)), Some((320, 200)));
1251
1252        let mut webp = b"RIFF\0\0\0\0WEBPVP8X".to_vec();
1253        webp.extend([0, 0, 0, 0, 0, 0, 0, 0]); // chunk size and flags
1254        webp.extend([0x3F, 0x00, 0x00, 0x1F, 0x00, 0x00]); // 64 x 32, less one
1255        assert_eq!(probe(&webp).map(|i| (i.width, i.height)), Some((64, 32)));
1256    }
1257
1258    /// Part: the probe reads an SVG root for `width`, `height` and
1259    /// `viewBox`, and gives an intrinsic size and a ratio. An XML
1260    /// declaration, a doctype and a comment before the root are
1261    /// stepped over.
1262    #[test]
1263    fn an_svg_root_gives_up_its_size() {
1264        let plain = probe(br#"<svg xmlns="http://www.w3.org/2000/svg" width="192" height="96"/>"#)
1265            .expect("an SVG with a size probes");
1266        assert_eq!((plain.width, plain.height), (192, 96));
1267        assert_eq!(plain.size(), (144.0, 72.0));
1268        assert!(plain.sized);
1269
1270        let prefaced = probe(
1271            b"\xEF\xBB\xBF<?xml version=\"1.0\"?>\n<!-- a > rule -->\n\
1272              <!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"svg11.dtd\" [<!ENTITY a \"b\">]>\n\
1273              <svg:svg title='a > b' width='1in' height=\"36pt\" viewBox=\"0 0 10 10\">",
1274        )
1275        .expect("the root is found after its preamble");
1276        assert_eq!(prefaced.size(), (72.0, 36.0));
1277
1278        // A size no whole number of pixels holds is still exact.
1279        let metric = probe(br#"<svg width="10mm" height="2.5cm">"#).expect("metric units probe");
1280        let (width, height) = metric.size();
1281        assert!((width - 28.346).abs() < 0.001, "{width}");
1282        assert!((height - 70.866).abs() < 0.001, "{height}");
1283    }
1284
1285    /// Part: a percentage size or no size falls back to the `viewBox`
1286    /// ratio, and one side given takes the other from it.
1287    #[test]
1288    fn an_svg_without_a_size_falls_back_to_its_view_box() {
1289        for root in [
1290            r#"<svg viewBox="0 0 300 100">"#,
1291            r#"<svg width="100%" height="100%" viewBox="0,0,300,100">"#,
1292            r#"<svg width="20em" viewBox="-5 -5 300 100">"#,
1293        ] {
1294            let ratio = probe(root.as_bytes()).unwrap_or_else(|| panic!("{root} probes"));
1295            assert!(!ratio.sized, "{root} has no size of its own");
1296            assert_eq!(ratio.size(), (225.0, 75.0), "{root}");
1297            assert_eq!(ratio.size_within(360.0), (360.0, 120.0), "{root}");
1298        }
1299        let wide = probe(br#"<svg width="150" viewBox="0 0 300 100">"#).unwrap();
1300        assert!(wide.sized);
1301        assert_eq!((wide.width, wide.height), (150, 50));
1302        let tall = probe(br#"<svg height="50" viewBox="0 0 300 100">"#).unwrap();
1303        assert_eq!((tall.width, tall.height), (150, 50));
1304        assert_eq!(
1305            tall.size_within(360.0),
1306            tall.size(),
1307            "a sized image keeps its size"
1308        );
1309    }
1310
1311    /// Part: an SVG with no size and no `viewBox` warns and is
1312    /// skipped, the way an unreadable file is. The warning is raised
1313    /// once however often the url is offered.
1314    #[test]
1315    fn an_svg_with_no_size_and_no_view_box_is_refused_once() {
1316        for root in [
1317            "<svg xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M0 0\"/></svg>",
1318            "<svg width=\"100%\" height=\"50%\">",
1319            "<svg width=\"120\">",
1320            "<svg viewBox=\"0 0 0 10\">",
1321            "<svg viewBox=\"0 0 10\">",
1322            "<html><svg width=\"1\" height=\"1\"/></html>",
1323            "<svg width=\"10\" height=\"10\"",
1324        ] {
1325            assert!(probe(root.as_bytes()).is_none(), "{root} probed");
1326        }
1327        let mut assets = Assets::none();
1328        let bare = b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>".to_vec();
1329        assert_eq!(assets.add("rule.svg", bare.clone()), Added::Refused);
1330        assert_eq!(assets.add("rule.svg", bare), Added::Refused);
1331        assert_eq!(assets.warnings().len(), 1);
1332        assert_eq!(
1333            assets.warnings()[0].message,
1334            "Image rule.svg has no size in it. The image is skipped.",
1335        );
1336        assert!(assets.assets().is_empty());
1337    }
1338
1339    /// An SVG root cut off anywhere is `None` rather than a panic.
1340    #[test]
1341    fn a_truncated_svg_probes_to_nothing() {
1342        let svg = "<?xml version=\"1.0\"?><!-- c --><!DOCTYPE svg [ ]>\
1343                   <svg width=\"10\" height='10' viewBox=\"0 0 1 1\">";
1344        for cut in 0..svg.len() {
1345            assert!(probe(&svg.as_bytes()[..cut]).is_none(), "cut at {cut}");
1346        }
1347        assert!(probe(svg.as_bytes()).is_some());
1348    }
1349
1350    /// An SVG has no alpha channel to trace, so it traces to nothing
1351    /// and its box is what the text goes around.
1352    #[test]
1353    fn an_svg_traces_to_nothing() {
1354        let svg = br#"<svg width="64" height="64"><circle cx="32" cy="32" r="16"/></svg>"#;
1355        assert!(is_svg(svg));
1356        assert!(trace(svg).is_none());
1357    }
1358
1359    /// A header with no resolution in it is measured at 96dpi, and one
1360    /// with a resolution is measured at that: the same pixels, a
1361    /// different number of points.
1362    #[test]
1363    fn resolution_decides_the_intrinsic_size() {
1364        let bare = probe(&png_bytes(192, 96, None)).unwrap();
1365        assert_eq!(bare.size(), (144.0, 72.0));
1366        // 11811 pixels per metre is 300dpi.
1367        let dense = probe(&png_bytes(600, 300, Some(11811))).unwrap();
1368        assert!((dense.dpi_x - 300.0).abs() < 0.1, "{}", dense.dpi_x);
1369        assert!((dense.size().0 - 144.0).abs() < 0.1, "{:?}", dense.size());
1370        let inches = probe(&jpeg_bytes(600, 300, Some(300))).unwrap();
1371        assert_eq!(inches.dpi_x, 300.0);
1372        assert!((inches.size().0 - 144.0).abs() < 0.1);
1373    }
1374
1375    /// Bytes that are not an image, and truncated headers, are `None`
1376    /// rather than a panic.
1377    #[test]
1378    fn unknown_and_truncated_bytes_probe_to_nothing() {
1379        assert!(probe(b"").is_none());
1380        assert!(probe(b"not an image at all").is_none());
1381        let png = png_bytes(4, 4, None);
1382        for cut in 0..png.len() {
1383            let _ = probe(&png[..cut]);
1384        }
1385        let jpeg = jpeg_bytes(4, 4, Some(72));
1386        for cut in 0..jpeg.len() {
1387            let _ = probe(&jpeg[..cut]);
1388        }
1389    }
1390
1391    /// A host that pushes gets the same table a loader would have
1392    /// filled: the header sizes the image, the file is kept for the
1393    /// painter, and bytes no probe recognises are one complaint and no
1394    /// asset.
1395    #[test]
1396    fn pushed_images_are_probed_and_kept() {
1397        let mut assets = Assets::none();
1398        let png = png_bytes(96, 48, None);
1399        let a = assets.add("a.png", png.clone());
1400        assert!(matches!(
1401            a,
1402            Added::Replaced {
1403                index: 0,
1404                previous: None,
1405                ..
1406            }
1407        ));
1408        let b = assets.add("b.jpg", jpeg_bytes(200, 100, None));
1409        assert!(matches!(
1410            b,
1411            Added::Replaced {
1412                index: 1,
1413                previous: None,
1414                ..
1415            }
1416        ));
1417        // The same url and the same bytes twice is the same asset,
1418        // not a second copy, and costs nothing.
1419        assert_eq!(assets.add("a.png", png.clone()), Added::Unchanged(0));
1420        assert_eq!(assets.bytes(0), Some(png.as_slice()));
1421        assert_eq!(assets.lookup("a.png").map(|(index, _)| index), Some(0));
1422
1423        assert_eq!(
1424            assets.add("c.txt", b"not an image".to_vec()),
1425            Added::Refused
1426        );
1427        assert!(assets.probed("c.txt"), "a refusal counts as probed");
1428        assert!(!assets.probed("d.png"), "a url nobody offered does not");
1429        assert_eq!(assets.warnings().len(), 1);
1430        assert!(assets.warnings()[0].message.contains("c.txt"));
1431        // Offered twice, complained about once.
1432        assert_eq!(assets.add("c.txt", b"still not".to_vec()), Added::Refused);
1433        assert_eq!(assets.warnings().len(), 1);
1434    }
1435
1436    /// The same url registered again with different bytes replaces
1437    /// them in place, keeping the index `DrawItem::Image.asset`
1438    /// already names, and says what the size was before so a caller
1439    /// can tell whether the box an image takes moved.
1440    #[test]
1441    fn different_bytes_at_the_same_url_replace_it_in_place() {
1442        let mut assets = Assets::none();
1443        assets.add("a.png", png_bytes(96, 48, None));
1444
1445        let same_size = assets.add("a.png", png_bytes(96, 48, Some(150)));
1446        let Added::Replaced {
1447            index,
1448            previous,
1449            current,
1450        } = same_size
1451        else {
1452            panic!("different bytes at a registered url did not replace it: {same_size:?}");
1453        };
1454        assert_eq!(index, 0, "the index moved");
1455        assert_eq!(previous.map(|i| (i.width, i.height)), Some((96, 48)));
1456        assert_eq!((current.width, current.height), (96, 48));
1457        assert_eq!(
1458            assets.bytes(0),
1459            Some(png_bytes(96, 48, Some(150)).as_slice())
1460        );
1461
1462        let resized = assets.add("a.png", png_bytes(200, 100, None));
1463        let Added::Replaced {
1464            index,
1465            previous,
1466            current,
1467        } = resized
1468        else {
1469            panic!("a resize did not replace the asset: {resized:?}");
1470        };
1471        assert_eq!(index, 0);
1472        assert_eq!(previous.map(|i| (i.width, i.height)), Some((96, 48)));
1473        assert_eq!((current.width, current.height), (200, 100));
1474    }
1475
1476    /// The book's images are probed once each, in document order,
1477    /// through the host's loader; one the loader cannot resolve is a
1478    /// diagnostic and no asset.
1479    #[test]
1480    fn assets_index_the_book_in_document_order() {
1481        struct Two;
1482        impl ImageLoader for Two {
1483            fn load(&self, url: &str) -> Option<Vec<u8>> {
1484                match url {
1485                    "a.png" => Some(png_bytes(96, 48, None)),
1486                    "b.jpg" => Some(jpeg_bytes(200, 100, None)),
1487                    _ => None,
1488                }
1489            }
1490        }
1491
1492        let image = |url: &str| Block::Image {
1493            id: crate::content::NodeId::UNASSIGNED,
1494            url: url.into(),
1495            alt: String::new(),
1496            attributes: Attributes::default(),
1497            position: None,
1498            span: None,
1499        };
1500        let mut book = Book {
1501            metadata: Default::default(),
1502            sections: vec![crate::content::Section {
1503                attributes: Default::default(),
1504                blocks: vec![
1505                    image("a.png"),
1506                    Block::Blockquote {
1507                        id: crate::content::NodeId::UNASSIGNED,
1508                        blocks: vec![image("b.jpg")],
1509                        attributes: Attributes::default(),
1510                        position: None,
1511                        span: None,
1512                    },
1513                    image("a.png"),
1514                    image("missing.png"),
1515                ],
1516                ..Default::default()
1517            }],
1518        };
1519        book.assign_node_ids();
1520        let styles = crate::style::defaults(
1521            &book,
1522            crate::fonts::bundled_registry()
1523                .as_ref()
1524                .expect("the bundled face parses"),
1525        );
1526        let assets = Assets::probe(&book, &styles, &Two);
1527        assert_eq!(assets.assets().len(), 2, "a.png was probed twice");
1528        assert_eq!(assets.lookup("a.png").map(|(index, _)| index), Some(0));
1529        assert_eq!(assets.lookup("b.jpg").map(|(index, _)| index), Some(1));
1530        assert_eq!(assets.lookup("missing.png"), None);
1531        assert_eq!(assets.warnings().len(), 1);
1532        assert!(assets.warnings()[0].message.contains("missing.png"));
1533    }
1534
1535    /// A contour that traced to nothing warns while the sheet asks
1536    /// for it, once however often the stage runs, and stops when the
1537    /// sheet stops asking.
1538    #[test]
1539    fn a_missing_contour_warns_only_while_the_sheet_asks_for_it() {
1540        let mut book = Book {
1541            metadata: Default::default(),
1542            sections: vec![crate::content::Section {
1543                attributes: Default::default(),
1544                blocks: vec![Block::Image {
1545                    id: crate::content::NodeId::UNASSIGNED,
1546                    url: "seal.svg".into(),
1547                    alt: String::new(),
1548                    attributes: Attributes::default(),
1549                    position: None,
1550                    span: None,
1551                }],
1552                ..Default::default()
1553            }],
1554        };
1555        book.assign_node_ids();
1556        let mut assets = Assets::none();
1557        assets.add("seal.svg", br#"<svg width="64" height="64"/>"#.to_vec());
1558        let anchored = "img { position: absolute; top: 0; left: 0; wrap-flow: end }";
1559        let asking = styled(&book, &format!("{anchored} img {{ shape-outside: auto }}"));
1560        let plain = styled(&book, anchored);
1561
1562        let mut contours = Contours::none();
1563        assert_eq!(contours.update(&book, &asking, &assets), 1);
1564        assert_eq!(contours.warnings().len(), 1);
1565        assert_eq!(contours.update(&book, &asking, &assets), 0, "traced twice");
1566        assert_eq!(contours.warnings().len(), 1);
1567        contours.update(&book, &plain, &assets);
1568        assert!(contours.warnings().is_empty(), "{:?}", contours.warnings());
1569        contours.update(&book, &asking, &assets);
1570        assert_eq!(contours.warnings().len(), 1);
1571    }
1572
1573    /// A book of one paragraph, with no image in it.
1574    fn plain_book() -> Book {
1575        let mut book = Book {
1576            metadata: Default::default(),
1577            sections: vec![crate::content::Section {
1578                attributes: Default::default(),
1579                blocks: vec![Block::Paragraph {
1580                    id: crate::content::NodeId::UNASSIGNED,
1581                    inlines: vec![crate::content::Inline::Text {
1582                        id: crate::content::NodeId::UNASSIGNED,
1583                        value: "Nothing is placed here.".into(),
1584                        attributes: Attributes::default(),
1585                        position: None,
1586                        span: None,
1587                    }],
1588                    attributes: Attributes::default(),
1589                    position: None,
1590                    span: None,
1591                }],
1592                ..Default::default()
1593            }],
1594        };
1595        book.assign_node_ids();
1596        book
1597    }
1598
1599    /// One book under one sheet.
1600    fn styled(book: &Book, css: &str) -> StyleTree {
1601        let registry = crate::fonts::bundled_registry().expect("the bundled face parses");
1602        let styles = crate::style::Stylesheets::parse(&[crate::style::Source::author(
1603            "background.css",
1604            css,
1605        )])
1606        .compile(book, &registry);
1607        assert!(
1608            styles.warnings().is_empty(),
1609            "the sheet is in the subset: {:?}",
1610            styles.warnings(),
1611        );
1612        styles
1613    }
1614
1615    /// A loader that counts what it was asked for.
1616    struct Counting(std::cell::RefCell<Vec<String>>);
1617
1618    impl ImageLoader for Counting {
1619        fn load(&self, url: &str) -> Option<Vec<u8>> {
1620            self.0.borrow_mut().push(url.to_string());
1621            (url != "missing.png").then(|| png_bytes(96, 48, None))
1622        }
1623    }
1624
1625    /// A url the sheet names reaches the asset table, from a block
1626    /// rule and from `@page` alike, and the manuscript's own images
1627    /// are indexed first.
1628    #[test]
1629    fn a_url_the_sheet_names_reaches_the_asset_table() {
1630        let book = plain_book();
1631        let styles = styled(
1632            &book,
1633            "@page { background-image: url(\"scan.png\") }\n\
1634             p { background-image: url(tint.png) }",
1635        );
1636        let loader = Counting(std::cell::RefCell::new(Vec::new()));
1637        let assets = Assets::probe(&book, &styles, &loader);
1638
1639        let mut named: Vec<&str> = assets.assets().iter().map(|a| a.url.as_str()).collect();
1640        named.sort_unstable();
1641        assert_eq!(named, ["scan.png", "tint.png"]);
1642        assert!(assets.warnings().is_empty(), "{:?}", assets.warnings());
1643    }
1644
1645    /// A book whose sheet names no background image offers the loader
1646    /// nothing of its own: the cascade is read, and nothing is probed
1647    /// for it.
1648    #[test]
1649    fn a_sheet_that_names_no_background_probes_nothing() {
1650        let book = plain_book();
1651        let styles = styled(&book, "p { background-color: #f4f1ea }");
1652        let loader = Counting(std::cell::RefCell::new(Vec::new()));
1653        let assets = Assets::probe(&book, &styles, &loader);
1654
1655        assert!(
1656            loader.0.borrow().is_empty(),
1657            "the loader was asked for {:?}",
1658            loader.0.borrow(),
1659        );
1660        assert!(assets.assets().is_empty());
1661    }
1662
1663    /// A url nothing resolves warns, and the warning names the line
1664    /// and column the sheet wrote it at.
1665    #[test]
1666    fn a_url_nothing_resolves_names_where_it_was_written() {
1667        let book = plain_book();
1668        let styles = styled(&book, "p {\n  background-image: url(missing.png);\n}");
1669        let loader = Counting(std::cell::RefCell::new(Vec::new()));
1670        let assets = Assets::probe(&book, &styles, &loader);
1671
1672        assert!(assets.assets().is_empty());
1673        assert_eq!(assets.warnings().len(), 1);
1674        assert!(assets.warnings()[0].message.contains("missing.png"));
1675        assert_eq!(
1676            assets.warnings()[0].origin.as_deref(),
1677            Some("background.css:2:3"),
1678        );
1679    }
1680
1681    /// An asset probed through a loader hashes the same as one pushed
1682    /// through `add`: registering it again, with the bytes it already
1683    /// has or with different ones, does not panic and answers the
1684    /// same way either door would have.
1685    #[test]
1686    fn probed_and_pushed_assets_share_one_hash_table() {
1687        struct One;
1688        impl ImageLoader for One {
1689            fn load(&self, url: &str) -> Option<Vec<u8>> {
1690                (url == "a.png").then(|| png_bytes(96, 48, None))
1691            }
1692        }
1693
1694        let image = |url: &str| Block::Image {
1695            id: crate::content::NodeId::UNASSIGNED,
1696            url: url.into(),
1697            alt: String::new(),
1698            attributes: Attributes::default(),
1699            position: None,
1700            span: None,
1701        };
1702        let mut book = Book {
1703            metadata: Default::default(),
1704            sections: vec![crate::content::Section {
1705                attributes: Default::default(),
1706                blocks: vec![image("a.png")],
1707                ..Default::default()
1708            }],
1709        };
1710        book.assign_node_ids();
1711        let styles = crate::style::defaults(
1712            &book,
1713            crate::fonts::bundled_registry()
1714                .as_ref()
1715                .expect("the bundled face parses"),
1716        );
1717        let mut assets = Assets::probe(&book, &styles, &One);
1718
1719        assert_eq!(
1720            assets.add("a.png", png_bytes(96, 48, None)),
1721            Added::Unchanged(0),
1722            "the same bytes probed and pushed hash the same"
1723        );
1724        let resized = assets.add("a.png", png_bytes(200, 100, None));
1725        assert!(
1726            matches!(resized, Added::Replaced { index: 0, .. }),
1727            "different bytes replaced the probed asset in place: {resized:?}"
1728        );
1729    }
1730}