Skip to main content

pdfboss_render/
lib.rs

1//! Page rasterization for pdfboss: paths, fills, strokes, clipping, color
2//! spaces, images and glyph outlines, rendered to an RGBA8 pixmap and
3//! encodable as PNG.
4//!
5//! Glyph painting is staged behind [`GlyphPainting`] tiers: embedded
6//! TrueType only, then every embedded font program (TrueType, CFF, Type1,
7//! Type3), and finally `Full`, which additionally substitutes a
8//! replacement face for a non-embedded simple font (see `crate::glyph` and
9//! `crate::substitute` for the loader and the request/provider plumbing).
10//! A substitute face comes from either a caller-supplied directory
11//! ([`SubstituteSource::Dir`]) or the compiled-in OFL Croscore set
12//! ([`SubstituteSource::Builtin`]), the latter gated behind this crate's
13//! `substitute-fonts` Cargo feature and queryable at runtime via
14//! [`builtin_fonts_available`]. Advance widths for a substituted
15//! standard-14 font additionally consult Adobe Core-14 AFM tables
16//! (`pdfboss_encoding::standard_14_width`) ahead of the substitute's own
17//! `hmtx`, behind only the PDF's own `/Widths`.
18//!
19//! v1 limitations: `/Symbol` and `/ZapfDingbats` have no license-clean
20//! substitute, so they stay unpainted at every tier rather than borrowing
21//! an unrelated face's glyphs (their text still advances, via the
22//! metrics-only loader in `crate::glyph`); and a "bold" *sans* substitute
23//! request is not visually distinct from regular weight (Arimo is a
24//! `[wght]` variable font, rendered at its Regular instance -- only italic
25//! varies, via a separate static face).
26
27// The rasterizer modules are consumed by the content-stream executor; the
28// `dead_code` allowances below disappear once it is wired up.
29mod cff;
30#[allow(dead_code)]
31mod color;
32mod encode;
33mod executor;
34mod extract;
35mod glyph;
36mod image;
37#[allow(dead_code)]
38mod path;
39#[allow(dead_code)]
40mod raster;
41mod shading;
42#[allow(dead_code)]
43mod stroke;
44#[allow(dead_code)]
45mod substitute;
46mod truetype;
47mod type1;
48mod type3;
49
50use std::path::{Path, PathBuf};
51use std::sync::Arc;
52
53use pdfboss_core::{AsyncObjectSource, Document, Error, OcState, Page, Result};
54
55pub use extract::{extract_page_images, extract_page_images_with};
56
57/// An RGBA8 raster image with straight (non-premultiplied) alpha, row-major
58/// from the top-left.
59#[derive(Debug, Clone, PartialEq)]
60pub struct Pixmap {
61    pub width: u32,
62    pub height: u32,
63    /// Pixel data, `width * height * 4` bytes (RGBA per pixel).
64    pub data: Vec<u8>,
65}
66
67/// How much CPU the PNG encoder spends shrinking the file. Every level
68/// round-trips the exact same pixels; only encode time and file size move.
69/// `Balanced` is what [`Pixmap::encode_png`] has always used.
70#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
71pub enum PngCompression {
72    /// Uncompressed: fastest, largest files.
73    None,
74    /// Very fast with a decent ratio.
75    Fast,
76    /// Balances encode speed and file size.
77    #[default]
78    Balanced,
79    /// Smallest files, much slower.
80    Best,
81}
82
83impl PngCompression {
84    fn to_encoding(self) -> png::Compression {
85        match self {
86            PngCompression::None => png::Compression::NoCompression,
87            PngCompression::Fast => png::Compression::Fast,
88            PngCompression::Balanced => png::Compression::Balanced,
89            PngCompression::Best => png::Compression::High,
90        }
91    }
92}
93
94impl Pixmap {
95    /// Creates a fully transparent pixmap.
96    pub fn new(w: u32, h: u32) -> Pixmap {
97        Pixmap {
98            width: w,
99            height: h,
100            data: vec![0; w as usize * h as usize * 4],
101        }
102    }
103
104    /// Fills every pixel with `rgba`.
105    pub fn fill(&mut self, rgba: [u8; 4]) {
106        for px in self.data.as_chunks_mut::<4>().0 {
107            *px = rgba;
108        }
109    }
110
111    /// Encodes the pixmap as a PNG image, at the default compression level.
112    pub fn encode_png(&self) -> Result<Vec<u8>> {
113        self.encode_png_with(PngCompression::default())
114    }
115
116    /// Encodes the pixmap as a PNG image at the given compression level.
117    pub fn encode_png_with(&self, compression: PngCompression) -> Result<Vec<u8>> {
118        fn err(e: png::EncodingError) -> Error {
119            Error::Other(format!("png encode: {e}"))
120        }
121        if compression == PngCompression::Balanced {
122            return Ok(encode::encode_rgba(self.width, self.height, &self.data));
123        }
124        let mut out = Vec::new();
125        let mut enc = png::Encoder::new(&mut out, self.width, self.height);
126        enc.set_color(png::ColorType::Rgba);
127        enc.set_depth(png::BitDepth::Eight);
128        enc.set_compression(compression.to_encoding());
129        let mut writer = enc.write_header().map_err(err)?;
130        writer.write_image_data(&self.data).map_err(err)?;
131        writer.finish().map_err(err)?;
132        Ok(out)
133    }
134
135    /// Encodes the pixmap as PNG and writes it to `path`.
136    pub fn save_png(&self, path: impl AsRef<Path>) -> Result<()> {
137        std::fs::write(path, self.encode_png()?)?;
138        Ok(())
139    }
140}
141
142/// How aggressively the rasterizer turns text into filled outlines. Each tier is
143/// a strict superset of the previous one; the difference is only observable once
144/// the corresponding glyph loaders exist.
145#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
146pub enum GlyphPainting {
147    /// Only embedded TrueType (`glyf`) outlines — the cheapest tier.
148    EmbeddedTrueTypeOnly,
149    /// Every embedded program: TrueType, CFF, Type1 and Type3. No bundled assets.
150    #[default]
151    AllEmbedded,
152    /// Also substitute bundled or caller-provided faces for non-embedded
153    /// fonts, and per glyph for codes an embedded simple font's program
154    /// lacks.
155    Full,
156}
157
158impl GlyphPainting {
159    /// Whether this tier paints every embedded program (CFF, Type1, Type3),
160    /// not just embedded TrueType.
161    pub fn paints_all_embedded(self) -> bool {
162        !matches!(self, GlyphPainting::EmbeddedTrueTypeOnly)
163    }
164}
165
166/// Where non-embedded glyph substitution (the `Full` [`GlyphPainting`] tier)
167/// draws replacement faces from. The default, `None`, substitutes nothing --
168/// `Full` behaves exactly like `AllEmbedded` until a caller opts in.
169#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
170pub enum SubstituteSource {
171    /// No substitution: non-embedded fonts stay unpainted.
172    #[default]
173    None,
174    /// Compiled-in faces: the OFL Croscore set (Arimo/Tinos/Cousine,
175    /// metric-compatible with Helvetica/Times/Courier) bundled via
176    /// `include_bytes!` behind the `substitute-fonts` Cargo feature -- see
177    /// [`builtin_fonts_available`] and `crate::substitute::BuiltinProvider`.
178    /// Built without that feature, there are no compiled-in faces to hand
179    /// out: `Builtin` degrades to no provider at all, so `Full` behaves
180    /// exactly like `AllEmbedded` for non-embedded fonts, the same as
181    /// `SubstituteSource::None`.
182    Builtin,
183    /// Faces read from a directory at render time (e.g. an installed
184    /// `pdfboss-fonts` package), one file per style -- see
185    /// `substitute::face_filename`.
186    Dir(PathBuf),
187}
188
189/// Options controlling a single page render.
190#[derive(Clone, Debug, Default)]
191pub struct RenderOptions {
192    /// Which font programs the rasterizer will paint.
193    pub glyph_painting: GlyphPainting,
194    /// Where `Full`-tier substitution draws replacement faces from. Ignored
195    /// at every other tier.
196    pub substitutes: SubstituteSource,
197    /// The document's optional-content visibility (ISO 32000-1 §8.11):
198    /// content in groups the default configuration turns off is not
199    /// painted, counted in [`RenderReport::hidden`]. The synchronous entry
200    /// points fill this from the document when it is `None`; an
201    /// asynchronous caller builds it itself (e.g.
202    /// `AsyncDocument::oc_state`), and leaving it `None` there renders
203    /// every layer.
204    pub oc: Option<Arc<OcState>>,
205    /// Fonts loaded once for the document instead of once per page: a
206    /// caller rendering a whole document passes one [`RenderCache`] to
207    /// every page, and each font program — outline parsing included —
208    /// loads once. `None` keeps every load page-local. Keyed by the font
209    /// dictionary's object reference, so identical resource names on
210    /// different pages never collide, exactly like text extraction's
211    /// `FontCache`.
212    pub cache: Option<Arc<RenderCache>>,
213}
214
215/// Cross-page render state: fonts by their dictionary's object reference,
216/// and parsed `ICCBased` colorspace outcomes by their profile stream's.
217/// `Send + Sync`, so a parallel page walk may share one.
218#[derive(Default)]
219pub struct RenderCache {
220    fonts: std::sync::Mutex<pdfboss_core::FastMap<FontKey, executor::SharedGlyphFont>>,
221    /// Shared as one handle with every page's executor, which otherwise
222    /// builds a render-local one — the same two-level shape as `fonts`
223    /// without a second lookup tier.
224    colorspaces: Arc<color::IccCache>,
225}
226
227/// What a cached font load depended on besides the dictionary itself: the
228/// painting tier and the substitute source. One cache handle may serve
229/// renders with different options — a load made at `all-embedded` paints
230/// nothing for a non-embedded font and must not be handed to a `full`
231/// render, so the options are part of the key rather than an invariant the
232/// caller polices.
233#[derive(PartialEq, Eq, Hash, Clone)]
234pub(crate) struct FontKey {
235    pub(crate) font: pdfboss_core::ObjRef,
236    pub(crate) painting: GlyphPainting,
237    pub(crate) substitutes: SubstituteSource,
238}
239
240impl std::fmt::Debug for RenderCache {
241    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242        let fonts = self.fonts.lock().map(|m| m.len()).unwrap_or(0);
243        f.debug_struct("RenderCache")
244            .field("fonts", &fonts)
245            .finish()
246    }
247}
248
249impl RenderCache {
250    pub(crate) fn font(&self, key: &FontKey) -> Option<executor::SharedGlyphFont> {
251        self.fonts.lock().ok()?.get(key).cloned()
252    }
253
254    /// First writer wins, exactly like the text-side cache: concurrent
255    /// workers may load the same font twice and the copies are
256    /// interchangeable.
257    pub(crate) fn store(&self, key: FontKey, font: executor::SharedGlyphFont) {
258        if let Ok(mut fonts) = self.fonts.lock() {
259            fonts.entry(key).or_insert(font);
260        }
261    }
262}
263
264/// Whether this binary was built with the `substitute-fonts` feature, i.e.
265/// whether `SubstituteSource::Builtin` has compiled-in faces to hand out.
266/// Callers (e.g. the CLI) use this to give an actionable message when `Full`
267/// is requested with no `--font-dir` and no compiled-in set, rather than
268/// silently rendering as if `Full` had never been asked for.
269pub fn builtin_fonts_available() -> bool {
270    cfg!(feature = "substitute-fonts")
271}
272
273/// Renders a page at `scale` onto a white background. The pixel size is
274/// `ceil(crop_w * scale) x ceil(crop_h * scale)` (after `/Rotate`), and the
275/// base transform maps the crop box to device space with a y-flip and the
276/// page rotation applied.
277///
278/// Rendering is lenient: content pdfboss cannot read is skipped rather than
279/// failing the render, so a page can come back blank without an error. Use
280/// [`render_page_reporting`] to find out what was dropped.
281pub fn render_page(doc: &Document, page: &Page, scale: f32) -> Result<Pixmap> {
282    render_page_with_options(doc, page, scale, &RenderOptions::default())
283}
284
285/// Renders a page like [`render_page`], honoring `opts` (currently the glyph
286/// painting tier). See [`render_page`] for the geometry contract and for
287/// what leniency means for the pixels you get back.
288pub fn render_page_with_options(
289    doc: &Document,
290    page: &Page,
291    scale: f32,
292    opts: &RenderOptions,
293) -> Result<Pixmap> {
294    executor::render_page_reporting(doc, page, scale, opts).map(|(pix, _)| pix)
295}
296
297/// Renders a page like [`render_page_with_options`], additionally returning
298/// a [`RenderReport`] describing any content that had to be dropped or
299/// approximated. Use this when a silently blank page would be misleading.
300pub fn render_page_reporting(
301    doc: &Document,
302    page: &Page,
303    scale: f32,
304    opts: &RenderOptions,
305) -> Result<(Pixmap, RenderReport)> {
306    executor::render_page_reporting(doc, page, scale, opts)
307}
308
309/// Renders a page like [`render_page_reporting`] against any object source,
310/// awaiting whatever I/O the source needs — this is the asynchronous entry
311/// point, and the synchronous ones above are this implementation over
312/// `pdfboss_core::Immediate` (with [`RenderOptions::oc`] filled from the
313/// document when the caller left it unset), so under the same options the
314/// two APIs cannot render differently.
315///
316/// The source is taken by value and the page by reference, which is the
317/// combination a consumer needs to spawn the result: the future is `Send`
318/// over a source that is `Send + Sync`, and `'static` as long as the borrow
319/// of `page` is created inside the consumer's own `async move` block, which
320/// owns the page. See `pdfboss_core::source`'s "Signing a shared algorithm".
321pub async fn render_page_reporting_with<S: AsyncObjectSource>(
322    src: S,
323    page: &Page,
324    scale: f32,
325    opts: &RenderOptions,
326) -> Result<(Pixmap, RenderReport)> {
327    executor::render_page_reporting_with(src, page, scale, opts).await
328}
329
330/// Upper bound on the distinct entries a [`RenderReport`] keeps. Repeats of
331/// the same kind and reason only raise an existing entry's count, so this
332/// bounds the report's memory for any page: a stream drawing the same
333/// undecodable image a million times costs one entry, and a stream inventing
334/// endlessly *different* failures stops growing the list here and counts the
335/// rest in [`RenderReport::unlisted`].
336const MAX_SKIPPED: usize = 64;
337
338/// Which piece of page content a render could not reproduce.
339#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
340#[non_exhaustive]
341pub enum SkippedKind {
342    /// The page's own content stream: nothing on the page was drawn.
343    PageContents,
344    /// An image XObject or an inline image.
345    Image,
346    /// A form XObject, and with it everything nested inside it.
347    Form,
348    /// A `Do` whose XObject resource is missing, is not a stream, or has no
349    /// subtype this renderer knows how to draw.
350    XObject,
351    /// A shading (`sh` or a shading pattern) this renderer could not
352    /// load: a missing resource or a structural failure. All seven
353    /// shading types paint.
354    Shading,
355    /// A pattern fill or stroke, painted as flat mid-gray instead of the
356    /// pattern's own content.
357    Pattern,
358    /// A mask that was ignored, so content the author masked out painted
359    /// solid: an image `/SMask` or `/Mask`, or an `/ExtGState` `/SMask`.
360    SoftMask,
361    /// A `/BM` blend mode painted as `Normal`. No longer produced — every
362    /// ISO 32000 blend mode paints — but retained so report consumers
363    /// keep compiling against the same set of kinds.
364    BlendMode,
365    /// An annotation appearance stream that was declared but could not be
366    /// painted: unreadable, unparsable, or with no selectable state.
367    /// Annotations that declare no appearance, and ones flagged Hidden or
368    /// NoView, paint nothing by design and are not reported.
369    Annotation,
370    /// A character code a *painting* font has no glyph for: the code
371    /// advanced the text position but painted nothing. A single-byte code
372    /// 0x20 is exempt — a space paints nothing whether or not the font maps
373    /// it — while a two-byte 0x20 is a real CID and is reported. Text whose
374    /// font paints at no tier (the [`GlyphPainting`] tier, or a load
375    /// failure) is configured behavior and stays unreported; such a font
376    /// still loads its metrics so the text advances.
377    Glyph,
378    /// Text shown in a clipping rendering mode (`Tr` 4-7, ISO 32000-1
379    /// §9.3.6). The painting half of the mode is honored, but the glyph
380    /// outlines never join the clipping path, so content the author
381    /// clipped to the text paints unclipped.
382    TextClip,
383}
384
385impl SkippedKind {
386    /// The noun this kind reads as in [`RenderReport::summary`] and
387    /// [`RenderReport::warnings`], pluralized for `n`.
388    fn noun(self, n: u64) -> &'static str {
389        let one = n == 1;
390        match self {
391            SkippedKind::PageContents if one => "content stream",
392            SkippedKind::PageContents => "content streams",
393            SkippedKind::Image if one => "image",
394            SkippedKind::Image => "images",
395            SkippedKind::Form if one => "form XObject",
396            SkippedKind::Form => "form XObjects",
397            SkippedKind::XObject if one => "XObject",
398            SkippedKind::XObject => "XObjects",
399            SkippedKind::Shading if one => "shading",
400            SkippedKind::Shading => "shadings",
401            SkippedKind::Pattern if one => "pattern",
402            SkippedKind::Pattern => "patterns",
403            SkippedKind::SoftMask if one => "mask",
404            SkippedKind::SoftMask => "masks",
405            SkippedKind::BlendMode if one => "blend mode",
406            SkippedKind::BlendMode => "blend modes",
407            SkippedKind::Annotation if one => "annotation",
408            SkippedKind::Annotation => "annotations",
409            SkippedKind::Glyph if one => "glyph",
410            SkippedKind::Glyph => "glyphs",
411            SkippedKind::TextClip if one => "text clip",
412            SkippedKind::TextClip => "text clips",
413        }
414    }
415}
416
417/// Why a piece of page content was dropped or approximated during
418/// rasterization.
419///
420/// Rendering is lenient: content pdfboss cannot read is skipped so the rest
421/// of the page still rasterizes. This enum records *why*, so callers can
422/// tell an intentionally blank page from a page whose content pdfboss could
423/// not read.
424#[derive(Clone, Debug, PartialEq, Eq)]
425#[non_exhaustive]
426pub enum SkipReason {
427    /// The stream's `/Filter` chain names a filter pdfboss does not decode.
428    UnsupportedFilter(String),
429    /// Reading the stream failed, carrying the underlying message: a filter
430    /// that ran but gave up (corrupt data, size limit, ...), or a syntax
431    /// error in a content stream.
432    DecodeFailed(String),
433    /// Filters applied cleanly but the bytes could not be interpreted (bad
434    /// image dimensions, unparsable content stream, unsupported JPEG, ...).
435    Undecodable,
436    /// The stream held fewer samples than the image's dimensions and bit
437    /// depth demand; the missing region painted as zero samples.
438    Truncated,
439    /// A resource the operator names is absent, or is not the kind of object
440    /// the operator needs.
441    Missing,
442    /// pdfboss understands the construct but does not paint it yet, so it
443    /// was omitted or approximated.
444    Unsupported,
445    /// A nesting or size guard stopped the render at this point.
446    LimitExceeded,
447    /// A loaded font has no glyph for a character code the page draws, so
448    /// the code advanced the text position without painting. One value per
449    /// distinct `(font, code)` pair, so the report counts occurrences
450    /// instead of listing them.
451    NoGlyph {
452        /// The character code exactly as the show operator carried it.
453        code: u32,
454        /// The font's `/BaseFont` name, or its `Tf` resource name when the
455        /// dictionary has none.
456        font: String,
457    },
458}
459
460impl std::fmt::Display for SkipReason {
461    /// The reason as the clause after the colon of a warning line, e.g.
462    /// `unsupported filter /Crypt`.
463    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
464        match self {
465            SkipReason::UnsupportedFilter(name) => write!(f, "unsupported filter /{name}"),
466            SkipReason::DecodeFailed(msg) => f.write_str(msg),
467            SkipReason::Undecodable => f.write_str("the data could not be interpreted"),
468            SkipReason::Truncated => f.write_str("sample data ended early; the rest painted blank"),
469            SkipReason::Missing => f.write_str("the resource is missing"),
470            SkipReason::Unsupported => f.write_str("not supported yet"),
471            SkipReason::LimitExceeded => f.write_str("a nesting limit stopped the render here"),
472            SkipReason::NoGlyph { code, font } => {
473                write!(f, "no glyph for code {code} in /{font}")
474            }
475        }
476    }
477}
478
479/// One kind of content dropped for one reason, with how often it happened.
480#[derive(Clone, Debug, PartialEq, Eq)]
481#[non_exhaustive]
482pub struct SkippedContent {
483    /// What was dropped.
484    pub kind: SkippedKind,
485    /// Why it was dropped.
486    pub reason: SkipReason,
487    /// How many times this exact kind/reason pair came up in the render.
488    pub count: u64,
489}
490
491/// What a page render could not reproduce faithfully: content dropped
492/// outright (an undecodable image, an unreadable form) and content painted
493/// as an approximation (a pattern fill as flat gray). Empty means every
494/// construct the render encountered was painted as the page describes it.
495///
496/// Two things are deliberately *not* reported, because they are configured
497/// behavior rather than a failure: text left unpainted by the requested
498/// [`GlyphPainting`] tier — its font loads metrics only, so the text still
499/// advances but draws nothing — and content clipped or transformed off the
500/// page. A code a *painting* font has no glyph for is a real loss and IS
501/// reported, as [`SkippedKind::Glyph`].
502#[derive(Clone, Debug, Default, PartialEq, Eq)]
503#[non_exhaustive]
504pub struct RenderReport {
505    /// Distinct drops in the order first encountered, at most 64 entries
506    /// (see `count` for repeats and [`RenderReport::unlisted`] for the
507    /// overflow).
508    pub skipped: Vec<SkippedContent>,
509    /// Drops that arrived after `skipped` reached its 64-entry cap and so
510    /// are counted but not described.
511    pub unlisted: u64,
512    /// Content the document's optional-content configuration turns off
513    /// (ISO 32000-1 §8.11): one count per `BDC /OC` span whose own
514    /// membership evaluated hidden, per XObject with a hidden `/OC` entry,
515    /// and per annotation with a hidden `/OC` entry. Configured behavior,
516    /// not a loss, so it plays no part in [`RenderReport::is_empty`],
517    /// [`RenderReport::summary`], or [`RenderReport::warnings`].
518    pub hidden: u64,
519}
520
521impl RenderReport {
522    /// Whether the page rasterized with nothing dropped or approximated.
523    pub fn is_empty(&self) -> bool {
524        self.skipped.is_empty() && self.unlisted == 0
525    }
526
527    /// A one-line human summary counting drops per kind, or `None` when
528    /// nothing was dropped: `"2 images, 1 shading skipped"`.
529    pub fn summary(&self) -> Option<String> {
530        if self.is_empty() {
531            return None;
532        }
533        let mut totals: Vec<(SkippedKind, u64)> = Vec::new();
534        for item in &self.skipped {
535            match totals.iter_mut().find(|(kind, _)| *kind == item.kind) {
536                Some((_, n)) => *n = n.saturating_add(item.count),
537                None => totals.push((item.kind, item.count)),
538            }
539        }
540        let mut parts: Vec<String> = totals
541            .iter()
542            .map(|(kind, n)| format!("{n} {}", kind.noun(*n)))
543            .collect();
544        if self.unlisted > 0 {
545            parts.push(format!("{} more", self.unlisted));
546        }
547        Some(format!("{} skipped", parts.join(", ")))
548    }
549
550    /// One human-readable line per distinct drop, for callers that warn
551    /// about them: `"1 image skipped: unsupported filter /Crypt"`.
552    pub fn warnings(&self) -> Vec<String> {
553        let mut out: Vec<String> = self
554            .skipped
555            .iter()
556            .map(|item| {
557                format!(
558                    "{} {} skipped: {}",
559                    item.count,
560                    item.kind.noun(item.count),
561                    item.reason
562                )
563            })
564            .collect();
565        if self.unlisted > 0 {
566            out.push(format!(
567                "{} further drops not described (report limit reached)",
568                self.unlisted
569            ));
570        }
571        out
572    }
573
574    /// Records one drop, merging it into an existing entry when the same
575    /// kind and reason already happened. Beyond [`MAX_SKIPPED`] distinct
576    /// entries the drop is only counted, so a page drawing endlessly varied
577    /// broken content cannot grow this report without bound.
578    pub(crate) fn record(&mut self, kind: SkippedKind, reason: SkipReason) {
579        if let Some(item) = self
580            .skipped
581            .iter_mut()
582            .find(|item| item.kind == kind && item.reason == reason)
583        {
584            item.count = item.count.saturating_add(1);
585            return;
586        }
587        if self.skipped.len() >= MAX_SKIPPED {
588            self.unlisted = self.unlisted.saturating_add(1);
589            return;
590        }
591        self.skipped.push(SkippedContent {
592            kind,
593            reason,
594            count: 1,
595        });
596    }
597}
598
599#[cfg(test)]
600mod tests {
601    use super::*;
602
603    #[test]
604    fn new_pixmap_is_transparent() {
605        let pix = Pixmap::new(3, 2);
606        assert_eq!(pix.width, 3);
607        assert_eq!(pix.height, 2);
608        assert_eq!(pix.data.len(), 24);
609        assert!(pix.data.iter().all(|&b| b == 0));
610    }
611
612    #[test]
613    fn fill_sets_every_pixel() {
614        let mut pix = Pixmap::new(2, 2);
615        pix.fill([1, 2, 3, 4]);
616        assert_eq!(pix.data, [1, 2, 3, 4].repeat(4));
617    }
618
619    #[test]
620    fn compression_levels_map_to_their_encoder_settings() {
621        // png::Compression derives no PartialEq, hence matches!.
622        assert!(matches!(
623            PngCompression::None.to_encoding(),
624            png::Compression::NoCompression
625        ));
626        assert!(matches!(
627            PngCompression::Fast.to_encoding(),
628            png::Compression::Fast
629        ));
630        assert!(matches!(
631            PngCompression::Balanced.to_encoding(),
632            png::Compression::Balanced
633        ));
634        assert!(matches!(
635            PngCompression::Best.to_encoding(),
636            png::Compression::High
637        ));
638    }
639
640    #[test]
641    fn balanced_is_the_default_compression() {
642        assert_eq!(PngCompression::default(), PngCompression::Balanced);
643    }
644
645    #[test]
646    fn png_round_trip_preserves_pixels() {
647        let mut pix = Pixmap::new(3, 2);
648        for (i, b) in pix.data.iter_mut().enumerate() {
649            *b = (i * 11 % 256) as u8;
650        }
651        let bytes = pix.encode_png().expect("encode");
652        assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
653
654        let decoder = png::Decoder::new(std::io::Cursor::new(&bytes));
655        let mut reader = decoder.read_info().expect("read_info");
656        let mut buf = vec![0u8; reader.output_buffer_size().expect("size")];
657        let info = reader.next_frame(&mut buf).expect("frame");
658        assert_eq!(info.width, 3);
659        assert_eq!(info.height, 2);
660        assert_eq!(info.color_type, png::ColorType::Rgba);
661        assert_eq!(info.bit_depth, png::BitDepth::Eight);
662        assert_eq!(&buf[..info.buffer_size()], &pix.data[..]);
663    }
664
665    #[test]
666    fn report_merges_repeats_and_counts_per_kind() {
667        let mut report = RenderReport::default();
668        assert!(report.is_empty());
669        report.record(SkippedKind::Image, SkipReason::Undecodable);
670        report.record(SkippedKind::Image, SkipReason::Undecodable);
671        report.record(
672            SkippedKind::Image,
673            SkipReason::UnsupportedFilter("Crypt".to_string()),
674        );
675        report.record(SkippedKind::Shading, SkipReason::Unsupported);
676
677        assert!(!report.is_empty());
678        assert_eq!(report.skipped.len(), 3, "same kind and reason merge");
679        assert_eq!(report.skipped[0].count, 2);
680        // The summary counts per kind, so the two image reasons add up.
681        assert_eq!(
682            report.summary().as_deref(),
683            Some("3 images, 1 shading skipped"),
684        );
685        assert_eq!(
686            report.warnings(),
687            vec![
688                "2 images skipped: the data could not be interpreted".to_string(),
689                "1 image skipped: unsupported filter /Crypt".to_string(),
690                "1 shading skipped: not supported yet".to_string(),
691            ],
692        );
693    }
694
695    #[test]
696    fn report_stops_listing_at_the_cap_but_keeps_counting() {
697        let mut report = RenderReport::default();
698        for i in 0..MAX_SKIPPED + 5 {
699            report.record(SkippedKind::Image, SkipReason::DecodeFailed(i.to_string()));
700        }
701        assert_eq!(report.skipped.len(), MAX_SKIPPED);
702        assert_eq!(report.unlisted, 5);
703        assert_eq!(
704            report.summary().as_deref(),
705            Some("64 images, 5 more skipped"),
706        );
707    }
708
709    #[test]
710    fn save_png_writes_decodable_file() {
711        let mut pix = Pixmap::new(4, 4);
712        pix.fill([10, 20, 30, 255]);
713        let dir = std::env::temp_dir().join("pdfboss-render-test");
714        std::fs::create_dir_all(&dir).unwrap();
715        let path = dir.join("pix.png");
716        pix.save_png(&path).expect("save");
717        let bytes = std::fs::read(&path).unwrap();
718        assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
719        std::fs::remove_file(&path).ok();
720    }
721}