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