Skip to main content

pdf2_render/
walk.rs

1//! The content-stream walker: graphics state, path construction, painting
2//! operators, clipping and dash handling.
3//!
4//! The walker reuses [`pdf2::Parser`] (the same tokenizer the object parser
5//! uses) and maps operators to draw calls. Operators it does not implement —
6//! text and images, until the next round — are counted and reported, never
7//! fatal: a page with text still paints its paths.
8
9use std::collections::BTreeMap;
10use std::fmt;
11
12use pdf2::lexer::{is_delimiter, is_whitespace};
13use pdf2::{Dictionary, Document, Encoding, Object, Page, Parser, Token};
14
15use crate::canvas::{BlendMode, Canvas, ClipMask, Color};
16use crate::font::{Font, Glyph};
17use crate::geom::{Matrix, Point};
18use crate::image::{Image, resolve};
19use crate::path::{Cap, Dash, Join, Path, dash_polyline, stroke_outline};
20use crate::raster::{clip_mask, fill_polygons};
21
22/// How deep form XObjects may nest before a further `/Do` is reported instead of
23/// followed.
24///
25/// PDF lets a form draw another form (8.10), and nothing in the format forbids a
26/// cycle. Eight levels is far past what real files use — a form inside a form
27/// inside a form is already unusual — and mirrors [`pdf2::Document`]'s
28/// `MAX_RESOLVE_DEPTH`: a named constant, a report, and a test that proves it
29/// fires rather than a stack overflow.
30const MAX_FORM_DEPTH: usize = 8;
31
32/// How many pattern cells one fill may paint.
33///
34/// The clause sets no bound on the lattice ("Painting with the pattern replicates
35/// the cell at fixed horizontal and vertical intervals"), so `/XStep 0.01` over a
36/// page is millions of cells; the budget is the renderer's own, in
37/// [`MAX_FORM_DEPTH`]'s shape: a named constant, a reported operator, a test.
38const MAX_TILE_CELLS: usize = 4096;
39
40/// What a page render should look like.
41#[derive(Debug, Clone, PartialEq)]
42pub struct RenderOptions {
43    /// Device pixels per PDF point: `1.0` is 72 dpi.
44    pub scale: f64,
45    /// Canvas background.
46    pub background: Color,
47}
48
49impl Default for RenderOptions {
50    fn default() -> Self {
51        Self {
52            scale: 1.0,
53            background: Color::WHITE,
54        }
55    }
56}
57
58/// What happened while rendering, beyond the pixels.
59#[derive(Debug, Clone, Default, PartialEq)]
60pub struct Report {
61    /// Operators that were recognised but not drawn, and the conditions that
62    /// stopped a page drawing, with how often each appeared.
63    pub unsupported: BTreeMap<String, usize>,
64    /// Painting operators the walker executed: fills, strokes, text runs, images
65    /// and shadings. Zero means the page had nothing to draw.
66    pub painted: usize,
67}
68
69impl Report {
70    /// Total unsupported operators.
71    pub fn unsupported_total(&self) -> usize {
72        self.unsupported.values().sum()
73    }
74
75    fn note(&mut self, operator: &[u8]) {
76        let name = String::from_utf8_lossy(operator).into_owned();
77        *self.unsupported.entry(name).or_insert(0) += 1;
78    }
79}
80
81impl fmt::Display for Report {
82    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
83        if self.unsupported.is_empty() {
84            return write!(formatter, "all operators supported");
85        }
86        let mut first = true;
87        for (name, count) in &self.unsupported {
88            if !first {
89                write!(formatter, ", ")?;
90            }
91            first = false;
92            write!(formatter, "{name}×{count}")?;
93        }
94        Ok(())
95    }
96}
97
98/// A rendered page.
99#[derive(Debug, Clone)]
100pub struct RenderedPage {
101    /// The raster.
102    pub canvas: Canvas,
103    /// What was skipped.
104    pub report: Report,
105}
106
107/// One glyph the renderer painted, in page space: points, `y` growing upwards,
108/// the origin at the page's visible box -- the same convention
109/// [`pdf2::TextSpan`] uses, so a text layer can mix the two.
110///
111/// `advance` is how far the pen moved for this glyph, and `size` is the font
112/// size the renderer used for it: together they are what an invisible text
113/// layer needs to sit exactly on the paint, whatever font the browser
114/// substitutes.
115#[derive(Debug, Clone, PartialEq)]
116pub struct GlyphBox {
117    /// The character this code stands for, empty when the encoding has none.
118    pub text: String,
119    /// Baseline origin, x.
120    pub x: f64,
121    /// Baseline origin, y.
122    pub y: f64,
123    /// Pen advance for this glyph, in page units.
124    pub advance: f64,
125    /// Effective font size, in page units.
126    pub size: f64,
127}
128
129/// A rendered page together with the glyphs it painted, in painting order.
130#[derive(Debug, Clone)]
131pub struct TracedPage {
132    /// The raster and its report, exactly as [`render_page`] returns them.
133    pub page: RenderedPage,
134    /// Every glyph the walker painted, in page space.
135    pub glyphs: Vec<GlyphBox>,
136}
137
138/// A document, page number (zero based) and rasterisation scale in one call.
139pub fn render_page_number(
140    document: &Document,
141    page_index: usize,
142    options: &RenderOptions,
143) -> crate::Result<RenderedPage> {
144    let page = document.page(page_index)?;
145    render_page(document, &page, options)
146}
147
148/// [`render_page_number`], keeping what the walker painted: the raster and the
149/// page-space box of every glyph, for the text layer over it.
150pub fn render_page_number_traced(
151    document: &Document,
152    page_index: usize,
153    options: &RenderOptions,
154) -> crate::Result<TracedPage> {
155    let page = document.page(page_index)?;
156    render_page_traced(document, &page, options)
157}
158
159/// [`render_page`], keeping the glyph boxes.
160pub fn render_page_traced(
161    document: &Document,
162    page: &Page,
163    options: &RenderOptions,
164) -> crate::Result<TracedPage> {
165    let (page, placed, base) = paint_page(document, page, options)?;
166    let inverse = base
167        .invert()
168        .ok_or_else(|| pdf2::Error::malformed("the page transform is singular"))?;
169    let glyphs = placed
170        .into_iter()
171        .map(|glyph| {
172            let start = inverse.apply(glyph.start);
173            let end = inverse.apply(glyph.end);
174            GlyphBox {
175                text: glyph.text.map(String::from).unwrap_or_default(),
176                x: start.x,
177                y: start.y,
178                advance: (end.x - start.x).hypot(end.y - start.y),
179                size: glyph.size,
180            }
181        })
182        .collect();
183    Ok(TracedPage { page, glyphs })
184}
185
186/// `/Widths` of a simple font, in 1/1000 em, with the descriptor's
187/// `/MissingWidth` for codes the array does not cover (9.2.4).
188#[derive(Debug, Clone, Default, PartialEq)]
189struct SimpleWidths {
190    first: i64,
191    widths: Vec<f64>,
192    missing: f64,
193}
194
195impl SimpleWidths {
196    fn advance(&self, code: u8) -> f64 {
197        let code = i64::from(code);
198        let index = code - self.first;
199        if index >= 0 {
200            #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
201            if let Some(width) = self.widths.get(index as usize) {
202                return width / 1000.0;
203            }
204        }
205        self.missing / 1000.0
206    }
207}
208
209/// What a font resource yields, with the reason it is not drawable when it is
210/// not.
211#[derive(Debug, Clone, Default)]
212struct LoadedFont {
213    font: Option<Font>,
214    widths: Option<SimpleWidths>,
215    cid: Option<CidFont>,
216    type3: Option<Type3Font>,
217    note: Option<&'static str>,
218}
219
220/// A Type 3 font: each glyph is a content stream, not an outline (9.6.5).
221#[derive(Debug, Clone)]
222struct Type3Font {
223    /// `/CharProcs`: glyph name → content stream.
224    char_procs: pdf2::Dictionary,
225    /// Code → glyph name, from `/Encoding`'s `/Differences` (12.5.5, 9.6.6.1).
226    names: Vec<Option<Vec<u8>>>,
227    /// `/FontMatrix`: glyph space to text space, default `0.001` scale.
228    font_matrix: Matrix,
229    /// The font's own `/Resources`, which its char procedures paint with.
230    resources: Option<pdf2::Dictionary>,
231}
232
233/// What a `/Pattern` fill paints (8.7.3): a shading, or a tiling pattern's cell.
234#[derive(Debug, Clone)]
235enum PatternFill {
236    /// `/PatternType 2`: a shading that fills the path.
237    Shading(std::rc::Rc<crate::shading::Shading>),
238    /// `/PatternType 1`: a cell replicated over the path, and — for an
239    /// uncoloured (`/PaintType 2`) pattern — the colour given at use time, which
240    /// the cell's stencil is poured with (`8.7.3.3`).
241    Tile(std::rc::Rc<crate::pattern::Tile>, Option<Color>),
242}
243
244/// A composite (Type 0) font: two-byte codes, CIDs mapped to glyph ids through
245/// `/CIDToGIDMap`, and advances from `/W` with `/DW` as the default (9.7.4).
246#[derive(Debug, Clone)]
247struct CidFont {
248    font: Font,
249    to_gid: CidToGid,
250    widths: CidWidths,
251}
252
253#[derive(Debug, Clone)]
254enum CidToGid {
255    Identity,
256    Table(Vec<u16>),
257}
258
259#[derive(Debug, Clone, Default)]
260struct CidWidths {
261    /// `(first CID, widths)` runs from `/W`, in 1/1000 em.
262    ranges: Vec<(u32, Vec<f64>)>,
263    /// `/DW`, which the standard sets to 1000 when absent.
264    default: f64,
265}
266
267impl CidFont {
268    fn glyph_id(&self, cid: u16) -> u16 {
269        match &self.to_gid {
270            CidToGid::Identity => cid,
271            CidToGid::Table(table) => table.get(usize::from(cid)).copied().unwrap_or(0),
272        }
273    }
274
275    fn advance(&self, cid: u16) -> f64 {
276        for (start, widths) in &self.widths.ranges {
277            let index = u32::from(cid).wrapping_sub(*start);
278            if let Some(width) = widths.get(index as usize) {
279                return width / 1000.0;
280            }
281        }
282        self.widths.default / 1000.0
283    }
284}
285
286/// Rasterise one page.
287pub fn render_page(
288    document: &Document,
289    page: &Page,
290    options: &RenderOptions,
291) -> crate::Result<RenderedPage> {
292    Ok(paint_page(document, page, options)?.0)
293}
294
295/// One glyph the walker placed, in device pixels, with the pen's two ends: the
296/// page-space conversion happens once, at [`render_page_traced`].
297struct PlacedGlyph {
298    start: Point,
299    end: Point,
300    text: Option<char>,
301    size: f64,
302}
303
304/// Render a page and keep what it painted: the raster, its report, the glyphs
305/// the walker placed, and the page-to-device transform used.
306fn paint_page(
307    document: &Document,
308    page: &Page,
309    options: &RenderOptions,
310) -> crate::Result<(RenderedPage, Vec<PlacedGlyph>, Matrix)> {
311    let scale = if options.scale.is_finite() && options.scale > 0.0 {
312        options.scale
313    } else {
314        1.0
315    };
316    // The visible box is `/CropBox` when the page states one (14.11.2): it
317    // defines the raster and the origin, and the media box only bounds it.
318    let media = page
319        .crop_box
320        .or(page.media_box)
321        .unwrap_or(pdf2::Rect::new(0.0, 0.0, 612.0, 792.0));
322    // `/UserUnit` scales default user space (7.7.3.4), so it multiplies the
323    // device resolution rather than the page's coordinates.
324    let scale = scale * document.page_user_unit(page).unwrap_or(1.0);
325    // `/Rotate` turns the page clockwise for display, so a quarter turn swaps
326    // the canvas dimensions.
327    let rotate = page.rotate.rem_euclid(360);
328    let landscape = rotate == 90 || rotate == 270;
329    let (width_points, height_points) = if landscape {
330        (media.height(), media.width())
331    } else {
332        (media.width(), media.height())
333    };
334    let width = ((width_points * scale).round().max(1.0)) as u32;
335    let height = ((height_points * scale).round().max(1.0)) as u32;
336    let mut canvas = Canvas::new(width, height, options.background);
337    let mut report = Report::default();
338
339    // PDF user space to device space. Every case shifts the media box origin to
340    // (0, 0); the y axis grows downwards in the raster, and `/Rotate` composes
341    // a clockwise quarter turn (or two) on top of that flip.
342    let base = match rotate {
343        90 => Matrix::new(0.0, scale, scale, 0.0, -media.y0 * scale, -media.x0 * scale),
344        180 => Matrix::new(-scale, 0.0, 0.0, scale, media.x1 * scale, -media.y0 * scale),
345        270 => Matrix::new(0.0, scale, -scale, 0.0, media.y1 * scale, -media.x0 * scale),
346        _ => Matrix::new(scale, 0.0, 0.0, -scale, -media.x0 * scale, media.y1 * scale),
347    };
348
349    let content = document.page_content(page)?;
350    let mut walker = Walker {
351        canvas: &mut canvas,
352        report: &mut report,
353        document,
354        resources: page.resources.clone(),
355        state: State::new(base),
356        stack: Vec::new(),
357        path: Path::new(),
358        pending_clip: None,
359        mask: ClipMask::all(width, height),
360        form_depth: 0,
361        stream_starts: Vec::new(),
362        uncoloured_cell: false,
363        glyphs: Vec::new(),
364    };
365    walker.run(&content)?;
366    // Annotation appearance streams are drawn after the page content (12.5.5),
367    // and are the reason a page with an empty `/Contents` can still show
368    // something: 25 of the 49 silent-blank sample pages were exactly this.
369    walker.draw_annotations(page)?;
370    // Take the glyphs and release the walker's borrows before the report is
371    // read again below.
372    let glyphs = core::mem::take(&mut walker.glyphs);
373    drop(walker);
374    // A page that ran painting operators and produced an empty raster is not
375    // "all operators supported" — it is a page that drew nothing, and a reader
376    // deserves to know which. Silent blanks are the worst failure this renderer
377    // has: 49 of 160 blank pages in a 300-file sample, measured 2026-11-15.
378    if report.painted > 0 && report.unsupported.is_empty() && canvas.is_blank() {
379        report.note(b"drew-nothing");
380    }
381    Ok((RenderedPage { canvas, report }, glyphs, base))
382}
383
384/// The part of the graphics state that painting depends on.
385#[derive(Debug, Clone)]
386struct State {
387    ctm: Matrix,
388    line_width: f64,
389    cap: Cap,
390    join: Join,
391    dash: Dash,
392    fill: Color,
393    stroke: Color,
394    /// `/ca`: constant alpha for fills and text, 0..=1.
395    fill_alpha: f64,
396    /// `/CA`: constant alpha for strokes.
397    stroke_alpha: f64,
398    /// `/BM`: how a painted colour combines with what is already there.
399    blend: BlendMode,
400    /// The colour space `cs`/`CS` selected, when it is one this renderer can tint.
401    space: Option<crate::shading::Space>,
402    /// For a `/Pattern` colour space, the underlying space an uncoloured
403    /// pattern's colour is given in (`8.7.3.3`).
404    underlying: Option<crate::shading::Space>,
405    /// What a `/Pattern` fill paints, when `scn` named one.
406    pattern: Option<PatternFill>,
407    font: Option<Font>,
408    font_size: f64,
409    miter_limit: f64,
410    widths: Option<SimpleWidths>,
411    cid: Option<CidFont>,
412    type3: Option<Type3Font>,
413    char_spacing: f64,
414    word_spacing: f64,
415    horizontal_scale: f64,
416    leading: f64,
417    rise: f64,
418    /// `Tr`: 0 fill, 1 stroke, 2 both, 3 neither (invisible), 4–7 the same with
419    /// clipping (9.3).
420    text_mode: i64,
421    text_matrix: Matrix,
422    line_matrix: Matrix,
423}
424
425impl State {
426    fn new(ctm: Matrix) -> Self {
427        Self {
428            ctm,
429            line_width: 1.0,
430            cap: Cap::Butt,
431            join: Join::Miter,
432            dash: Dash::solid(),
433            fill: Color::BLACK,
434            stroke: Color::BLACK,
435            fill_alpha: 1.0,
436            stroke_alpha: 1.0,
437            blend: BlendMode::Normal,
438            space: None,
439            underlying: None,
440            pattern: None,
441            font: None,
442            font_size: 0.0,
443            miter_limit: 10.0,
444            widths: None,
445            cid: None,
446            type3: None,
447            char_spacing: 0.0,
448            word_spacing: 0.0,
449            horizontal_scale: 1.0,
450            leading: 0.0,
451            rise: 0.0,
452            text_mode: 0,
453            text_matrix: Matrix::IDENTITY,
454            line_matrix: Matrix::IDENTITY,
455        }
456    }
457}
458
459struct Walker<'a> {
460    canvas: &'a mut Canvas,
461    report: &'a mut Report,
462    document: &'a Document,
463    resources: Option<Dictionary>,
464    state: State,
465    stack: Vec<(State, ClipMask)>,
466    path: Path,
467    pending_clip: Option<bool>,
468    mask: ClipMask,
469    /// Form XObjects currently being drawn, for [`MAX_FORM_DEPTH`].
470    form_depth: usize,
471    /// The state each enclosing content stream started with, innermost last: a
472    /// pattern cell is painted with the parent stream's *initial* state (8.7.3.1).
473    stream_starts: Vec<State>,
474    /// Whether the content being run is an uncoloured pattern's cell, whose
475    /// operators "shall not explicitly specify any colours" (8.7.3.3).
476    uncoloured_cell: bool,
477    /// Every glyph painted so far, in device pixels: the text layer's source.
478    glyphs: Vec<PlacedGlyph>,
479}
480
481impl Walker<'_> {
482    fn run(&mut self, content: &[u8]) -> crate::Result<()> {
483        self.stream_starts.push(self.state.clone());
484        let mut parser = Parser::new(content);
485        let mut operands: Vec<Object> = Vec::new();
486        loop {
487            match parser.peek_token()? {
488                Token::Eof => break,
489                Token::Keyword(_) => {
490                    let operator = match parser.next_token()? {
491                        Token::Keyword(operator) => operator,
492                        _ => return Err(crate::Error::malformed("content-stream operator")),
493                    };
494                    self.execute(&operator, &mut operands, &mut parser)?;
495                    operands.clear();
496                }
497                _ => {
498                    operands.push(parser.parse_object()?);
499                }
500            }
501        }
502        self.stream_starts.pop();
503        Ok(())
504    }
505
506    fn execute(
507        &mut self,
508        operator: &[u8],
509        operands: &mut [Object],
510        parser: &mut Parser<'_>,
511    ) -> crate::Result<()> {
512        // Painting operators, counted so that a page which produced an empty
513        // raster can be told apart from one that had nothing to draw.
514        if matches!(
515            operator,
516            b"f" | b"F"
517                | b"f*"
518                | b"S"
519                | b"s"
520                | b"B"
521                | b"B*"
522                | b"b"
523                | b"b*"
524                | b"Tj"
525                | b"TJ"
526                | b"'"
527                | b"\""
528                | b"Do"
529                | b"BI"
530        ) {
531            self.report.painted += 1;
532        }
533        match operator {
534            b"q" => {
535                self.stack.push((self.state.clone(), self.mask.clone()));
536            }
537            b"Q" => {
538                if let Some((state, mask)) = self.stack.pop() {
539                    self.state = state;
540                    self.mask = mask;
541                }
542            }
543            b"cm" => {
544                if let Some(matrix) = matrix_operand(operands) {
545                    self.state.ctm = matrix.multiply(self.state.ctm);
546                }
547            }
548            b"gs" => {
549                if let Some(Object::Name(name)) = operands.first() {
550                    let name = name.clone();
551                    self.apply_ext_gstate(&name)?;
552                }
553            }
554            b"w" => self.state.line_width = number(operands, 0),
555            b"J" => {
556                self.state.cap = match integer(operands, 0) {
557                    1 => Cap::Round,
558                    2 => Cap::Square,
559                    _ => Cap::Butt,
560                }
561            }
562            b"j" => {
563                self.state.join = match integer(operands, 0) {
564                    1 => Join::Round,
565                    2 => Join::Bevel,
566                    _ => Join::Miter,
567                }
568            }
569            b"M" => self.state.miter_limit = number(operands, 0).max(1.0),
570            b"d" => self.state.dash = dash_operand(operands),
571            b"m" => {
572                if let Some(point) = point_operand(operands, 0) {
573                    self.path.move_to(point);
574                }
575            }
576            b"l" => {
577                if let Some(point) = point_operand(operands, 0) {
578                    self.path.line_to(point);
579                }
580            }
581            b"c" => {
582                if let (Some(c1), Some(c2), Some(to)) = (
583                    point_operand(operands, 0),
584                    point_operand(operands, 1),
585                    point_operand(operands, 2),
586                ) {
587                    self.path.curve_to(c1, c2, to);
588                }
589            }
590            b"v" | b"y" => {
591                // `v` and `y` are shorthand curves; draw them as a straight
592                // line to the end point, which keeps the path closed.
593                if let Some(to) = point_operand(operands, 1) {
594                    self.path.line_to(to);
595                }
596            }
597            b"h" => self.path.close(),
598            b"re" => {
599                let x = number(operands, 0);
600                let y = number(operands, 1);
601                let width = number(operands, 2);
602                let height = number(operands, 3);
603                self.path.add_rect(x, y, width, height);
604            }
605            b"S" => self.paint(Paint::Stroke, false)?,
606            b"s" => {
607                self.path.close();
608                self.paint(Paint::Stroke, false)?;
609            }
610            b"f" | b"F" => self.paint(Paint::Fill, false)?,
611            b"f*" => self.paint(Paint::Fill, true)?,
612            b"B" => self.paint(Paint::Both, false)?,
613            b"B*" => self.paint(Paint::Both, true)?,
614            b"b" => {
615                self.path.close();
616                self.paint(Paint::Both, false)?;
617            }
618            b"b*" => {
619                self.path.close();
620                self.paint(Paint::Both, true)?;
621            }
622            b"W" => self.pending_clip = Some(false),
623            b"W*" => self.pending_clip = Some(true),
624            b"n" => {
625                self.apply_pending_clip();
626                self.path = Path::new();
627            }
628            // An uncoloured pattern's cell "shall not explicitly specify any
629            // colours" (8.7.3.3); the operator is reported and the stencil keeps the
630            // poured colour, so the page names the defect instead of losing the tile.
631            b"g" | b"G" | b"rg" | b"RG" | b"k" | b"K" | b"cs" | b"CS" | b"sc" | b"SC" | b"scn"
632            | b"SCN"
633                if self.uncoloured_cell =>
634            {
635                self.report.note(operator);
636            }
637            b"g" => {
638                self.state.fill = Color::rgb(
639                    number(operands, 0),
640                    number(operands, 0),
641                    number(operands, 0),
642                )
643            }
644            b"G" => {
645                self.state.stroke = Color::rgb(
646                    number(operands, 0),
647                    number(operands, 0),
648                    number(operands, 0),
649                )
650            }
651            b"rg" => {
652                self.state.fill = Color::rgb(
653                    number(operands, 0),
654                    number(operands, 1),
655                    number(operands, 2),
656                );
657            }
658            b"RG" => {
659                self.state.stroke = Color::rgb(
660                    number(operands, 0),
661                    number(operands, 1),
662                    number(operands, 2),
663                );
664            }
665            b"k" => {
666                self.state.fill = Color::from_cmyk(
667                    number(operands, 0),
668                    number(operands, 1),
669                    number(operands, 2),
670                    number(operands, 3),
671                );
672            }
673            b"K" => {
674                self.state.stroke = Color::from_cmyk(
675                    number(operands, 0),
676                    number(operands, 1),
677                    number(operands, 2),
678                    number(operands, 3),
679                );
680            }
681            // `d0`/`d1` declare a Type 3 glyph's width (and, for `d1`, its bbox)
682            // in glyph space, which is what a Type 1 charstring's `setcachedevice`
683            // does. The width a page advances by comes from `/Widths`, so these
684            // are read and not acted on (9.6.5.2).
685            b"d0" | b"d1" => {}
686            b"BT" => {
687                self.state.text_matrix = Matrix::IDENTITY;
688                self.state.line_matrix = Matrix::IDENTITY;
689            }
690            b"ET" => {}
691            b"Tf" => {
692                let name = match operands.first() {
693                    Some(Object::Name(name)) => name.clone(),
694                    _ => return Err(crate::Error::malformed("/Tf needs a font name")),
695                };
696                self.state.font_size = number(operands, 1);
697                let (font, widths, cid, type3) = self.load_font(&name);
698                self.state.font = font;
699                self.state.widths = widths;
700                self.state.cid = cid;
701                self.state.type3 = type3;
702            }
703            b"Td" | b"TD" => {
704                let tx = number(operands, 0);
705                let ty = number(operands, 1);
706                self.state.line_matrix =
707                    Matrix::new(1.0, 0.0, 0.0, 1.0, tx, ty).multiply(self.state.line_matrix);
708                self.state.text_matrix = self.state.line_matrix;
709                if operator == b"TD" {
710                    self.state.leading = -ty;
711                }
712            }
713            b"T*" => {
714                self.state.line_matrix = Matrix::new(1.0, 0.0, 0.0, 1.0, 0.0, -self.state.leading)
715                    .multiply(self.state.line_matrix);
716                self.state.text_matrix = self.state.line_matrix;
717            }
718            b"Tm" => {
719                if let Some(matrix) = matrix_operand(operands) {
720                    self.state.line_matrix = matrix;
721                    self.state.text_matrix = matrix;
722                }
723            }
724            b"TL" => self.state.leading = number(operands, 0),
725            b"Tc" => self.state.char_spacing = number(operands, 0),
726            b"Tw" => self.state.word_spacing = number(operands, 0),
727            b"Tz" => self.state.horizontal_scale = number(operands, 0) / 100.0,
728            b"Ts" => self.state.rise = number(operands, 0),
729            b"Tr" => {
730                let mode = number(operands, 0);
731                let mode = if mode.is_finite() {
732                    #[allow(clippy::cast_possible_truncation)]
733                    let mode = mode as i64;
734                    mode.clamp(0, 7)
735                } else {
736                    0
737                };
738                // Modes 4–7 add clipping, which the rasteriser does not model
739                // yet; the fill and stroke halves are what a page shows.
740                self.state.text_mode = mode;
741            }
742            b"Tj" => {
743                if let Some(Object::String(string)) = operands.first() {
744                    let bytes = string.as_bytes().to_vec();
745                    self.show_text(&bytes)?;
746                }
747            }
748            b"'" => {
749                self.state.line_matrix = Matrix::new(1.0, 0.0, 0.0, 1.0, 0.0, -self.state.leading)
750                    .multiply(self.state.line_matrix);
751                self.state.text_matrix = self.state.line_matrix;
752                if let Some(Object::String(string)) = operands.first() {
753                    let bytes = string.as_bytes().to_vec();
754                    self.show_text(&bytes)?;
755                }
756            }
757            b"\"" => {
758                self.state.word_spacing = number(operands, 0);
759                self.state.char_spacing = number(operands, 1);
760                self.state.line_matrix = Matrix::new(1.0, 0.0, 0.0, 1.0, 0.0, -self.state.leading)
761                    .multiply(self.state.line_matrix);
762                self.state.text_matrix = self.state.line_matrix;
763                if let Some(Object::String(string)) = operands.get(2) {
764                    let bytes = string.as_bytes().to_vec();
765                    self.show_text(&bytes)?;
766                }
767            }
768            b"TJ" => {
769                if let Some(Object::Array(items)) = operands.first() {
770                    for item in items {
771                        match item {
772                            Object::String(string) => {
773                                let bytes = string.as_bytes().to_vec();
774                                self.show_text(&bytes)?;
775                            }
776                            Object::Integer(adjustment) => {
777                                self.adjust_text(*adjustment as f64);
778                            }
779                            Object::Real(adjustment) => self.adjust_text(*adjustment),
780                            _ => {}
781                        }
782                    }
783                }
784            }
785            b"Do" => {
786                if let Some(Object::Name(name)) = operands.first() {
787                    let name = name.clone();
788                    self.draw_image(&name)?;
789                }
790            }
791            b"cs" | b"CS" => {
792                if let Some(Object::Name(name)) = operands.first() {
793                    let name = name.clone();
794                    self.select_colour_space(&name)?;
795                }
796            }
797            b"sc" | b"SC" | b"scn" | b"SCN" => {
798                let stroke = operator == b"SC" || operator == b"SCN";
799                // `scn` names a pattern; for an uncoloured one the components come
800                // first and the name last (`0.30 0.75 0.21 /P2 scn`, 8.7.3.3).
801                if let Some(name) = operands.iter().find_map(|operand| match operand {
802                    Object::Name(name) => Some(name.clone()),
803                    _ => None,
804                }) {
805                    let values: Vec<f64> = operands.iter().filter_map(Object::as_real).collect();
806                    self.select_pattern(&name, &values)?;
807                } else if let Some(space) = self.state.space.clone() {
808                    let values: Vec<f64> = operands.iter().filter_map(Object::as_real).collect();
809                    let colour = crate::shading::color_in(&space, &values);
810                    if stroke {
811                        self.state.stroke = colour;
812                    } else {
813                        self.state.fill = colour;
814                    }
815                }
816            }
817            b"sh" => {
818                if let Some(Object::Name(name)) = operands.first() {
819                    let name = name.clone();
820                    self.paint_shading(&name)?;
821                }
822            }
823            b"BI" => {
824                skip_inline_image(parser)?;
825                self.report.note(operator);
826            }
827            _ => self.report.note(operator),
828        }
829        Ok(())
830    }
831
832    fn paint(&mut self, what: Paint, even_odd: bool) -> crate::Result<()> {
833        self.apply_pending_clip();
834        let ctm = self.state.ctm;
835        let scale = determinant_scale(ctm);
836        let polylines = self.path.flatten(ctm);
837        let painted = match what {
838            Paint::Fill | Paint::Both => true,
839            Paint::Stroke => false,
840        };
841        if painted && !polylines.is_empty() {
842            if let Some(pattern) = self.state.pattern.clone() {
843                // A pattern paints where the path fills: the path becomes the
844                // clip and the pattern the paint (8.7.3).
845                let mut mask = self.mask.clone();
846                mask.intersect(&clip_mask(
847                    self.canvas.width(),
848                    self.canvas.height(),
849                    &polylines,
850                    even_odd,
851                ));
852                match &pattern {
853                    PatternFill::Shading(shading) => {
854                        let to_device = shading.matrix().multiply(ctm);
855                        shading.with_matrix(to_device).paint_through(
856                            self.canvas,
857                            &mask,
858                            self.state.fill_alpha,
859                            self.state.blend,
860                        );
861                    }
862                    PatternFill::Tile(tile, colour) => {
863                        let (tile, colour) = (tile.clone(), *colour);
864                        self.paint_tile(&tile, colour, &polylines, &mask, ctm)?;
865                    }
866                }
867                self.path = Path::new();
868                return Ok(());
869            }
870            fill_polygons(
871                self.canvas,
872                &self.mask,
873                &polylines,
874                self.state.fill,
875                even_odd,
876                self.state.fill_alpha,
877                self.state.blend,
878            );
879        }
880        if matches!(what, Paint::Stroke | Paint::Both) {
881            let mut stroked: Vec<Vec<Point>> = Vec::new();
882            for polyline in &polylines {
883                stroked.extend(dash_polyline(polyline, &self.state.dash, scale));
884            }
885            let outline = stroke_outline(
886                &stroked,
887                self.state.line_width * scale,
888                self.state.cap,
889                self.state.join,
890                self.state.miter_limit,
891            );
892            if !outline.is_empty() {
893                fill_polygons(
894                    self.canvas,
895                    &self.mask,
896                    &outline,
897                    self.state.stroke,
898                    false,
899                    self.state.stroke_alpha,
900                    self.state.blend,
901                );
902            }
903        }
904        self.path = Path::new();
905        Ok(())
906    }
907
908    fn adjust_text(&mut self, adjustment: f64) {
909        let tx = -adjustment / 1000.0 * self.state.font_size * self.state.horizontal_scale;
910        self.state.text_matrix =
911            Matrix::new(1.0, 0.0, 0.0, 1.0, tx, 0.0).multiply(self.state.text_matrix);
912    }
913
914    fn show_text(&mut self, bytes: &[u8]) -> crate::Result<()> {
915        if let Some(cid) = self.state.cid.clone() {
916            // Identity-H and friends: the string is a run of two-byte codes.
917            for pair in bytes.as_chunks::<2>().0 {
918                let code = u16::from_be_bytes(*pair);
919                if let Some(glyph) = cid.font.glyph_by_id(cid.glyph_id(code)) {
920                    self.place_glyph(&glyph);
921                }
922                let advance = cid.advance(code) * self.state.font_size + self.state.char_spacing;
923                let advance = advance * self.state.horizontal_scale;
924                // A composite code has no character in the font's encoding: its
925                // text comes from `/ToUnicode`, which is the extractor's job.
926                self.note_glyph(None, advance);
927                self.advance_text(advance);
928            }
929            return Ok(());
930        }
931        if let Some(type3) = self.state.type3.clone() {
932            for &code in bytes {
933                self.run_type3_glyph(&type3, code)?;
934                let em = self
935                    .state
936                    .widths
937                    .as_ref()
938                    .map_or(0.0, |widths| widths.advance(code));
939                let mut advance = em * self.state.font_size + self.state.char_spacing;
940                if code == b' ' {
941                    advance += self.state.word_spacing;
942                }
943                let advance = advance * self.state.horizontal_scale;
944                // A Type 3 font names its glyphs; the name is what a reader can
945                // quote, and a name nobody recognises leaves the box textless.
946                let text = type3
947                    .names
948                    .get(usize::from(code))
949                    .and_then(|name| name.as_deref())
950                    .and_then(pdf2::encoding::glyph_name_character);
951                self.note_glyph(text, advance);
952                self.advance_text(advance);
953            }
954            return Ok(());
955        }
956        let Some(font) = self.state.font.clone() else {
957            return Ok(());
958        };
959        for &code in bytes {
960            if let Some(glyph) = font.glyph(code) {
961                self.place_glyph(&glyph);
962            }
963            let em = self
964                .state
965                .widths
966                .as_ref()
967                .map_or_else(|| font.advance(code), |widths| widths.advance(code));
968            let mut advance = em * self.state.font_size + self.state.char_spacing;
969            if code == b' ' {
970                advance += self.state.word_spacing;
971            }
972            let advance = advance * self.state.horizontal_scale;
973            self.note_glyph(font.character(code), advance);
974            self.advance_text(advance);
975        }
976        Ok(())
977    }
978
979    /// Fill one glyph outline at the current text position.
980    fn place_glyph(&mut self, glyph: &Glyph) {
981        if glyph.contours.is_empty() {
982            return;
983        }
984        // `Tr` (9.3.6, Table 104): 0 fill, 1 stroke, 2 both, 3 nothing, 4 fill+clip,
985        // 5 stroke+clip, 6 both+clip, 7 clip only. Mode 3 paints nothing *and* clips
986        // nothing, so it returns before the polygons are built.
987        let mode = self.state.text_mode;
988        if mode == 3 {
989            return;
990        }
991        let scale = Matrix::new(
992            self.state.font_size * self.state.horizontal_scale,
993            0.0,
994            0.0,
995            self.state.font_size,
996            0.0,
997            self.state.rise,
998        );
999        let transform = scale
1000            .multiply(self.state.text_matrix)
1001            .multiply(self.state.ctm);
1002        let polygons: Vec<Vec<Point>> = glyph
1003            .contours
1004            .iter()
1005            .map(|contour| {
1006                contour
1007                    .iter()
1008                    .map(|point| transform.apply(*point))
1009                    .collect()
1010            })
1011            .collect();
1012        // Modes 4–7 add the outlines to the *current* clip, as if they were a path
1013        // filled by the non-zero winding rule (8.5.3.3). The clip accumulates and
1014        // belongs to the graphics state, so `q`/`Q` already restores it.
1015        if matches!(mode, 4..=7) {
1016            let outline = clip_mask(self.canvas.width(), self.canvas.height(), &polygons, false);
1017            self.mask.intersect(&outline);
1018        }
1019        // Mode 7 clipped; it paints nothing.
1020        if mode == 7 {
1021            return;
1022        }
1023        let filled = matches!(mode, 0 | 2 | 4 | 6);
1024        if filled {
1025            fill_polygons(
1026                self.canvas,
1027                &self.mask,
1028                &polygons,
1029                self.state.fill,
1030                false,
1031                self.state.fill_alpha,
1032                self.state.blend,
1033            );
1034        }
1035        if matches!(mode, 1 | 2 | 5 | 6) {
1036            // A stroked glyph uses the text state's line width, cap and join.
1037            let mut outline = Vec::new();
1038            for polygon in &polygons {
1039                let mut closed = polygon.clone();
1040                if let Some(first) = closed.first().copied() {
1041                    closed.push(first);
1042                }
1043                outline.extend(stroke_outline(
1044                    &[closed],
1045                    self.state.line_width,
1046                    self.state.cap,
1047                    self.state.join,
1048                    self.state.miter_limit,
1049                ));
1050            }
1051            if !outline.is_empty() {
1052                fill_polygons(
1053                    self.canvas,
1054                    &self.mask,
1055                    &outline,
1056                    self.state.stroke,
1057                    false,
1058                    self.state.stroke_alpha,
1059                    self.state.blend,
1060                );
1061            }
1062        }
1063    }
1064
1065    /// Move the text position by `advance` in unscaled text space.
1066    /// Where the glyph's baseline starts, in device pixels.
1067    fn text_origin(&self) -> Point {
1068        self.state
1069            .text_matrix
1070            .multiply(self.state.ctm)
1071            .apply(Point::new(0.0, 0.0))
1072    }
1073
1074    /// Where the pen stands after `advance` text-space units.
1075    fn text_origin_after(&self, advance: f64) -> Point {
1076        self.state
1077            .text_matrix
1078            .multiply(self.state.ctm)
1079            .apply(Point::new(advance, 0.0))
1080    }
1081
1082    /// Record one painted glyph for the text layer, before the pen moves.
1083    fn note_glyph(&mut self, text: Option<char>, advance: f64) {
1084        let start = self.text_origin();
1085        let end = self.text_origin_after(advance);
1086        self.glyphs.push(PlacedGlyph {
1087            start,
1088            end,
1089            text,
1090            size: self.state.font_size,
1091        });
1092    }
1093
1094    fn advance_text(&mut self, advance: f64) {
1095        self.state.text_matrix =
1096            Matrix::new(1.0, 0.0, 0.0, 1.0, advance, 0.0).multiply(self.state.text_matrix);
1097    }
1098
1099    fn draw_image(&mut self, name: &[u8]) -> crate::Result<()> {
1100        let Some(resources) = self.resources.clone() else {
1101            self.report.note(b"Do");
1102            return Ok(());
1103        };
1104        let xobjects = match resolve(self.document, resources.get(b"XObject")) {
1105            Ok(Object::Dictionary(xobjects)) => xobjects,
1106            _ => {
1107                self.report.note(b"Do");
1108                return Ok(());
1109            }
1110        };
1111        let entry = match xobjects.get(name) {
1112            Some(entry) => entry.clone(),
1113            None => {
1114                self.report.note(b"Do");
1115                return Ok(());
1116            }
1117        };
1118        let object_id = match &entry {
1119            Object::Reference(id) => Some(*id),
1120            _ => None,
1121        };
1122        let object = resolve(self.document, Some(&entry))?;
1123        let Object::Stream(stream) = object else {
1124            self.report.note(b"Do");
1125            return Ok(());
1126        };
1127        match stream.dict().get(b"Subtype").and_then(Object::as_name) {
1128            Some(b"Image") => {}
1129            Some(b"Form") => return self.run_form(&stream),
1130            _ => {
1131                self.report.note(b"Do");
1132                return Ok(());
1133            }
1134        }
1135        match Image::from_stream(self.document, &stream, object_id) {
1136            Ok(image) => {
1137                image.paint(
1138                    self.canvas,
1139                    &self.mask,
1140                    self.state.ctm,
1141                    self.state.fill_alpha,
1142                    self.state.blend,
1143                );
1144            }
1145            // An image we cannot decode is reported, not fatal: the rest of the
1146            // page still renders.
1147            Err(_) => self.report.note(b"Do"),
1148        }
1149        Ok(())
1150    }
1151
1152    /// Run a `/Subtype /Form` XObject as a nested content stream (8.10).
1153    ///
1154    /// The form's `/Matrix` maps its space into the current one, its `/BBox`
1155    /// clips what it draws, and its `/Resources` replace the ones in force —
1156    /// falling back to them when the form has none, which is what the standard
1157    /// says and what most writers rely on. Depth is capped by
1158    /// [`MAX_FORM_DEPTH`] so a cycle is reported instead of followed.
1159    fn run_form(&mut self, stream: &pdf2::Stream) -> crate::Result<()> {
1160        self.run_form_nested(stream, Matrix::IDENTITY)
1161    }
1162
1163    /// Paint a tiling pattern over the filled path (8.7.3.1).
1164    ///
1165    /// The path is already the clip. The lattice is computed in **pattern
1166    /// space** — the path's device box mapped back through the pattern matrix —
1167    /// and each cell is clipped to its own `/BBox` and run as nested content.
1168    /// The clause sets no bound on the lattice, so [`MAX_TILE_CELLS`] is the
1169    /// renderer's: over it the fill is reported instead of attempted.
1170    fn paint_tile(
1171        &mut self,
1172        tile: &crate::pattern::Tile,
1173        colour: Option<Color>,
1174        polylines: &[Vec<Point>],
1175        mask: &ClipMask,
1176        ctm: Matrix,
1177    ) -> crate::Result<()> {
1178        let to_device = tile.matrix.multiply(ctm);
1179        let Some(to_pattern) = to_device.invert() else {
1180            self.report.note(b"pattern");
1181            return Ok(());
1182        };
1183        // The path's device box, and the pattern-space box it covers.
1184        let (mut min_x, mut min_y) = (f64::INFINITY, f64::INFINITY);
1185        let (mut max_x, mut max_y) = (f64::NEG_INFINITY, f64::NEG_INFINITY);
1186        for point in polylines.iter().flatten() {
1187            min_x = min_x.min(point.x);
1188            min_y = min_y.min(point.y);
1189            max_x = max_x.max(point.x);
1190            max_y = max_y.max(point.y);
1191        }
1192        if !min_x.is_finite() || !min_y.is_finite() {
1193            return Ok(());
1194        }
1195        let (mut p_min_x, mut p_min_y) = (f64::INFINITY, f64::INFINITY);
1196        let (mut p_max_x, mut p_max_y) = (f64::NEG_INFINITY, f64::NEG_INFINITY);
1197        for corner in [
1198            Point::new(min_x, min_y),
1199            Point::new(max_x, min_y),
1200            Point::new(max_x, max_y),
1201            Point::new(min_x, max_y),
1202        ] {
1203            let pattern = to_pattern.apply(corner);
1204            p_min_x = p_min_x.min(pattern.x);
1205            p_min_y = p_min_y.min(pattern.y);
1206            p_max_x = p_max_x.max(pattern.x);
1207            p_max_y = p_max_y.max(pattern.y);
1208        }
1209        // Cells sit at multiples of the step, with the key cell at the origin.
1210        #[allow(clippy::cast_possible_truncation)]
1211        let first_i = (p_min_x / tile.x_step).floor() as i64;
1212        #[allow(clippy::cast_possible_truncation)]
1213        let last_i = (p_max_x / tile.x_step).ceil() as i64;
1214        #[allow(clippy::cast_possible_truncation)]
1215        let first_j = (p_min_y / tile.y_step).floor() as i64;
1216        #[allow(clippy::cast_possible_truncation)]
1217        let last_j = (p_max_y / tile.y_step).ceil() as i64;
1218        let columns = last_i.saturating_sub(first_i).saturating_add(1);
1219        let rows = last_j.saturating_sub(first_j).saturating_add(1);
1220        let cells = columns.saturating_mul(rows);
1221        if cells <= 0 || usize::try_from(cells).unwrap_or(usize::MAX) > MAX_TILE_CELLS {
1222            self.report.note(b"pattern");
1223            return Ok(());
1224        }
1225        // `/TilingType` 1 and 3 ask for constant spacing on the **device** grid, which
1226        // is a whole-pixel lattice: type 1 may distort a cell by up to a pixel to keep
1227        // it and type 3 allows more distortion for speed. Snapping each cell's device
1228        // origin is that rule, and it is the difference a fractional `XStep` makes
1229        // visible. Type 2's contract is the opposite — no distortion, spacing may
1230        // drift by a pixel — so it keeps the exact pattern-space lattice.
1231        let snap = matches!(tile.tiling_type, 1 | 3);
1232        // The cell's own box, in pattern space, as a device quad per cell.
1233        let cell_corners = [
1234            Point::new(tile.bbox[0], tile.bbox[1]),
1235            Point::new(tile.bbox[2], tile.bbox[1]),
1236            Point::new(tile.bbox[2], tile.bbox[3]),
1237            Point::new(tile.bbox[0], tile.bbox[3]),
1238        ];
1239        for row in first_j..=last_j {
1240            for column in first_i..=last_i {
1241                #[allow(clippy::cast_precision_loss)]
1242                let offset = Matrix::new(
1243                    1.0,
1244                    0.0,
1245                    0.0,
1246                    1.0,
1247                    column as f64 * tile.x_step,
1248                    row as f64 * tile.y_step,
1249                );
1250                let cell = offset.multiply(to_device);
1251                let cell = if snap {
1252                    // `multiply` applies its argument first, so the shift lands in
1253                    // device space, after the pattern transform.
1254                    let origin = cell.apply(Point::new(0.0, 0.0));
1255                    Matrix::new(
1256                        1.0,
1257                        0.0,
1258                        0.0,
1259                        1.0,
1260                        origin.x.round() - origin.x,
1261                        origin.y.round() - origin.y,
1262                    )
1263                    .multiply(cell)
1264                } else {
1265                    cell
1266                };
1267                let quad: Vec<Point> = cell_corners
1268                    .iter()
1269                    .map(|point| cell.apply(*point))
1270                    .collect();
1271                let mut cell_mask = mask.clone();
1272                cell_mask.intersect(&clip_mask(
1273                    self.canvas.width(),
1274                    self.canvas.height(),
1275                    &[quad],
1276                    false,
1277                ));
1278                if cell_mask.count() == 0 {
1279                    continue;
1280                }
1281                self.run_tile(tile, colour, cell, cell_mask)?;
1282            }
1283        }
1284        Ok(())
1285    }
1286
1287    /// Run one pattern cell's content with its own state and resources.
1288    ///
1289    /// The clause says a cell is painted with "the graphics state that was in
1290    /// effect at the beginning of the pattern's parent content stream", so the
1291    /// base is the state this stream started with, and only the CTM is the
1292    /// pattern matrix composed with the one in force at fill time.
1293    fn run_tile(
1294        &mut self,
1295        tile: &crate::pattern::Tile,
1296        colour: Option<Color>,
1297        ctm: Matrix,
1298        mask: ClipMask,
1299    ) -> crate::Result<()> {
1300        if self.form_depth >= MAX_FORM_DEPTH {
1301            self.report.note(b"pattern");
1302            return Ok(());
1303        }
1304        let saved_state = self.state.clone();
1305        let saved_mask = core::mem::replace(&mut self.mask, mask);
1306        let saved_resources = self.resources.clone();
1307        let saved_path = core::mem::replace(&mut self.path, Path::new());
1308
1309        let mut base = self
1310            .stream_starts
1311            .last()
1312            .cloned()
1313            .unwrap_or_else(|| self.state.clone());
1314        base.ctm = ctm;
1315        // An uncoloured cell is a stencil: it is poured with the use-time colour,
1316        // and its own colour operators are refused rather than obeyed (8.7.3.3).
1317        if let Some(colour) = colour {
1318            base.fill = colour;
1319            base.stroke = colour;
1320        }
1321        self.state = base;
1322        self.resources = tile.resources.clone();
1323        self.form_depth += 1;
1324        self.uncoloured_cell = colour.is_some();
1325        let result = self.run(&tile.content);
1326        self.uncoloured_cell = false;
1327        self.form_depth -= 1;
1328
1329        self.state = saved_state;
1330        self.mask = saved_mask;
1331        self.resources = saved_resources;
1332        self.path = saved_path;
1333        result
1334    }
1335
1336    /// Run a form with `outer` composed after its own `/Matrix`.
1337    ///
1338    /// An annotation appearance is placed by mapping its transformed `/BBox`
1339    /// onto the annotation's `/Rect` (12.5.5): the form's `/Matrix` runs first,
1340    /// the placement is a transform of the enclosing user space, so it is
1341    /// applied after — `Matrix::multiply` applies its receiver first.
1342    fn run_form_nested(&mut self, stream: &pdf2::Stream, outer: Matrix) -> crate::Result<()> {
1343        if self.form_depth >= MAX_FORM_DEPTH {
1344            self.report.note(b"Do");
1345            return Ok(());
1346        }
1347        let dict = stream.dict();
1348        let bbox = match dict.get(b"BBox").and_then(rect_of) {
1349            Some(bbox) => bbox,
1350            None => {
1351                // `/BBox` is required; without it there is nothing to clip to.
1352                self.report.note(b"Do");
1353                return Ok(());
1354            }
1355        };
1356        let matrix = dict
1357            .get(b"Matrix")
1358            .and_then(Object::as_array)
1359            .and_then(matrix_operand)
1360            .unwrap_or(Matrix::IDENTITY);
1361        let resources = match dict.get(b"Resources") {
1362            Some(value) => match resolve(self.document, Some(value))? {
1363                Object::Dictionary(dict) => Some(dict),
1364                _ => self.resources.clone(),
1365            },
1366            None => self.resources.clone(),
1367        };
1368        let content = match self.document.decode_stream(stream) {
1369            Ok(content) => content,
1370            Err(_) => {
1371                // A form we cannot decode is reported like any other undrawn `Do`.
1372                self.report.note(b"Do");
1373                return Ok(());
1374            }
1375        };
1376
1377        let saved_state = self.state.clone();
1378        let saved_mask = self.mask.clone();
1379        let saved_resources = self.resources.clone();
1380        let saved_path = core::mem::replace(&mut self.path, Path::new());
1381
1382        self.state.ctm = matrix.multiply(outer).multiply(self.state.ctm);
1383        let corners = [
1384            Point::new(bbox.x0, bbox.y0),
1385            Point::new(bbox.x1, bbox.y0),
1386            Point::new(bbox.x1, bbox.y1),
1387            Point::new(bbox.x0, bbox.y1),
1388        ]
1389        .map(|point| self.state.ctm.apply(point));
1390        self.mask.intersect(&clip_mask(
1391            self.canvas.width(),
1392            self.canvas.height(),
1393            &[corners.to_vec()],
1394            false,
1395        ));
1396        self.resources = resources;
1397        self.form_depth += 1;
1398        let result = self.run(&content);
1399        self.form_depth -= 1;
1400
1401        self.state = saved_state;
1402        self.mask = saved_mask;
1403        self.resources = saved_resources;
1404        self.path = saved_path;
1405        result
1406    }
1407
1408    /// Apply an `/ExtGState` dictionary (8.4.5).
1409    ///
1410    /// What is honoured: `/ca` and `/CA` (constant alpha), a `/BM` of `/Normal`,
1411    /// and the line state — `/LW`, `/LC`, `/LJ`, `/ML`, `/D`. What is not is
1412    /// reported as `gs` rather than ignored, because a page that blends or masks
1413    /// and says nothing would look correct and not be.
1414    fn apply_ext_gstate(&mut self, name: &[u8]) -> crate::Result<()> {
1415        let Some(resources) = self.resources.clone() else {
1416            self.report.note(b"gs");
1417            return Ok(());
1418        };
1419        let states = match resolve(self.document, resources.get(b"ExtGState")) {
1420            Ok(Object::Dictionary(states)) => states,
1421            _ => {
1422                self.report.note(b"gs");
1423                return Ok(());
1424            }
1425        };
1426        let Some(entry) = states.get(name).cloned() else {
1427            self.report.note(b"gs");
1428            return Ok(());
1429        };
1430        let Object::Dictionary(dict) = resolve(self.document, Some(&entry))? else {
1431            self.report.note(b"gs");
1432            return Ok(());
1433        };
1434        // A soft mask or a blend mode this renderer cannot honour keeps the note:
1435        // the state is only "supported" when everything it asks for is applied.
1436        // `/SMask /None` is how a writer says "no mask" — `cmykjpeg.pdf` carries
1437        // exactly that, so it is not a mask to report.
1438        if let Some(mask) = dict.get(b"SMask") {
1439            match resolve(self.document, Some(mask))? {
1440                Object::Name(name) if name == b"None" => {}
1441                Object::Dictionary(mask) => {
1442                    if !self.apply_soft_mask(&mask)? {
1443                        self.report.note(b"gs");
1444                        return Ok(());
1445                    }
1446                }
1447                _ => {
1448                    self.report.note(b"gs");
1449                    return Ok(());
1450                }
1451            }
1452        }
1453        if let Some(blend) = dict.get(b"BM") {
1454            // `/BM` may be a name or an array whose first entry is used.
1455            let name = match blend {
1456                Object::Name(name) => Some(name.clone()),
1457                Object::Array(items) => items.first().and_then(Object::as_name).map(<[u8]>::to_vec),
1458                _ => None,
1459            };
1460            match name.as_deref().and_then(BlendMode::from_name) {
1461                Some(mode) => self.state.blend = mode,
1462                None => {
1463                    self.report.note(b"gs");
1464                    return Ok(());
1465                }
1466            }
1467        }
1468        if let Some(alpha) = dict.get(b"ca") {
1469            self.state.fill_alpha = alpha.as_real().unwrap_or(1.0).clamp(0.0, 1.0);
1470        }
1471        if let Some(alpha) = dict.get(b"CA") {
1472            self.state.stroke_alpha = alpha.as_real().unwrap_or(1.0).clamp(0.0, 1.0);
1473        }
1474        if let Some(width) = dict.get(b"LW")
1475            && let Some(width) = width.as_real()
1476        {
1477            self.state.line_width = width;
1478        }
1479        if let Some(cap) = dict.get(b"LC").and_then(Object::as_integer) {
1480            self.state.cap = if cap == 1 {
1481                Cap::Round
1482            } else if cap == 2 {
1483                Cap::Square
1484            } else {
1485                Cap::Butt
1486            };
1487        }
1488        if let Some(join) = dict.get(b"LJ").and_then(Object::as_integer) {
1489            self.state.join = if join == 1 { Join::Round } else { Join::Miter };
1490        }
1491        if let Some(limit) = dict.get(b"ML").and_then(Object::as_real) {
1492            self.state.miter_limit = limit;
1493        }
1494        // `/D` is `[dashArray dashPhase]` (table 58), not a flat list.
1495        if let Some(Object::Array(items)) = dict.get(b"D")
1496            && let Some(Object::Array(pattern)) = items.first()
1497        {
1498            let pattern: Vec<f64> = pattern.iter().filter_map(|item| item.as_real()).collect();
1499            let phase = items.get(1).and_then(Object::as_real).unwrap_or(0.0);
1500            self.state.dash = Dash { pattern, phase };
1501        }
1502        Ok(())
1503    }
1504
1505    /// Apply an `/SMask` entry (11.6.5.2) by multiplying its luminosity into the
1506    /// current coverage mask.
1507    ///
1508    /// The mask's `/G` form is rendered onto **black**, which is the backdrop the
1509    /// standard specifies: unpainted areas then have luminance 0 and hide
1510    /// everything, white shows everything, and greys fade proportionally. Only
1511    /// `/S /Luminosity` is honoured; an `/Alpha` mask needs a transparent canvas,
1512    /// which this rasteriser does not have, so it keeps the `gs` note instead of
1513    /// being approximated by a different definition of alpha.
1514    fn apply_soft_mask(&mut self, mask: &Dictionary) -> crate::Result<bool> {
1515        let kind = mask
1516            .get(b"S")
1517            .and_then(Object::as_name)
1518            .unwrap_or(b"Luminosity")
1519            .to_vec();
1520        if kind != b"Luminosity" {
1521            return Ok(false);
1522        }
1523        let Some(group) = mask.get(b"G") else {
1524            return Ok(false);
1525        };
1526        let Object::Stream(stream) = resolve(self.document, Some(group))? else {
1527            return Ok(false);
1528        };
1529        let content = match self.document.decode_stream(&stream) {
1530            Ok(content) => content,
1531            Err(_) => return Ok(false),
1532        };
1533        let resources = match stream.dict().get(b"Resources") {
1534            Some(value) => match resolve(self.document, Some(value))? {
1535                Object::Dictionary(dict) => Some(dict),
1536                _ => self.resources.clone(),
1537            },
1538            None => self.resources.clone(),
1539        };
1540        let mut backdrop = Canvas::new(
1541            self.canvas.width(),
1542            self.canvas.height(),
1543            Color::rgb(0.0, 0.0, 0.0),
1544        );
1545        let mut group_report = Report::default();
1546        let mut walker = Walker {
1547            canvas: &mut backdrop,
1548            report: &mut group_report,
1549            document: self.document,
1550            resources,
1551            state: State {
1552                ctm: self.state.ctm,
1553                // The mask group starts from a clean graphics state.
1554                ..State::new(self.state.ctm)
1555            },
1556            stack: Vec::new(),
1557            path: Path::new(),
1558            pending_clip: None,
1559            mask: ClipMask::all(self.canvas.width(), self.canvas.height()),
1560            form_depth: self.form_depth,
1561            stream_starts: Vec::new(),
1562            uncoloured_cell: false,
1563            // A pattern cell's glyphs belong to the cell, not the page: the
1564            // text layer over the page must not see them twice.
1565            glyphs: Vec::new(),
1566        };
1567        walker.run(&content)?;
1568        // A `Do` inside the mask group is the page's business too: merging the
1569        // counts keeps the report honest about what was not drawn.
1570        for (name, count) in &group_report.unsupported {
1571            for _ in 0..*count {
1572                self.report.note(name.as_bytes());
1573            }
1574        }
1575        self.mask.multiply_luminosity(&backdrop);
1576        Ok(true)
1577    }
1578
1579    /// `cs`/`CS`: select a colour space from the page's `/ColorSpace` resources.
1580    ///
1581    /// Only the spaces this renderer can tint are kept — a tint space
1582    /// (`/Separation`, `/DeviceN`) or a named device space; a `/Pattern` space is
1583    /// remembered as "no tint", because the next `scn` names the pattern instead.
1584    fn select_colour_space(&mut self, name: &[u8]) -> crate::Result<()> {
1585        self.state.pattern = None;
1586        let Some(resources) = self.resources.clone() else {
1587            return Ok(());
1588        };
1589        let Some(entry) = resources.get(b"ColorSpace").cloned() else {
1590            return Ok(());
1591        };
1592        let Object::Dictionary(spaces) = resolve(self.document, Some(&entry))? else {
1593            return Ok(());
1594        };
1595        let Some(entry) = spaces.get(name).cloned() else {
1596            return Ok(());
1597        };
1598        // The dictionary's entry is usually a *reference* (`/Cs1 5 0 R`, `/R8 8 0 R`),
1599        // so it is resolved once here: the array checks below were reading a reference
1600        // and concluding "not an array", which is how a legal `[/Pattern]` space got
1601        // reported as unresolvable.
1602        let value = resolve(self.document, Some(&entry))?;
1603        // A `/Pattern` colour space may be an array `[/Pattern /DeviceRGB]` whose
1604        // second element is the underlying space an uncoloured pattern's colour is
1605        // given in (8.7.3.3); anything else here is a tint space `scn` converts.
1606        self.state.underlying = match &value {
1607            Object::Array(items) => items
1608                .get(1)
1609                .and_then(|item| crate::shading::parse_space(self.document, item).ok()),
1610            _ => None,
1611        };
1612        // A space that cannot be resolved used to leave `None` behind in silence,
1613        // and `sc` with no space keeps the previous colour: the CV's page painted
1614        // black because `/Cs1` was an `/ICCBased` array and the failure was
1615        // invisible. `/Pattern` is the exception — its colour arrives through
1616        // `scn`, and the underlying space is already installed above.
1617        self.state.space = match crate::shading::parse_space(self.document, &value) {
1618            Ok(space) => Some(space),
1619            Err(_) => {
1620                let is_pattern = matches!(&value, Object::Array(items)
1621                    if items.first().and_then(Object::as_name) == Some(b"Pattern"));
1622                if !is_pattern {
1623                    self.report
1624                        .note(format!("cs:{}", String::from_utf8_lossy(name)).as_bytes());
1625                }
1626                None
1627            }
1628        };
1629        Ok(())
1630    }
1631
1632    /// `scn` naming a pattern: a shading becomes the fill's paint, and a tiling
1633    /// pattern becomes a cell — with the colour `values` pours through it when it
1634    /// is uncoloured (`8.7.3.3`).
1635    fn select_pattern(&mut self, name: &[u8], values: &[f64]) -> crate::Result<()> {
1636        let Some(resources) = self.resources.clone() else {
1637            return Ok(());
1638        };
1639        let Some(entry) = resources.get(b"Pattern").cloned() else {
1640            return Ok(());
1641        };
1642        let Object::Dictionary(patterns) = resolve(self.document, Some(&entry))? else {
1643            return Ok(());
1644        };
1645        let Some(pattern) = patterns.get(name).cloned() else {
1646            return Ok(());
1647        };
1648        // A pattern object is a stream (its content paints the cell or nothing);
1649        // the type lives in its dictionary.
1650        let object = resolve(self.document, Some(&pattern))?;
1651        let dict = match &object {
1652            Object::Stream(stream) => stream.dict().clone(),
1653            Object::Dictionary(dict) => dict.clone(),
1654            _ => {
1655                self.report.note(b"pattern");
1656                return Ok(());
1657            }
1658        };
1659        match dict.get(b"PatternType").and_then(Object::as_integer) {
1660            Some(2) => {
1661                let Some(shading) = dict.get(b"Shading") else {
1662                    self.report.note(b"pattern");
1663                    return Ok(());
1664                };
1665                if let Ok(shading) = crate::shading::Shading::from_object(self.document, shading) {
1666                    self.state.pattern = Some(PatternFill::Shading(std::rc::Rc::new(shading)));
1667                } else {
1668                    self.report.note(b"pattern");
1669                }
1670            }
1671            // A tiling pattern (`8.7.3`): a coloured cell paints its own content,
1672            // an uncoloured one is a stencil poured with the colour `scn` gave —
1673            // "the entire pattern cell is painted with a separately specified
1674            // colour each time the pattern is used" (8.7.3.1).
1675            Some(1) => match &object {
1676                Object::Stream(stream) => {
1677                    match crate::pattern::Tile::from_stream(self.document, stream) {
1678                        Ok(tile) => {
1679                            let colour = match tile.paint_type {
1680                                crate::pattern::PaintType::Coloured => {
1681                                    // "For other types of patterns, these operands shall
1682                                    // not be specified" (8.6.8): extra ones are reported,
1683                                    // not silently ignored.
1684                                    if !values.is_empty() {
1685                                        self.report.note(b"scn");
1686                                    }
1687                                    None
1688                                }
1689                                crate::pattern::PaintType::Uncoloured => {
1690                                    let Some(space) = self.state.underlying.clone() else {
1691                                        // Without `[/Pattern /Device]` there is no space
1692                                        // to read the colour in.
1693                                        self.report.note(b"pattern");
1694                                        return Ok(());
1695                                    };
1696                                    Some(crate::shading::color_in(&space, values))
1697                                }
1698                            };
1699                            self.state.pattern =
1700                                Some(PatternFill::Tile(std::rc::Rc::new(tile), colour));
1701                        }
1702                        Err(_) => self.report.note(b"pattern"),
1703                    }
1704                }
1705                _ => self.report.note(b"pattern"),
1706            },
1707            _ => self.report.note(b"pattern"),
1708        }
1709        Ok(())
1710    }
1711
1712    /// `sh`: paint a `/Shading` resource (8.7.4.3).
1713    ///
1714    /// The shading is sampled per pixel inside the current clip and its own
1715    /// bounding box, with the current fill alpha and blend mode — the same
1716    /// treatment a fill gets, which is what keeps a gradient under `/ca` and
1717    /// inside a `/BM` looking like the rest of the page.
1718    fn paint_shading(&mut self, name: &[u8]) -> crate::Result<()> {
1719        let Some(resources) = self.resources.clone() else {
1720            self.report.note(b"sh");
1721            return Ok(());
1722        };
1723        let Object::Dictionary(shadings) = resolve(self.document, resources.get(b"Shading"))?
1724        else {
1725            self.report.note(b"sh");
1726            return Ok(());
1727        };
1728        let Some(entry) = shadings.get(name).cloned() else {
1729            self.report.note(b"sh");
1730            return Ok(());
1731        };
1732        let Object::Dictionary(dict) = resolve(self.document, Some(&entry))? else {
1733            self.report.note(b"sh");
1734            return Ok(());
1735        };
1736        let shading = match crate::shading::Shading::parse(self.document, &dict) {
1737            Ok(shading) => shading,
1738            Err(_) => {
1739                self.report.note(b"sh");
1740                return Ok(());
1741            }
1742        };
1743        // The shading's own space is mapped into the page by its `/Matrix` and
1744        // then the CTM; painting goes through the inverse of that product.
1745        let to_device = shading.matrix().multiply(self.state.ctm);
1746        crate::shading::paint(
1747            &shading.with_matrix(to_device),
1748            self.canvas,
1749            &self.mask,
1750            self.state.fill_alpha,
1751            self.state.blend,
1752        );
1753        Ok(())
1754    }
1755
1756    /// Draw every annotation that has an appearance stream (12.5.5).
1757    ///
1758    /// `/Rect` is the area the annotation occupies in page user space;
1759    /// `/AP /N` is the normal appearance, either a form stream or a dictionary
1760    /// of them keyed by `/AS`. Annotations flagged invisible, hidden or
1761    /// no-view are skipped, which is what a viewer does with them.
1762    fn draw_annotations(&mut self, page: &Page) -> crate::Result<()> {
1763        let Some(id) = page.id else {
1764            return Ok(());
1765        };
1766        let annotations = match self.document.get_object(id)? {
1767            Object::Dictionary(dict) => match dict.get(b"Annots") {
1768                Some(value) => resolve(self.document, Some(value))?,
1769                None => return Ok(()),
1770            },
1771            _ => return Ok(()),
1772        };
1773        let Object::Array(annotations) = annotations else {
1774            return Ok(());
1775        };
1776        for annotation in annotations {
1777            let annotation = resolve(self.document, Some(&annotation))?;
1778            let Object::Dictionary(dict) = annotation else {
1779                continue;
1780            };
1781            if annotation_is_hidden(&dict) {
1782                continue;
1783            }
1784            let Some(rect) = dict.get(b"Rect").and_then(rect_of) else {
1785                continue;
1786            };
1787            if rect.width() <= 0.0 || rect.height() <= 0.0 {
1788                continue;
1789            }
1790            let Some(appearance) = self.normal_appearance(&dict)? else {
1791                continue;
1792            };
1793            let Some(bbox) = appearance.dict().get(b"BBox").and_then(rect_of) else {
1794                continue;
1795            };
1796            let matrix = appearance
1797                .dict()
1798                .get(b"Matrix")
1799                .and_then(Object::as_array)
1800                .and_then(matrix_operand)
1801                .unwrap_or(Matrix::IDENTITY);
1802            // The appearance's box, after its own matrix, is what gets mapped
1803            // onto `/Rect`.
1804            let corners = [
1805                Point::new(bbox.x0, bbox.y0),
1806                Point::new(bbox.x1, bbox.y0),
1807                Point::new(bbox.x1, bbox.y1),
1808                Point::new(bbox.x0, bbox.y1),
1809            ]
1810            .map(|point| matrix.apply(point));
1811            let (min_x, max_x) = corners
1812                .iter()
1813                .fold((f64::MAX, f64::MIN), |(low, high), point| {
1814                    (low.min(point.x), high.max(point.x))
1815                });
1816            let (min_y, max_y) = corners
1817                .iter()
1818                .fold((f64::MAX, f64::MIN), |(low, high), point| {
1819                    (low.min(point.y), high.max(point.y))
1820                });
1821            let width = max_x - min_x;
1822            let height = max_y - min_y;
1823            if width <= 0.0 || height <= 0.0 {
1824                continue;
1825            }
1826            let scale_x = rect.width() / width;
1827            let scale_y = rect.height() / height;
1828            let place = Matrix::new(
1829                scale_x,
1830                0.0,
1831                0.0,
1832                scale_y,
1833                rect.x0 - min_x * scale_x,
1834                rect.y0 - min_y * scale_y,
1835            );
1836            self.run_form_nested(&appearance, place)?;
1837        }
1838        Ok(())
1839    }
1840
1841    /// The annotation's normal appearance: a form stream, or the `/AS` entry of
1842    /// a dictionary of them. `None` when there is nothing to draw.
1843    fn normal_appearance(&self, dict: &Dictionary) -> crate::Result<Option<pdf2::Stream>> {
1844        let Some(ap) = dict.get(b"AP") else {
1845            return Ok(None);
1846        };
1847        let Object::Dictionary(ap) = resolve(self.document, Some(ap))? else {
1848            return Ok(None);
1849        };
1850        let Some(normal) = ap.get(b"N") else {
1851            return Ok(None);
1852        };
1853        let normal = resolve(self.document, Some(normal))?;
1854        match normal {
1855            Object::Stream(stream) => Ok(Some(stream)),
1856            Object::Dictionary(states) => {
1857                // `/AS` names the state a viewer shows; without it the first
1858                // entry is the only thing to go on.
1859                let state = dict
1860                    .get(b"AS")
1861                    .and_then(Object::as_name)
1862                    .and_then(|name| states.get(name))
1863                    .cloned()
1864                    .or_else(|| states.iter().next().map(|(_, value)| value.clone()));
1865                match state {
1866                    Some(value) => match resolve(self.document, Some(&value))? {
1867                        Object::Stream(stream) => Ok(Some(stream)),
1868                        _ => Ok(None),
1869                    },
1870                    None => Ok(None),
1871                }
1872            }
1873            _ => Ok(None),
1874        }
1875    }
1876
1877    #[allow(clippy::type_complexity)]
1878    fn load_font(
1879        &mut self,
1880        name: &[u8],
1881    ) -> (
1882        Option<Font>,
1883        Option<SimpleWidths>,
1884        Option<CidFont>,
1885        Option<Type3Font>,
1886    ) {
1887        let Some(loaded) = self.font_entry(name) else {
1888            return (None, None, None, None);
1889        };
1890        if let Some(note) = loaded.note {
1891            self.report.note(note.as_bytes());
1892        }
1893        (loaded.font, loaded.widths, loaded.cid, loaded.type3)
1894    }
1895
1896    /// Everything the walker needs from a font resource, with a note when the
1897    /// family is one this renderer cannot draw.
1898    fn font_entry(&mut self, name: &[u8]) -> Option<LoadedFont> {
1899        let resources = self.resources.clone()?;
1900        let fonts = match resolve(self.document, resources.get(b"Font")) {
1901            Ok(Object::Dictionary(fonts)) => fonts,
1902            _ => return None,
1903        };
1904        let entry = fonts.get(name)?.clone();
1905        let font_object = resolve(self.document, Some(&entry)).ok()?;
1906        let Object::Dictionary(font) = font_object else {
1907            return None;
1908        };
1909        let subtype = match font.get(b"Subtype") {
1910            Some(Object::Name(name)) => name.clone(),
1911            _ => Vec::new(),
1912        };
1913        match subtype.as_slice() {
1914            b"Type0" => return Some(self.cid_entry(&font)),
1915            b"Type3" => return Some(self.type3_entry(&font)),
1916            _ => {}
1917        }
1918        let encoding = self.encoding_for(&font);
1919        let widths = self.widths_for(&font);
1920        if let Some(descriptor) = font.get(b"FontDescriptor") {
1921            let descriptor = resolve(self.document, Some(descriptor)).ok()?;
1922            if let Object::Dictionary(descriptor) = descriptor {
1923                // A simple CFF font (`/FontFile3`, `/Subtype /Type1C`) carries no
1924                // `cmap`: its codes reach glyphs through the charset's names, so
1925                // it draws once the name map is read. Other `/FontFile3`
1926                // subtypes (OpenType-wrapped CFF is handled too) and Type 1
1927                // programs (`/FontFile`, `eexec`) are still the fallback font.
1928                if let Some(Object::Reference(id)) = descriptor.get(b"FontFile3")
1929                    && let Some(font) = self
1930                        .document
1931                        .stream_data(*id)
1932                        .ok()
1933                        .and_then(|data| Font::cff(encoding.clone(), data))
1934                    && font.has_glyph_names()
1935                {
1936                    return Some(LoadedFont {
1937                        font: Some(font),
1938                        widths,
1939                        cid: None,
1940                        type3: None,
1941                        note: None,
1942                    });
1943                }
1944                // A Type 1 program (`/FontFile`) is a PostScript program with
1945                // charstrings, which `ttf-parser` cannot read: `crate::type1` does,
1946                // and a simple font's code reaches its glyphs by the *names* the
1947                // encoding declares.
1948                if let Some(Object::Reference(id)) = descriptor.get(b"FontFile")
1949                    && let Some(font) = self
1950                        .document
1951                        .stream_data(*id)
1952                        .ok()
1953                        .and_then(|data| crate::type1::Program::parse(&data))
1954                        .and_then(|program| Font::type1(encoding.clone(), program))
1955                {
1956                    return Some(LoadedFont {
1957                        font: Some(font),
1958                        widths,
1959                        cid: None,
1960                        type3: None,
1961                        note: None,
1962                    });
1963                }
1964                for (key, kind) in [
1965                    (&b"FontFile3"[..], "font:FontFile3"),
1966                    (&b"FontFile"[..], "font:FontFile"),
1967                ] {
1968                    if descriptor.get(key).is_some() {
1969                        return Some(LoadedFont {
1970                            font: Some(Font::builtin(encoding)),
1971                            widths,
1972                            cid: None,
1973                            type3: None,
1974                            note: Some(kind),
1975                        });
1976                    }
1977                }
1978                if let Some(font_file) = descriptor.get(b"FontFile2") {
1979                    let data = match font_file {
1980                        Object::Reference(id) => self.document.stream_data(*id).ok(),
1981                        _ => None,
1982                    };
1983                    if let Some(data) = data
1984                        && let Some(font) = Font::true_type(encoding.clone(), data)
1985                    {
1986                        // A program with no `cmap` cannot be decoded from its
1987                        // codes; say so here, where the font is loaded, so the
1988                        // page reports it once rather than looking blank.
1989                        let note = if font.has_character_map() {
1990                            None
1991                        } else {
1992                            Some("font:TrueType-without-cmap")
1993                        };
1994                        return Some(LoadedFont {
1995                            font: Some(font),
1996                            widths,
1997                            cid: None,
1998                            type3: None,
1999                            note,
2000                        });
2001                    }
2002                }
2003            }
2004        }
2005        Some(LoadedFont {
2006            font: Some(Font::builtin(encoding)),
2007            widths,
2008            cid: None,
2009            type3: None,
2010            note: None,
2011        })
2012    }
2013
2014    /// A Type 0 font: a descendant CIDFontType2 with an embedded program and an
2015    /// identity CMap is drawable; anything else is reported by reason.
2016    /// A Type 3 font: a `/CharProcs` dictionary of content streams, selected by
2017    /// the glyph names its `/Encoding` declares (9.6.5).
2018    ///
2019    /// Without `/Differences` there are no names to select by, and the note says
2020    /// so rather than drawing nothing.
2021    fn type3_entry(&mut self, font: &Dictionary) -> LoadedFont {
2022        let char_procs = match resolve(self.document, font.get(b"CharProcs")) {
2023            Ok(Object::Dictionary(procs)) => procs,
2024            _ => {
2025                return LoadedFont {
2026                    note: Some("font:Type3"),
2027                    ..LoadedFont::default()
2028                };
2029            }
2030        };
2031        let Some(names) = self.type3_names(font) else {
2032            return LoadedFont {
2033                note: Some("font:Type3"),
2034                ..LoadedFont::default()
2035            };
2036        };
2037        let font_matrix = font
2038            .get(b"FontMatrix")
2039            .and_then(Object::as_array)
2040            .and_then(matrix_operand)
2041            .unwrap_or(Matrix::new(0.001, 0.0, 0.0, 0.001, 0.0, 0.0));
2042        let resources = match resolve(self.document, font.get(b"Resources")) {
2043            Ok(Object::Dictionary(resources)) => Some(resources),
2044            _ => self.resources.clone(),
2045        };
2046        let widths = self.widths_for(font);
2047        LoadedFont {
2048            type3: Some(Type3Font {
2049                char_procs,
2050                names,
2051                font_matrix,
2052                resources,
2053            }),
2054            widths,
2055            ..LoadedFont::default()
2056        }
2057    }
2058
2059    /// Code → glyph name from `/Encoding`'s `/Differences`, 256 entries.
2060    fn type3_names(&mut self, font: &Dictionary) -> Option<Vec<Option<Vec<u8>>>> {
2061        let Ok(encoding) = resolve(self.document, font.get(b"Encoding")) else {
2062            return None;
2063        };
2064        let Object::Dictionary(encoding) = encoding else {
2065            // A named base encoding alone gives no glyph names this renderer has.
2066            return None;
2067        };
2068        let Ok(Object::Array(differences)) = resolve(self.document, encoding.get(b"Differences"))
2069        else {
2070            return None;
2071        };
2072        let mut names = vec![None; 256];
2073        let mut code: Option<usize> = None;
2074        for entry in &differences {
2075            match entry {
2076                Object::Integer(value) => {
2077                    code = usize::try_from(*value).ok().filter(|value| *value < 256);
2078                }
2079                Object::Name(name) => {
2080                    if let Some(slot) = code.and_then(|at| names.get_mut(at)) {
2081                        *slot = Some(name.clone());
2082                    }
2083                    code = code.and_then(|at| at.checked_add(1)).filter(|at| *at < 256);
2084                }
2085                _ => {}
2086            }
2087        }
2088        Some(names)
2089    }
2090
2091    /// Run one Type 3 glyph's content stream in glyph space (9.6.5).
2092    ///
2093    /// The char procedure paints in glyph space, so it is placed by
2094    /// `/FontMatrix`, then the text rendering matrix — which is why the font
2095    /// matrix is the *first* factor. The glyph's own state is isolated: colour,
2096    /// width and clip a char procedure sets belong to that glyph.
2097    fn run_type3_glyph(&mut self, type3: &Type3Font, code: u8) -> crate::Result<()> {
2098        let Some(name) = type3.names.get(usize::from(code)).and_then(Option::as_ref) else {
2099            return Ok(());
2100        };
2101        // A char procedure with no glyph name in `/CharProcs` draws nothing.
2102        let Some(entry) = type3.char_procs.get(name).cloned() else {
2103            return Ok(());
2104        };
2105        let Object::Reference(id) = entry else {
2106            return Ok(());
2107        };
2108        let Ok(stream) = self.document.get_object(id) else {
2109            return Ok(());
2110        };
2111        let Object::Stream(stream) = stream else {
2112            return Ok(());
2113        };
2114        let content = match self.document.decode_stream(&stream) {
2115            Ok(content) => content,
2116            Err(_) => {
2117                self.report.note(b"Tj");
2118                return Ok(());
2119            }
2120        };
2121        if self.form_depth >= MAX_FORM_DEPTH {
2122            // `ContentStreamCycleType3insideType3.pdf` is exactly this: a glyph
2123            // whose procedure shows more text in the same font.
2124            self.report.note(b"Tj");
2125            return Ok(());
2126        }
2127        // Text rendering mode 3 paints nothing (9.3.6); modes 4–7 also *clip* to
2128        // the glyph outline, and a Type 3 glyph has no outline — it is a content
2129        // stream — so the clip is reported by name instead of silently empty.
2130        if matches!(self.state.text_mode, 4..=7) {
2131            self.report.note(b"text-clip");
2132            return Ok(());
2133        }
2134        if self.state.text_mode == 3 {
2135            return Ok(());
2136        }
2137
2138        let scale = Matrix::new(
2139            self.state.font_size * self.state.horizontal_scale,
2140            0.0,
2141            0.0,
2142            self.state.font_size,
2143            0.0,
2144            self.state.rise,
2145        );
2146        let glyph_ctm = type3
2147            .font_matrix
2148            .multiply(scale)
2149            .multiply(self.state.text_matrix)
2150            .multiply(self.state.ctm);
2151
2152        let saved_state = self.state.clone();
2153        let saved_mask = self.mask.clone();
2154        let saved_resources = self.resources.clone();
2155        let saved_path = core::mem::replace(&mut self.path, Path::new());
2156
2157        self.state.ctm = glyph_ctm;
2158        // The procedure's own text runs in *its* scope, not in this font's:
2159        // `d0`/`d1` and any `Tf` inside belong to the glyph.
2160        self.state.font = None;
2161        self.state.type3 = None;
2162        self.state.cid = None;
2163        self.state.widths = None;
2164        self.resources = type3.resources.clone();
2165        self.form_depth += 1;
2166        let result = self.run(&content);
2167        self.form_depth -= 1;
2168
2169        self.state = saved_state;
2170        self.mask = saved_mask;
2171        self.resources = saved_resources;
2172        self.path = saved_path;
2173        result
2174    }
2175
2176    fn cid_entry(&mut self, font: &Dictionary) -> LoadedFont {
2177        let identity = matches!(
2178            resolve(self.document, font.get(b"Encoding")).ok(),
2179            Some(Object::Name(name)) if name.starts_with(b"Identity")
2180        );
2181        if !identity {
2182            return LoadedFont {
2183                note: Some("font:Type0-cmap"),
2184                ..LoadedFont::default()
2185            };
2186        }
2187        let descendant = match resolve(self.document, font.get(b"DescendantFonts")).ok() {
2188            Some(Object::Array(items)) => items
2189                .first()
2190                .and_then(|item| resolve(self.document, Some(item)).ok()),
2191            _ => None,
2192        };
2193        let Some(Object::Dictionary(descendant)) = descendant else {
2194            return LoadedFont {
2195                note: Some("font:Type0-descendant"),
2196                ..LoadedFont::default()
2197            };
2198        };
2199        let subtype = match descendant.get(b"Subtype") {
2200            Some(Object::Name(name)) => name.clone(),
2201            _ => Vec::new(),
2202        };
2203        // CIDFontType2 is TrueType, CIDFontType0 is CFF; both draw once the
2204        // program is wrapped, so the only difference here is which descriptor
2205        // entry carries it.
2206        if subtype != b"CIDFontType2" && subtype != b"CIDFontType0" {
2207            return LoadedFont {
2208                note: Some("font:CIDFontType0-unknown"),
2209                ..LoadedFont::default()
2210            };
2211        }
2212        let is_cff = subtype == b"CIDFontType0";
2213        let program = descendant
2214            .get(b"FontDescriptor")
2215            .and_then(|descriptor| resolve(self.document, Some(descriptor)).ok())
2216            .and_then(|descriptor| match descriptor {
2217                Object::Dictionary(descriptor) => {
2218                    let entry: &[u8] = if is_cff { b"FontFile3" } else { b"FontFile2" };
2219                    descriptor.get(entry).and_then(|file| match file {
2220                        Object::Reference(id) => self.document.stream_data(*id).ok(),
2221                        _ => None,
2222                    })
2223                }
2224                _ => None,
2225            })
2226            .and_then(|data| {
2227                if is_cff {
2228                    // CFF arrives bare (`/CIDFontType0C`) or wrapped (`/OpenType`);
2229                    // `Font::cff` accepts both.
2230                    Font::cff(Encoding::standard(), data)
2231                } else {
2232                    Font::true_type(Encoding::standard(), data)
2233                }
2234            });
2235        let Some(program) = program else {
2236            return LoadedFont {
2237                note: Some("font:Type0-no-program"),
2238                ..LoadedFont::default()
2239            };
2240        };
2241        // Read the entry unresolved: resolving it would dereference the stream
2242        // reference and lose the id the bytes are behind.
2243        let to_gid = match descendant.get(b"CIDToGIDMap") {
2244            Some(Object::Name(name)) if name == b"Identity" => CidToGid::Identity,
2245            Some(Object::Reference(id)) => self
2246                .document
2247                .stream_data(*id)
2248                .map(|data| {
2249                    CidToGid::Table(
2250                        data.as_chunks::<2>()
2251                            .0
2252                            .iter()
2253                            .map(|pair| u16::from_be_bytes(*pair))
2254                            .collect(),
2255                    )
2256                })
2257                .unwrap_or(CidToGid::Identity),
2258            // Absent means identity.
2259            _ => CidToGid::Identity,
2260        };
2261        LoadedFont {
2262            font: None,
2263            widths: None,
2264            cid: Some(CidFont {
2265                font: program,
2266                to_gid,
2267                widths: self.cid_widths(&descendant),
2268            }),
2269            type3: None,
2270            note: None,
2271        }
2272    }
2273
2274    /// `/W` runs and `/DW` from a CID font dictionary (9.7.4.3).
2275    fn cid_widths(&self, descendant: &Dictionary) -> CidWidths {
2276        let mut ranges = vec![];
2277        if let Ok(Object::Array(items)) = resolve(self.document, descendant.get(b"W")) {
2278            let number = |item: Option<&Object>| {
2279                item.and_then(|item| resolve(self.document, Some(item)).ok())
2280                    .and_then(|item| item.as_real())
2281            };
2282            let mut index = 0;
2283            while index + 1 < items.len() {
2284                let Some(first) = number(items.get(index)) else {
2285                    break;
2286                };
2287                match items.get(index + 1) {
2288                    Some(Object::Array(list)) => {
2289                        let widths = list
2290                            .iter()
2291                            .map(Object::as_real)
2292                            .map(|w| w.unwrap_or(0.0))
2293                            .collect();
2294                        ranges.push((first as u32, widths));
2295                        index += 2;
2296                    }
2297                    second => {
2298                        let Some(last) = number(second) else { break };
2299                        let Some(width) = number(items.get(index + 2)) else {
2300                            break;
2301                        };
2302                        let count = (last - first).max(0.0) as usize + 1;
2303                        ranges.push((first as u32, vec![width; count]));
2304                        index += 3;
2305                    }
2306                }
2307            }
2308        }
2309        let default = number_of(self.document, descendant.get(b"DW")).unwrap_or(1000.0);
2310        CidWidths { ranges, default }
2311    }
2312
2313    /// `/Widths` plus the descriptor's `/MissingWidth`, when the font states
2314    /// them. A base-14 font usually does not, and then the glyph's own advance
2315    /// is the best available answer.
2316    fn widths_for(&self, font: &Dictionary) -> Option<SimpleWidths> {
2317        let first = font.get(b"FirstChar").and_then(Object::as_integer)?;
2318        let Object::Array(items) = resolve(self.document, font.get(b"Widths")).ok()? else {
2319            return None;
2320        };
2321        let widths: Vec<f64> = items
2322            .iter()
2323            .map(|item| number_of(self.document, Some(item)).unwrap_or(0.0))
2324            .collect();
2325        let missing = font
2326            .get(b"FontDescriptor")
2327            .and_then(|descriptor| resolve(self.document, Some(descriptor)).ok())
2328            .and_then(|descriptor| match descriptor {
2329                Object::Dictionary(descriptor) => {
2330                    number_of(self.document, descriptor.get(b"MissingWidth"))
2331                }
2332                _ => None,
2333            })
2334            .unwrap_or(0.0);
2335        Some(SimpleWidths {
2336            first,
2337            widths,
2338            missing,
2339        })
2340    }
2341
2342    fn encoding_for(&self, font: &Dictionary) -> Encoding {
2343        let Some(encoding_object) = font.get(b"Encoding") else {
2344            return Encoding::standard();
2345        };
2346        let Ok(encoding_object) = resolve(self.document, Some(encoding_object)) else {
2347            return Encoding::standard();
2348        };
2349        let mut encoding = Encoding::from_object(Some(&encoding_object)).unwrap_or_default();
2350        if let Object::Dictionary(dict) = &encoding_object
2351            && let Some(differences) = dict.get(b"Differences")
2352            && let Ok(Object::Array(items)) = resolve(self.document, Some(differences))
2353        {
2354            let _ = encoding.apply_differences(&items);
2355        }
2356        encoding
2357    }
2358
2359    fn apply_pending_clip(&mut self) {
2360        let Some(even_odd) = self.pending_clip.take() else {
2361            return;
2362        };
2363        let polylines = self.path.flatten(self.state.ctm);
2364        let mask = clip_mask(
2365            self.canvas.width(),
2366            self.canvas.height(),
2367            &polylines,
2368            even_odd,
2369        );
2370        self.mask.intersect(&mask);
2371    }
2372}
2373
2374#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2375enum Paint {
2376    Fill,
2377    Stroke,
2378    Both,
2379}
2380
2381fn determinant_scale(ctm: Matrix) -> f64 {
2382    let determinant = ctm.a * ctm.d - ctm.b * ctm.c;
2383    determinant.abs().sqrt()
2384}
2385
2386fn number(operands: &[Object], index: usize) -> f64 {
2387    operands.get(index).and_then(Object::as_real).unwrap_or(0.0)
2388}
2389
2390fn integer(operands: &[Object], index: usize) -> i64 {
2391    operands
2392        .get(index)
2393        .and_then(Object::as_integer)
2394        .unwrap_or(0)
2395}
2396
2397fn number_of(document: &Document, object: Option<&Object>) -> Option<f64> {
2398    resolve(document, object)
2399        .ok()
2400        .and_then(|object| object.as_real())
2401}
2402
2403/// Whether an annotation's `/F` flags say a viewer hides it (12.5.3, table 165):
2404/// invisible (bit 1), hidden (bit 2) and no-view (bit 6).
2405fn annotation_is_hidden(dict: &Dictionary) -> bool {
2406    let flags = dict
2407        .get(b"F")
2408        .and_then(Object::as_integer)
2409        .unwrap_or_default();
2410    flags & 0b100011 != 0
2411}
2412
2413/// A `/BBox` (or any four-number rectangle) as a [`pdf2::Rect`].
2414fn rect_of(object: &Object) -> Option<pdf2::Rect> {
2415    let items = object.as_array()?;
2416    if items.len() < 4 {
2417        return None;
2418    }
2419    let value = |index: usize| items.get(index).and_then(|item| item.as_real());
2420    let (x0, y0, x1, y1) = (value(0)?, value(1)?, value(2)?, value(3)?);
2421    Some(pdf2::Rect::new(
2422        x0.min(x1),
2423        y0.min(y1),
2424        x0.max(x1),
2425        y0.max(y1),
2426    ))
2427}
2428
2429fn matrix_operand(operands: &[Object]) -> Option<Matrix> {
2430    if operands.len() < 6 {
2431        return None;
2432    }
2433    Some(Matrix::new(
2434        number(operands, 0),
2435        number(operands, 1),
2436        number(operands, 2),
2437        number(operands, 3),
2438        number(operands, 4),
2439        number(operands, 5),
2440    ))
2441}
2442
2443/// The `pair`th point in the operands, if all of its numbers are there.
2444///
2445/// Callers name a *point*, not a number: `c` takes three of them at slots 0, 1
2446/// and 2, which are the numbers `(0, 1)`, `(2, 3)` and `(4, 5)`. Reading the
2447/// slot as a number index silently turned every curve's last control point into
2448/// its end point, which is what a wrong index looks like on the page.
2449fn point_operand(operands: &[Object], pair: usize) -> Option<Point> {
2450    let start = pair * 2;
2451    if operands.len() < start + 2 {
2452        return None;
2453    }
2454    Some(Point::new(
2455        number(operands, start),
2456        number(operands, start + 1),
2457    ))
2458}
2459
2460fn dash_operand(operands: &[Object]) -> Dash {
2461    let pattern = match operands.first() {
2462        Some(Object::Array(items)) => items
2463            .iter()
2464            .filter_map(Object::as_real)
2465            .collect::<Vec<f64>>(),
2466        _ => Vec::new(),
2467    };
2468    let phase = number(operands, 1);
2469    Dash { pattern, phase }
2470}
2471
2472/// Skip inline image data (`BI` … `EI`), which cannot be tokenised.
2473fn skip_inline_image(parser: &mut Parser<'_>) -> crate::Result<()> {
2474    let start = parser.raw_position();
2475    let content = parser.content();
2476    let found = content
2477        .get(start..)
2478        .and_then(|rest| find_operator(rest, b"EI"))
2479        .ok_or_else(|| crate::Error::malformed("inline image without a closing EI"))?;
2480    parser.seek(start + found + 2);
2481    Ok(())
2482}
2483
2484fn find_operator(haystack: &[u8], needle: &[u8]) -> Option<usize> {
2485    let mut index = 0;
2486    while index + needle.len() <= haystack.len() {
2487        if &haystack[index..index + needle.len()] == needle {
2488            let delimiter = |byte: u8| is_whitespace(byte) || is_delimiter(byte);
2489            let before_ok = index == 0 || delimiter(haystack[index - 1]);
2490            let after = index + needle.len();
2491            let after_ok = after >= haystack.len() || delimiter(haystack[after]);
2492            if before_ok && after_ok {
2493                return Some(index);
2494            }
2495        }
2496        index += 1;
2497    }
2498    None
2499}
2500
2501#[cfg(test)]
2502mod tests {
2503    use super::{Report, dash_operand};
2504    use pdf2::Object;
2505
2506    #[test]
2507    fn reports_collect_operator_counts_in_order() {
2508        let mut report = Report::default();
2509        report.note(b"Tj");
2510        report.note(b"Tj");
2511        report.note(b"Do");
2512        assert_eq!(report.unsupported_total(), 3);
2513        assert_eq!(report.unsupported.get("Tj"), Some(&2));
2514        assert_eq!(report.to_string(), "Do×1, Tj×2");
2515    }
2516
2517    #[test]
2518    fn dash_operands_default_to_solid() {
2519        assert!(dash_operand(&[]).is_solid());
2520        let dash = dash_operand(&[
2521            Object::array([Object::Integer(4), Object::Integer(2)]),
2522            Object::Integer(1),
2523        ]);
2524        assert_eq!(dash.pattern, vec![4.0, 2.0]);
2525        assert_eq!(dash.phase, 1.0);
2526    }
2527}