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        // `/TilingType` 1 and 3 ask for constant spacing on the **device** grid, which
1088        // is a whole-pixel lattice: type 1 may distort a cell by up to a pixel to keep
1089        // it and type 3 allows more distortion for speed. Snapping each cell's device
1090        // origin is that rule, and it is the difference a fractional `XStep` makes
1091        // visible. Type 2's contract is the opposite — no distortion, spacing may
1092        // drift by a pixel — so it keeps the exact pattern-space lattice.
1093        let snap = matches!(tile.tiling_type, 1 | 3);
1094        // The cell's own box, in pattern space, as a device quad per cell.
1095        let cell_corners = [
1096            Point::new(tile.bbox[0], tile.bbox[1]),
1097            Point::new(tile.bbox[2], tile.bbox[1]),
1098            Point::new(tile.bbox[2], tile.bbox[3]),
1099            Point::new(tile.bbox[0], tile.bbox[3]),
1100        ];
1101        for row in first_j..=last_j {
1102            for column in first_i..=last_i {
1103                #[allow(clippy::cast_precision_loss)]
1104                let offset = Matrix::new(
1105                    1.0,
1106                    0.0,
1107                    0.0,
1108                    1.0,
1109                    column as f64 * tile.x_step,
1110                    row as f64 * tile.y_step,
1111                );
1112                let cell = offset.multiply(to_device);
1113                let cell = if snap {
1114                    // `multiply` applies its argument first, so the shift lands in
1115                    // device space, after the pattern transform.
1116                    let origin = cell.apply(Point::new(0.0, 0.0));
1117                    Matrix::new(
1118                        1.0,
1119                        0.0,
1120                        0.0,
1121                        1.0,
1122                        origin.x.round() - origin.x,
1123                        origin.y.round() - origin.y,
1124                    )
1125                    .multiply(cell)
1126                } else {
1127                    cell
1128                };
1129                let quad: Vec<Point> = cell_corners
1130                    .iter()
1131                    .map(|point| cell.apply(*point))
1132                    .collect();
1133                let mut cell_mask = mask.clone();
1134                cell_mask.intersect(&clip_mask(
1135                    self.canvas.width(),
1136                    self.canvas.height(),
1137                    &[quad],
1138                    false,
1139                ));
1140                if cell_mask.count() == 0 {
1141                    continue;
1142                }
1143                self.run_tile(tile, colour, cell, cell_mask)?;
1144            }
1145        }
1146        Ok(())
1147    }
1148
1149    /// Run one pattern cell's content with its own state and resources.
1150    ///
1151    /// The clause says a cell is painted with "the graphics state that was in
1152    /// effect at the beginning of the pattern's parent content stream", so the
1153    /// base is the state this stream started with, and only the CTM is the
1154    /// pattern matrix composed with the one in force at fill time.
1155    fn run_tile(
1156        &mut self,
1157        tile: &crate::pattern::Tile,
1158        colour: Option<Color>,
1159        ctm: Matrix,
1160        mask: ClipMask,
1161    ) -> crate::Result<()> {
1162        if self.form_depth >= MAX_FORM_DEPTH {
1163            self.report.note(b"pattern");
1164            return Ok(());
1165        }
1166        let saved_state = self.state.clone();
1167        let saved_mask = core::mem::replace(&mut self.mask, mask);
1168        let saved_resources = self.resources.clone();
1169        let saved_path = core::mem::replace(&mut self.path, Path::new());
1170
1171        let mut base = self
1172            .stream_starts
1173            .last()
1174            .cloned()
1175            .unwrap_or_else(|| self.state.clone());
1176        base.ctm = ctm;
1177        // An uncoloured cell is a stencil: it is poured with the use-time colour,
1178        // and its own colour operators are refused rather than obeyed (8.7.3.3).
1179        if let Some(colour) = colour {
1180            base.fill = colour;
1181            base.stroke = colour;
1182        }
1183        self.state = base;
1184        self.resources = tile.resources.clone();
1185        self.form_depth += 1;
1186        self.uncoloured_cell = colour.is_some();
1187        let result = self.run(&tile.content);
1188        self.uncoloured_cell = false;
1189        self.form_depth -= 1;
1190
1191        self.state = saved_state;
1192        self.mask = saved_mask;
1193        self.resources = saved_resources;
1194        self.path = saved_path;
1195        result
1196    }
1197
1198    /// Run a form with `outer` composed after its own `/Matrix`.
1199    ///
1200    /// An annotation appearance is placed by mapping its transformed `/BBox`
1201    /// onto the annotation's `/Rect` (12.5.5): the form's `/Matrix` runs first,
1202    /// the placement is a transform of the enclosing user space, so it is
1203    /// applied after — `Matrix::multiply` applies its receiver first.
1204    fn run_form_nested(&mut self, stream: &pdf2::Stream, outer: Matrix) -> crate::Result<()> {
1205        if self.form_depth >= MAX_FORM_DEPTH {
1206            self.report.note(b"Do");
1207            return Ok(());
1208        }
1209        let dict = stream.dict();
1210        let bbox = match dict.get(b"BBox").and_then(rect_of) {
1211            Some(bbox) => bbox,
1212            None => {
1213                // `/BBox` is required; without it there is nothing to clip to.
1214                self.report.note(b"Do");
1215                return Ok(());
1216            }
1217        };
1218        let matrix = dict
1219            .get(b"Matrix")
1220            .and_then(Object::as_array)
1221            .and_then(matrix_operand)
1222            .unwrap_or(Matrix::IDENTITY);
1223        let resources = match dict.get(b"Resources") {
1224            Some(value) => match resolve(self.document, Some(value))? {
1225                Object::Dictionary(dict) => Some(dict),
1226                _ => self.resources.clone(),
1227            },
1228            None => self.resources.clone(),
1229        };
1230        let content = match self.document.decode_stream(stream) {
1231            Ok(content) => content,
1232            Err(_) => {
1233                // A form we cannot decode is reported like any other undrawn `Do`.
1234                self.report.note(b"Do");
1235                return Ok(());
1236            }
1237        };
1238
1239        let saved_state = self.state.clone();
1240        let saved_mask = self.mask.clone();
1241        let saved_resources = self.resources.clone();
1242        let saved_path = core::mem::replace(&mut self.path, Path::new());
1243
1244        self.state.ctm = matrix.multiply(outer).multiply(self.state.ctm);
1245        let corners = [
1246            Point::new(bbox.x0, bbox.y0),
1247            Point::new(bbox.x1, bbox.y0),
1248            Point::new(bbox.x1, bbox.y1),
1249            Point::new(bbox.x0, bbox.y1),
1250        ]
1251        .map(|point| self.state.ctm.apply(point));
1252        self.mask.intersect(&clip_mask(
1253            self.canvas.width(),
1254            self.canvas.height(),
1255            &[corners.to_vec()],
1256            false,
1257        ));
1258        self.resources = resources;
1259        self.form_depth += 1;
1260        let result = self.run(&content);
1261        self.form_depth -= 1;
1262
1263        self.state = saved_state;
1264        self.mask = saved_mask;
1265        self.resources = saved_resources;
1266        self.path = saved_path;
1267        result
1268    }
1269
1270    /// Apply an `/ExtGState` dictionary (8.4.5).
1271    ///
1272    /// What is honoured: `/ca` and `/CA` (constant alpha), a `/BM` of `/Normal`,
1273    /// and the line state — `/LW`, `/LC`, `/LJ`, `/ML`, `/D`. What is not is
1274    /// reported as `gs` rather than ignored, because a page that blends or masks
1275    /// and says nothing would look correct and not be.
1276    fn apply_ext_gstate(&mut self, name: &[u8]) -> crate::Result<()> {
1277        let Some(resources) = self.resources.clone() else {
1278            self.report.note(b"gs");
1279            return Ok(());
1280        };
1281        let states = match resolve(self.document, resources.get(b"ExtGState")) {
1282            Ok(Object::Dictionary(states)) => states,
1283            _ => {
1284                self.report.note(b"gs");
1285                return Ok(());
1286            }
1287        };
1288        let Some(entry) = states.get(name).cloned() else {
1289            self.report.note(b"gs");
1290            return Ok(());
1291        };
1292        let Object::Dictionary(dict) = resolve(self.document, Some(&entry))? else {
1293            self.report.note(b"gs");
1294            return Ok(());
1295        };
1296        // A soft mask or a blend mode this renderer cannot honour keeps the note:
1297        // the state is only "supported" when everything it asks for is applied.
1298        // `/SMask /None` is how a writer says "no mask" — `cmykjpeg.pdf` carries
1299        // exactly that, so it is not a mask to report.
1300        if let Some(mask) = dict.get(b"SMask") {
1301            match resolve(self.document, Some(mask))? {
1302                Object::Name(name) if name == b"None" => {}
1303                Object::Dictionary(mask) => {
1304                    if !self.apply_soft_mask(&mask)? {
1305                        self.report.note(b"gs");
1306                        return Ok(());
1307                    }
1308                }
1309                _ => {
1310                    self.report.note(b"gs");
1311                    return Ok(());
1312                }
1313            }
1314        }
1315        if let Some(blend) = dict.get(b"BM") {
1316            // `/BM` may be a name or an array whose first entry is used.
1317            let name = match blend {
1318                Object::Name(name) => Some(name.clone()),
1319                Object::Array(items) => items.first().and_then(Object::as_name).map(<[u8]>::to_vec),
1320                _ => None,
1321            };
1322            match name.as_deref().and_then(BlendMode::from_name) {
1323                Some(mode) => self.state.blend = mode,
1324                None => {
1325                    self.report.note(b"gs");
1326                    return Ok(());
1327                }
1328            }
1329        }
1330        if let Some(alpha) = dict.get(b"ca") {
1331            self.state.fill_alpha = alpha.as_real().unwrap_or(1.0).clamp(0.0, 1.0);
1332        }
1333        if let Some(alpha) = dict.get(b"CA") {
1334            self.state.stroke_alpha = alpha.as_real().unwrap_or(1.0).clamp(0.0, 1.0);
1335        }
1336        if let Some(width) = dict.get(b"LW")
1337            && let Some(width) = width.as_real()
1338        {
1339            self.state.line_width = width;
1340        }
1341        if let Some(cap) = dict.get(b"LC").and_then(Object::as_integer) {
1342            self.state.cap = if cap == 1 {
1343                Cap::Round
1344            } else if cap == 2 {
1345                Cap::Square
1346            } else {
1347                Cap::Butt
1348            };
1349        }
1350        if let Some(join) = dict.get(b"LJ").and_then(Object::as_integer) {
1351            self.state.join = if join == 1 { Join::Round } else { Join::Miter };
1352        }
1353        if let Some(limit) = dict.get(b"ML").and_then(Object::as_real) {
1354            self.state.miter_limit = limit;
1355        }
1356        // `/D` is `[dashArray dashPhase]` (table 58), not a flat list.
1357        if let Some(Object::Array(items)) = dict.get(b"D")
1358            && let Some(Object::Array(pattern)) = items.first()
1359        {
1360            let pattern: Vec<f64> = pattern.iter().filter_map(|item| item.as_real()).collect();
1361            let phase = items.get(1).and_then(Object::as_real).unwrap_or(0.0);
1362            self.state.dash = Dash { pattern, phase };
1363        }
1364        Ok(())
1365    }
1366
1367    /// Apply an `/SMask` entry (11.6.5.2) by multiplying its luminosity into the
1368    /// current coverage mask.
1369    ///
1370    /// The mask's `/G` form is rendered onto **black**, which is the backdrop the
1371    /// standard specifies: unpainted areas then have luminance 0 and hide
1372    /// everything, white shows everything, and greys fade proportionally. Only
1373    /// `/S /Luminosity` is honoured; an `/Alpha` mask needs a transparent canvas,
1374    /// which this rasteriser does not have, so it keeps the `gs` note instead of
1375    /// being approximated by a different definition of alpha.
1376    fn apply_soft_mask(&mut self, mask: &Dictionary) -> crate::Result<bool> {
1377        let kind = mask
1378            .get(b"S")
1379            .and_then(Object::as_name)
1380            .unwrap_or(b"Luminosity")
1381            .to_vec();
1382        if kind != b"Luminosity" {
1383            return Ok(false);
1384        }
1385        let Some(group) = mask.get(b"G") else {
1386            return Ok(false);
1387        };
1388        let Object::Stream(stream) = resolve(self.document, Some(group))? else {
1389            return Ok(false);
1390        };
1391        let content = match self.document.decode_stream(&stream) {
1392            Ok(content) => content,
1393            Err(_) => return Ok(false),
1394        };
1395        let resources = match stream.dict().get(b"Resources") {
1396            Some(value) => match resolve(self.document, Some(value))? {
1397                Object::Dictionary(dict) => Some(dict),
1398                _ => self.resources.clone(),
1399            },
1400            None => self.resources.clone(),
1401        };
1402        let mut backdrop = Canvas::new(
1403            self.canvas.width(),
1404            self.canvas.height(),
1405            Color::rgb(0.0, 0.0, 0.0),
1406        );
1407        let mut group_report = Report::default();
1408        let mut walker = Walker {
1409            canvas: &mut backdrop,
1410            report: &mut group_report,
1411            document: self.document,
1412            resources,
1413            state: State {
1414                ctm: self.state.ctm,
1415                // The mask group starts from a clean graphics state.
1416                ..State::new(self.state.ctm)
1417            },
1418            stack: Vec::new(),
1419            path: Path::new(),
1420            pending_clip: None,
1421            mask: ClipMask::all(self.canvas.width(), self.canvas.height()),
1422            form_depth: self.form_depth,
1423            stream_starts: Vec::new(),
1424            uncoloured_cell: false,
1425        };
1426        walker.run(&content)?;
1427        // A `Do` inside the mask group is the page's business too: merging the
1428        // counts keeps the report honest about what was not drawn.
1429        for (name, count) in &group_report.unsupported {
1430            for _ in 0..*count {
1431                self.report.note(name.as_bytes());
1432            }
1433        }
1434        self.mask.multiply_luminosity(&backdrop);
1435        Ok(true)
1436    }
1437
1438    /// `cs`/`CS`: select a colour space from the page's `/ColorSpace` resources.
1439    ///
1440    /// Only the spaces this renderer can tint are kept — a tint space
1441    /// (`/Separation`, `/DeviceN`) or a named device space; a `/Pattern` space is
1442    /// remembered as "no tint", because the next `scn` names the pattern instead.
1443    fn select_colour_space(&mut self, name: &[u8]) -> crate::Result<()> {
1444        self.state.pattern = None;
1445        let Some(resources) = self.resources.clone() else {
1446            return Ok(());
1447        };
1448        let Some(entry) = resources.get(b"ColorSpace").cloned() else {
1449            return Ok(());
1450        };
1451        let Object::Dictionary(spaces) = resolve(self.document, Some(&entry))? else {
1452            return Ok(());
1453        };
1454        let Some(entry) = spaces.get(name).cloned() else {
1455            return Ok(());
1456        };
1457        // The dictionary's entry is usually a *reference* (`/Cs1 5 0 R`, `/R8 8 0 R`),
1458        // so it is resolved once here: the array checks below were reading a reference
1459        // and concluding "not an array", which is how a legal `[/Pattern]` space got
1460        // reported as unresolvable.
1461        let value = resolve(self.document, Some(&entry))?;
1462        // A `/Pattern` colour space may be an array `[/Pattern /DeviceRGB]` whose
1463        // second element is the underlying space an uncoloured pattern's colour is
1464        // given in (8.7.3.3); anything else here is a tint space `scn` converts.
1465        self.state.underlying = match &value {
1466            Object::Array(items) => items
1467                .get(1)
1468                .and_then(|item| crate::shading::parse_space(self.document, item).ok()),
1469            _ => None,
1470        };
1471        // A space that cannot be resolved used to leave `None` behind in silence,
1472        // and `sc` with no space keeps the previous colour: the CV's page painted
1473        // black because `/Cs1` was an `/ICCBased` array and the failure was
1474        // invisible. `/Pattern` is the exception — its colour arrives through
1475        // `scn`, and the underlying space is already installed above.
1476        self.state.space = match crate::shading::parse_space(self.document, &value) {
1477            Ok(space) => Some(space),
1478            Err(_) => {
1479                let is_pattern = matches!(&value, Object::Array(items)
1480                    if items.first().and_then(Object::as_name) == Some(b"Pattern"));
1481                if !is_pattern {
1482                    self.report
1483                        .note(format!("cs:{}", String::from_utf8_lossy(name)).as_bytes());
1484                }
1485                None
1486            }
1487        };
1488        Ok(())
1489    }
1490
1491    /// `scn` naming a pattern: a shading becomes the fill's paint, and a tiling
1492    /// pattern becomes a cell — with the colour `values` pours through it when it
1493    /// is uncoloured (`8.7.3.3`).
1494    fn select_pattern(&mut self, name: &[u8], values: &[f64]) -> crate::Result<()> {
1495        let Some(resources) = self.resources.clone() else {
1496            return Ok(());
1497        };
1498        let Some(entry) = resources.get(b"Pattern").cloned() else {
1499            return Ok(());
1500        };
1501        let Object::Dictionary(patterns) = resolve(self.document, Some(&entry))? else {
1502            return Ok(());
1503        };
1504        let Some(pattern) = patterns.get(name).cloned() else {
1505            return Ok(());
1506        };
1507        // A pattern object is a stream (its content paints the cell or nothing);
1508        // the type lives in its dictionary.
1509        let object = resolve(self.document, Some(&pattern))?;
1510        let dict = match &object {
1511            Object::Stream(stream) => stream.dict().clone(),
1512            Object::Dictionary(dict) => dict.clone(),
1513            _ => {
1514                self.report.note(b"pattern");
1515                return Ok(());
1516            }
1517        };
1518        match dict.get(b"PatternType").and_then(Object::as_integer) {
1519            Some(2) => {
1520                let Some(shading) = dict.get(b"Shading") else {
1521                    self.report.note(b"pattern");
1522                    return Ok(());
1523                };
1524                if let Ok(shading) = crate::shading::Shading::from_object(self.document, shading) {
1525                    self.state.pattern = Some(PatternFill::Shading(std::rc::Rc::new(shading)));
1526                } else {
1527                    self.report.note(b"pattern");
1528                }
1529            }
1530            // A tiling pattern (`8.7.3`): a coloured cell paints its own content,
1531            // an uncoloured one is a stencil poured with the colour `scn` gave —
1532            // "the entire pattern cell is painted with a separately specified
1533            // colour each time the pattern is used" (8.7.3.1).
1534            Some(1) => match &object {
1535                Object::Stream(stream) => {
1536                    match crate::pattern::Tile::from_stream(self.document, stream) {
1537                        Ok(tile) => {
1538                            let colour = match tile.paint_type {
1539                                crate::pattern::PaintType::Coloured => {
1540                                    // "For other types of patterns, these operands shall
1541                                    // not be specified" (8.6.8): extra ones are reported,
1542                                    // not silently ignored.
1543                                    if !values.is_empty() {
1544                                        self.report.note(b"scn");
1545                                    }
1546                                    None
1547                                }
1548                                crate::pattern::PaintType::Uncoloured => {
1549                                    let Some(space) = self.state.underlying.clone() else {
1550                                        // Without `[/Pattern /Device]` there is no space
1551                                        // to read the colour in.
1552                                        self.report.note(b"pattern");
1553                                        return Ok(());
1554                                    };
1555                                    Some(crate::shading::color_in(&space, values))
1556                                }
1557                            };
1558                            self.state.pattern =
1559                                Some(PatternFill::Tile(std::rc::Rc::new(tile), colour));
1560                        }
1561                        Err(_) => self.report.note(b"pattern"),
1562                    }
1563                }
1564                _ => self.report.note(b"pattern"),
1565            },
1566            _ => self.report.note(b"pattern"),
1567        }
1568        Ok(())
1569    }
1570
1571    /// `sh`: paint a `/Shading` resource (8.7.4.3).
1572    ///
1573    /// The shading is sampled per pixel inside the current clip and its own
1574    /// bounding box, with the current fill alpha and blend mode — the same
1575    /// treatment a fill gets, which is what keeps a gradient under `/ca` and
1576    /// inside a `/BM` looking like the rest of the page.
1577    fn paint_shading(&mut self, name: &[u8]) -> crate::Result<()> {
1578        let Some(resources) = self.resources.clone() else {
1579            self.report.note(b"sh");
1580            return Ok(());
1581        };
1582        let Object::Dictionary(shadings) = resolve(self.document, resources.get(b"Shading"))?
1583        else {
1584            self.report.note(b"sh");
1585            return Ok(());
1586        };
1587        let Some(entry) = shadings.get(name).cloned() else {
1588            self.report.note(b"sh");
1589            return Ok(());
1590        };
1591        let Object::Dictionary(dict) = resolve(self.document, Some(&entry))? else {
1592            self.report.note(b"sh");
1593            return Ok(());
1594        };
1595        let shading = match crate::shading::Shading::parse(self.document, &dict) {
1596            Ok(shading) => shading,
1597            Err(_) => {
1598                self.report.note(b"sh");
1599                return Ok(());
1600            }
1601        };
1602        // The shading's own space is mapped into the page by its `/Matrix` and
1603        // then the CTM; painting goes through the inverse of that product.
1604        let to_device = shading.matrix().multiply(self.state.ctm);
1605        crate::shading::paint(
1606            &shading.with_matrix(to_device),
1607            self.canvas,
1608            &self.mask,
1609            self.state.fill_alpha,
1610            self.state.blend,
1611        );
1612        Ok(())
1613    }
1614
1615    /// Draw every annotation that has an appearance stream (12.5.5).
1616    ///
1617    /// `/Rect` is the area the annotation occupies in page user space;
1618    /// `/AP /N` is the normal appearance, either a form stream or a dictionary
1619    /// of them keyed by `/AS`. Annotations flagged invisible, hidden or
1620    /// no-view are skipped, which is what a viewer does with them.
1621    fn draw_annotations(&mut self, page: &Page) -> crate::Result<()> {
1622        let Some(id) = page.id else {
1623            return Ok(());
1624        };
1625        let annotations = match self.document.get_object(id)? {
1626            Object::Dictionary(dict) => match dict.get(b"Annots") {
1627                Some(value) => resolve(self.document, Some(value))?,
1628                None => return Ok(()),
1629            },
1630            _ => return Ok(()),
1631        };
1632        let Object::Array(annotations) = annotations else {
1633            return Ok(());
1634        };
1635        for annotation in annotations {
1636            let annotation = resolve(self.document, Some(&annotation))?;
1637            let Object::Dictionary(dict) = annotation else {
1638                continue;
1639            };
1640            if annotation_is_hidden(&dict) {
1641                continue;
1642            }
1643            let Some(rect) = dict.get(b"Rect").and_then(rect_of) else {
1644                continue;
1645            };
1646            if rect.width() <= 0.0 || rect.height() <= 0.0 {
1647                continue;
1648            }
1649            let Some(appearance) = self.normal_appearance(&dict)? else {
1650                continue;
1651            };
1652            let Some(bbox) = appearance.dict().get(b"BBox").and_then(rect_of) else {
1653                continue;
1654            };
1655            let matrix = appearance
1656                .dict()
1657                .get(b"Matrix")
1658                .and_then(Object::as_array)
1659                .and_then(matrix_operand)
1660                .unwrap_or(Matrix::IDENTITY);
1661            // The appearance's box, after its own matrix, is what gets mapped
1662            // onto `/Rect`.
1663            let corners = [
1664                Point::new(bbox.x0, bbox.y0),
1665                Point::new(bbox.x1, bbox.y0),
1666                Point::new(bbox.x1, bbox.y1),
1667                Point::new(bbox.x0, bbox.y1),
1668            ]
1669            .map(|point| matrix.apply(point));
1670            let (min_x, max_x) = corners
1671                .iter()
1672                .fold((f64::MAX, f64::MIN), |(low, high), point| {
1673                    (low.min(point.x), high.max(point.x))
1674                });
1675            let (min_y, max_y) = corners
1676                .iter()
1677                .fold((f64::MAX, f64::MIN), |(low, high), point| {
1678                    (low.min(point.y), high.max(point.y))
1679                });
1680            let width = max_x - min_x;
1681            let height = max_y - min_y;
1682            if width <= 0.0 || height <= 0.0 {
1683                continue;
1684            }
1685            let scale_x = rect.width() / width;
1686            let scale_y = rect.height() / height;
1687            let place = Matrix::new(
1688                scale_x,
1689                0.0,
1690                0.0,
1691                scale_y,
1692                rect.x0 - min_x * scale_x,
1693                rect.y0 - min_y * scale_y,
1694            );
1695            self.run_form_nested(&appearance, place)?;
1696        }
1697        Ok(())
1698    }
1699
1700    /// The annotation's normal appearance: a form stream, or the `/AS` entry of
1701    /// a dictionary of them. `None` when there is nothing to draw.
1702    fn normal_appearance(&self, dict: &Dictionary) -> crate::Result<Option<pdf2::Stream>> {
1703        let Some(ap) = dict.get(b"AP") else {
1704            return Ok(None);
1705        };
1706        let Object::Dictionary(ap) = resolve(self.document, Some(ap))? else {
1707            return Ok(None);
1708        };
1709        let Some(normal) = ap.get(b"N") else {
1710            return Ok(None);
1711        };
1712        let normal = resolve(self.document, Some(normal))?;
1713        match normal {
1714            Object::Stream(stream) => Ok(Some(stream)),
1715            Object::Dictionary(states) => {
1716                // `/AS` names the state a viewer shows; without it the first
1717                // entry is the only thing to go on.
1718                let state = dict
1719                    .get(b"AS")
1720                    .and_then(Object::as_name)
1721                    .and_then(|name| states.get(name))
1722                    .cloned()
1723                    .or_else(|| states.iter().next().map(|(_, value)| value.clone()));
1724                match state {
1725                    Some(value) => match resolve(self.document, Some(&value))? {
1726                        Object::Stream(stream) => Ok(Some(stream)),
1727                        _ => Ok(None),
1728                    },
1729                    None => Ok(None),
1730                }
1731            }
1732            _ => Ok(None),
1733        }
1734    }
1735
1736    #[allow(clippy::type_complexity)]
1737    fn load_font(
1738        &mut self,
1739        name: &[u8],
1740    ) -> (
1741        Option<Font>,
1742        Option<SimpleWidths>,
1743        Option<CidFont>,
1744        Option<Type3Font>,
1745    ) {
1746        let Some(loaded) = self.font_entry(name) else {
1747            return (None, None, None, None);
1748        };
1749        if let Some(note) = loaded.note {
1750            self.report.note(note.as_bytes());
1751        }
1752        (loaded.font, loaded.widths, loaded.cid, loaded.type3)
1753    }
1754
1755    /// Everything the walker needs from a font resource, with a note when the
1756    /// family is one this renderer cannot draw.
1757    fn font_entry(&mut self, name: &[u8]) -> Option<LoadedFont> {
1758        let resources = self.resources.clone()?;
1759        let fonts = match resolve(self.document, resources.get(b"Font")) {
1760            Ok(Object::Dictionary(fonts)) => fonts,
1761            _ => return None,
1762        };
1763        let entry = fonts.get(name)?.clone();
1764        let font_object = resolve(self.document, Some(&entry)).ok()?;
1765        let Object::Dictionary(font) = font_object else {
1766            return None;
1767        };
1768        let subtype = match font.get(b"Subtype") {
1769            Some(Object::Name(name)) => name.clone(),
1770            _ => Vec::new(),
1771        };
1772        match subtype.as_slice() {
1773            b"Type0" => return Some(self.cid_entry(&font)),
1774            b"Type3" => return Some(self.type3_entry(&font)),
1775            _ => {}
1776        }
1777        let encoding = self.encoding_for(&font);
1778        let widths = self.widths_for(&font);
1779        if let Some(descriptor) = font.get(b"FontDescriptor") {
1780            let descriptor = resolve(self.document, Some(descriptor)).ok()?;
1781            if let Object::Dictionary(descriptor) = descriptor {
1782                // A simple CFF font (`/FontFile3`, `/Subtype /Type1C`) carries no
1783                // `cmap`: its codes reach glyphs through the charset's names, so
1784                // it draws once the name map is read. Other `/FontFile3`
1785                // subtypes (OpenType-wrapped CFF is handled too) and Type 1
1786                // programs (`/FontFile`, `eexec`) are still the fallback font.
1787                if let Some(Object::Reference(id)) = descriptor.get(b"FontFile3")
1788                    && let Some(font) = self
1789                        .document
1790                        .stream_data(*id)
1791                        .ok()
1792                        .and_then(|data| Font::cff(encoding.clone(), data))
1793                    && font.has_glyph_names()
1794                {
1795                    return Some(LoadedFont {
1796                        font: Some(font),
1797                        widths,
1798                        cid: None,
1799                        type3: None,
1800                        note: None,
1801                    });
1802                }
1803                // A Type 1 program (`/FontFile`) is a PostScript program with
1804                // charstrings, which `ttf-parser` cannot read: `crate::type1` does,
1805                // and a simple font's code reaches its glyphs by the *names* the
1806                // encoding declares.
1807                if let Some(Object::Reference(id)) = descriptor.get(b"FontFile")
1808                    && let Some(font) = self
1809                        .document
1810                        .stream_data(*id)
1811                        .ok()
1812                        .and_then(|data| crate::type1::Program::parse(&data))
1813                        .and_then(|program| Font::type1(encoding.clone(), program))
1814                {
1815                    return Some(LoadedFont {
1816                        font: Some(font),
1817                        widths,
1818                        cid: None,
1819                        type3: None,
1820                        note: None,
1821                    });
1822                }
1823                for (key, kind) in [
1824                    (&b"FontFile3"[..], "font:FontFile3"),
1825                    (&b"FontFile"[..], "font:FontFile"),
1826                ] {
1827                    if descriptor.get(key).is_some() {
1828                        return Some(LoadedFont {
1829                            font: Some(Font::builtin(encoding)),
1830                            widths,
1831                            cid: None,
1832                            type3: None,
1833                            note: Some(kind),
1834                        });
1835                    }
1836                }
1837                if let Some(font_file) = descriptor.get(b"FontFile2") {
1838                    let data = match font_file {
1839                        Object::Reference(id) => self.document.stream_data(*id).ok(),
1840                        _ => None,
1841                    };
1842                    if let Some(data) = data
1843                        && let Some(font) = Font::true_type(encoding.clone(), data)
1844                    {
1845                        // A program with no `cmap` cannot be decoded from its
1846                        // codes; say so here, where the font is loaded, so the
1847                        // page reports it once rather than looking blank.
1848                        let note = if font.has_character_map() {
1849                            None
1850                        } else {
1851                            Some("font:TrueType-without-cmap")
1852                        };
1853                        return Some(LoadedFont {
1854                            font: Some(font),
1855                            widths,
1856                            cid: None,
1857                            type3: None,
1858                            note,
1859                        });
1860                    }
1861                }
1862            }
1863        }
1864        Some(LoadedFont {
1865            font: Some(Font::builtin(encoding)),
1866            widths,
1867            cid: None,
1868            type3: None,
1869            note: None,
1870        })
1871    }
1872
1873    /// A Type 0 font: a descendant CIDFontType2 with an embedded program and an
1874    /// identity CMap is drawable; anything else is reported by reason.
1875    /// A Type 3 font: a `/CharProcs` dictionary of content streams, selected by
1876    /// the glyph names its `/Encoding` declares (9.6.5).
1877    ///
1878    /// Without `/Differences` there are no names to select by, and the note says
1879    /// so rather than drawing nothing.
1880    fn type3_entry(&mut self, font: &Dictionary) -> LoadedFont {
1881        let char_procs = match resolve(self.document, font.get(b"CharProcs")) {
1882            Ok(Object::Dictionary(procs)) => procs,
1883            _ => {
1884                return LoadedFont {
1885                    note: Some("font:Type3"),
1886                    ..LoadedFont::default()
1887                };
1888            }
1889        };
1890        let Some(names) = self.type3_names(font) else {
1891            return LoadedFont {
1892                note: Some("font:Type3"),
1893                ..LoadedFont::default()
1894            };
1895        };
1896        let font_matrix = font
1897            .get(b"FontMatrix")
1898            .and_then(Object::as_array)
1899            .and_then(matrix_operand)
1900            .unwrap_or(Matrix::new(0.001, 0.0, 0.0, 0.001, 0.0, 0.0));
1901        let resources = match resolve(self.document, font.get(b"Resources")) {
1902            Ok(Object::Dictionary(resources)) => Some(resources),
1903            _ => self.resources.clone(),
1904        };
1905        let widths = self.widths_for(font);
1906        LoadedFont {
1907            type3: Some(Type3Font {
1908                char_procs,
1909                names,
1910                font_matrix,
1911                resources,
1912            }),
1913            widths,
1914            ..LoadedFont::default()
1915        }
1916    }
1917
1918    /// Code → glyph name from `/Encoding`'s `/Differences`, 256 entries.
1919    fn type3_names(&mut self, font: &Dictionary) -> Option<Vec<Option<Vec<u8>>>> {
1920        let Ok(encoding) = resolve(self.document, font.get(b"Encoding")) else {
1921            return None;
1922        };
1923        let Object::Dictionary(encoding) = encoding else {
1924            // A named base encoding alone gives no glyph names this renderer has.
1925            return None;
1926        };
1927        let Ok(Object::Array(differences)) = resolve(self.document, encoding.get(b"Differences"))
1928        else {
1929            return None;
1930        };
1931        let mut names = vec![None; 256];
1932        let mut code: Option<usize> = None;
1933        for entry in &differences {
1934            match entry {
1935                Object::Integer(value) => {
1936                    code = usize::try_from(*value).ok().filter(|value| *value < 256);
1937                }
1938                Object::Name(name) => {
1939                    if let Some(slot) = code.and_then(|at| names.get_mut(at)) {
1940                        *slot = Some(name.clone());
1941                    }
1942                    code = code.and_then(|at| at.checked_add(1)).filter(|at| *at < 256);
1943                }
1944                _ => {}
1945            }
1946        }
1947        Some(names)
1948    }
1949
1950    /// Run one Type 3 glyph's content stream in glyph space (9.6.5).
1951    ///
1952    /// The char procedure paints in glyph space, so it is placed by
1953    /// `/FontMatrix`, then the text rendering matrix — which is why the font
1954    /// matrix is the *first* factor. The glyph's own state is isolated: colour,
1955    /// width and clip a char procedure sets belong to that glyph.
1956    fn run_type3_glyph(&mut self, type3: &Type3Font, code: u8) -> crate::Result<()> {
1957        let Some(name) = type3.names.get(usize::from(code)).and_then(Option::as_ref) else {
1958            return Ok(());
1959        };
1960        // A char procedure with no glyph name in `/CharProcs` draws nothing.
1961        let Some(entry) = type3.char_procs.get(name).cloned() else {
1962            return Ok(());
1963        };
1964        let Object::Reference(id) = entry else {
1965            return Ok(());
1966        };
1967        let Ok(stream) = self.document.get_object(id) else {
1968            return Ok(());
1969        };
1970        let Object::Stream(stream) = stream else {
1971            return Ok(());
1972        };
1973        let content = match self.document.decode_stream(&stream) {
1974            Ok(content) => content,
1975            Err(_) => {
1976                self.report.note(b"Tj");
1977                return Ok(());
1978            }
1979        };
1980        if self.form_depth >= MAX_FORM_DEPTH {
1981            // `ContentStreamCycleType3insideType3.pdf` is exactly this: a glyph
1982            // whose procedure shows more text in the same font.
1983            self.report.note(b"Tj");
1984            return Ok(());
1985        }
1986        // Text rendering mode 3 paints nothing (9.3.6); modes 4–7 also *clip* to
1987        // the glyph outline, and a Type 3 glyph has no outline — it is a content
1988        // stream — so the clip is reported by name instead of silently empty.
1989        if matches!(self.state.text_mode, 4..=7) {
1990            self.report.note(b"text-clip");
1991            return Ok(());
1992        }
1993        if self.state.text_mode == 3 {
1994            return Ok(());
1995        }
1996
1997        let scale = Matrix::new(
1998            self.state.font_size * self.state.horizontal_scale,
1999            0.0,
2000            0.0,
2001            self.state.font_size,
2002            0.0,
2003            self.state.rise,
2004        );
2005        let glyph_ctm = type3
2006            .font_matrix
2007            .multiply(scale)
2008            .multiply(self.state.text_matrix)
2009            .multiply(self.state.ctm);
2010
2011        let saved_state = self.state.clone();
2012        let saved_mask = self.mask.clone();
2013        let saved_resources = self.resources.clone();
2014        let saved_path = core::mem::replace(&mut self.path, Path::new());
2015
2016        self.state.ctm = glyph_ctm;
2017        // The procedure's own text runs in *its* scope, not in this font's:
2018        // `d0`/`d1` and any `Tf` inside belong to the glyph.
2019        self.state.font = None;
2020        self.state.type3 = None;
2021        self.state.cid = None;
2022        self.state.widths = None;
2023        self.resources = type3.resources.clone();
2024        self.form_depth += 1;
2025        let result = self.run(&content);
2026        self.form_depth -= 1;
2027
2028        self.state = saved_state;
2029        self.mask = saved_mask;
2030        self.resources = saved_resources;
2031        self.path = saved_path;
2032        result
2033    }
2034
2035    fn cid_entry(&mut self, font: &Dictionary) -> LoadedFont {
2036        let identity = matches!(
2037            resolve(self.document, font.get(b"Encoding")).ok(),
2038            Some(Object::Name(name)) if name.starts_with(b"Identity")
2039        );
2040        if !identity {
2041            return LoadedFont {
2042                note: Some("font:Type0-cmap"),
2043                ..LoadedFont::default()
2044            };
2045        }
2046        let descendant = match resolve(self.document, font.get(b"DescendantFonts")).ok() {
2047            Some(Object::Array(items)) => items
2048                .first()
2049                .and_then(|item| resolve(self.document, Some(item)).ok()),
2050            _ => None,
2051        };
2052        let Some(Object::Dictionary(descendant)) = descendant else {
2053            return LoadedFont {
2054                note: Some("font:Type0-descendant"),
2055                ..LoadedFont::default()
2056            };
2057        };
2058        let subtype = match descendant.get(b"Subtype") {
2059            Some(Object::Name(name)) => name.clone(),
2060            _ => Vec::new(),
2061        };
2062        // CIDFontType2 is TrueType, CIDFontType0 is CFF; both draw once the
2063        // program is wrapped, so the only difference here is which descriptor
2064        // entry carries it.
2065        if subtype != b"CIDFontType2" && subtype != b"CIDFontType0" {
2066            return LoadedFont {
2067                note: Some("font:CIDFontType0-unknown"),
2068                ..LoadedFont::default()
2069            };
2070        }
2071        let is_cff = subtype == b"CIDFontType0";
2072        let program = descendant
2073            .get(b"FontDescriptor")
2074            .and_then(|descriptor| resolve(self.document, Some(descriptor)).ok())
2075            .and_then(|descriptor| match descriptor {
2076                Object::Dictionary(descriptor) => {
2077                    let entry: &[u8] = if is_cff { b"FontFile3" } else { b"FontFile2" };
2078                    descriptor.get(entry).and_then(|file| match file {
2079                        Object::Reference(id) => self.document.stream_data(*id).ok(),
2080                        _ => None,
2081                    })
2082                }
2083                _ => None,
2084            })
2085            .and_then(|data| {
2086                if is_cff {
2087                    // CFF arrives bare (`/CIDFontType0C`) or wrapped (`/OpenType`);
2088                    // `Font::cff` accepts both.
2089                    Font::cff(Encoding::standard(), data)
2090                } else {
2091                    Font::true_type(Encoding::standard(), data)
2092                }
2093            });
2094        let Some(program) = program else {
2095            return LoadedFont {
2096                note: Some("font:Type0-no-program"),
2097                ..LoadedFont::default()
2098            };
2099        };
2100        // Read the entry unresolved: resolving it would dereference the stream
2101        // reference and lose the id the bytes are behind.
2102        let to_gid = match descendant.get(b"CIDToGIDMap") {
2103            Some(Object::Name(name)) if name == b"Identity" => CidToGid::Identity,
2104            Some(Object::Reference(id)) => self
2105                .document
2106                .stream_data(*id)
2107                .map(|data| {
2108                    CidToGid::Table(
2109                        data.as_chunks::<2>()
2110                            .0
2111                            .iter()
2112                            .map(|pair| u16::from_be_bytes(*pair))
2113                            .collect(),
2114                    )
2115                })
2116                .unwrap_or(CidToGid::Identity),
2117            // Absent means identity.
2118            _ => CidToGid::Identity,
2119        };
2120        LoadedFont {
2121            font: None,
2122            widths: None,
2123            cid: Some(CidFont {
2124                font: program,
2125                to_gid,
2126                widths: self.cid_widths(&descendant),
2127            }),
2128            type3: None,
2129            note: None,
2130        }
2131    }
2132
2133    /// `/W` runs and `/DW` from a CID font dictionary (9.7.4.3).
2134    fn cid_widths(&self, descendant: &Dictionary) -> CidWidths {
2135        let mut ranges = vec![];
2136        if let Ok(Object::Array(items)) = resolve(self.document, descendant.get(b"W")) {
2137            let number = |item: Option<&Object>| {
2138                item.and_then(|item| resolve(self.document, Some(item)).ok())
2139                    .and_then(|item| item.as_real())
2140            };
2141            let mut index = 0;
2142            while index + 1 < items.len() {
2143                let Some(first) = number(items.get(index)) else {
2144                    break;
2145                };
2146                match items.get(index + 1) {
2147                    Some(Object::Array(list)) => {
2148                        let widths = list
2149                            .iter()
2150                            .map(Object::as_real)
2151                            .map(|w| w.unwrap_or(0.0))
2152                            .collect();
2153                        ranges.push((first as u32, widths));
2154                        index += 2;
2155                    }
2156                    second => {
2157                        let Some(last) = number(second) else { break };
2158                        let Some(width) = number(items.get(index + 2)) else {
2159                            break;
2160                        };
2161                        let count = (last - first).max(0.0) as usize + 1;
2162                        ranges.push((first as u32, vec![width; count]));
2163                        index += 3;
2164                    }
2165                }
2166            }
2167        }
2168        let default = number_of(self.document, descendant.get(b"DW")).unwrap_or(1000.0);
2169        CidWidths { ranges, default }
2170    }
2171
2172    /// `/Widths` plus the descriptor's `/MissingWidth`, when the font states
2173    /// them. A base-14 font usually does not, and then the glyph's own advance
2174    /// is the best available answer.
2175    fn widths_for(&self, font: &Dictionary) -> Option<SimpleWidths> {
2176        let first = font.get(b"FirstChar").and_then(Object::as_integer)?;
2177        let Object::Array(items) = resolve(self.document, font.get(b"Widths")).ok()? else {
2178            return None;
2179        };
2180        let widths: Vec<f64> = items
2181            .iter()
2182            .map(|item| number_of(self.document, Some(item)).unwrap_or(0.0))
2183            .collect();
2184        let missing = font
2185            .get(b"FontDescriptor")
2186            .and_then(|descriptor| resolve(self.document, Some(descriptor)).ok())
2187            .and_then(|descriptor| match descriptor {
2188                Object::Dictionary(descriptor) => {
2189                    number_of(self.document, descriptor.get(b"MissingWidth"))
2190                }
2191                _ => None,
2192            })
2193            .unwrap_or(0.0);
2194        Some(SimpleWidths {
2195            first,
2196            widths,
2197            missing,
2198        })
2199    }
2200
2201    fn encoding_for(&self, font: &Dictionary) -> Encoding {
2202        let Some(encoding_object) = font.get(b"Encoding") else {
2203            return Encoding::standard();
2204        };
2205        let Ok(encoding_object) = resolve(self.document, Some(encoding_object)) else {
2206            return Encoding::standard();
2207        };
2208        let mut encoding = Encoding::from_object(Some(&encoding_object)).unwrap_or_default();
2209        if let Object::Dictionary(dict) = &encoding_object
2210            && let Some(differences) = dict.get(b"Differences")
2211            && let Ok(Object::Array(items)) = resolve(self.document, Some(differences))
2212        {
2213            let _ = encoding.apply_differences(&items);
2214        }
2215        encoding
2216    }
2217
2218    fn apply_pending_clip(&mut self) {
2219        let Some(even_odd) = self.pending_clip.take() else {
2220            return;
2221        };
2222        let polylines = self.path.flatten(self.state.ctm);
2223        let mask = clip_mask(
2224            self.canvas.width(),
2225            self.canvas.height(),
2226            &polylines,
2227            even_odd,
2228        );
2229        self.mask.intersect(&mask);
2230    }
2231}
2232
2233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2234enum Paint {
2235    Fill,
2236    Stroke,
2237    Both,
2238}
2239
2240fn determinant_scale(ctm: Matrix) -> f64 {
2241    let determinant = ctm.a * ctm.d - ctm.b * ctm.c;
2242    determinant.abs().sqrt()
2243}
2244
2245fn number(operands: &[Object], index: usize) -> f64 {
2246    operands.get(index).and_then(Object::as_real).unwrap_or(0.0)
2247}
2248
2249fn integer(operands: &[Object], index: usize) -> i64 {
2250    operands
2251        .get(index)
2252        .and_then(Object::as_integer)
2253        .unwrap_or(0)
2254}
2255
2256fn number_of(document: &Document, object: Option<&Object>) -> Option<f64> {
2257    resolve(document, object)
2258        .ok()
2259        .and_then(|object| object.as_real())
2260}
2261
2262/// Whether an annotation's `/F` flags say a viewer hides it (12.5.3, table 165):
2263/// invisible (bit 1), hidden (bit 2) and no-view (bit 6).
2264fn annotation_is_hidden(dict: &Dictionary) -> bool {
2265    let flags = dict
2266        .get(b"F")
2267        .and_then(Object::as_integer)
2268        .unwrap_or_default();
2269    flags & 0b100011 != 0
2270}
2271
2272/// A `/BBox` (or any four-number rectangle) as a [`pdf2::Rect`].
2273fn rect_of(object: &Object) -> Option<pdf2::Rect> {
2274    let items = object.as_array()?;
2275    if items.len() < 4 {
2276        return None;
2277    }
2278    let value = |index: usize| items.get(index).and_then(|item| item.as_real());
2279    let (x0, y0, x1, y1) = (value(0)?, value(1)?, value(2)?, value(3)?);
2280    Some(pdf2::Rect::new(
2281        x0.min(x1),
2282        y0.min(y1),
2283        x0.max(x1),
2284        y0.max(y1),
2285    ))
2286}
2287
2288fn matrix_operand(operands: &[Object]) -> Option<Matrix> {
2289    if operands.len() < 6 {
2290        return None;
2291    }
2292    Some(Matrix::new(
2293        number(operands, 0),
2294        number(operands, 1),
2295        number(operands, 2),
2296        number(operands, 3),
2297        number(operands, 4),
2298        number(operands, 5),
2299    ))
2300}
2301
2302/// The `pair`th point in the operands, if all of its numbers are there.
2303///
2304/// Callers name a *point*, not a number: `c` takes three of them at slots 0, 1
2305/// and 2, which are the numbers `(0, 1)`, `(2, 3)` and `(4, 5)`. Reading the
2306/// slot as a number index silently turned every curve's last control point into
2307/// its end point, which is what a wrong index looks like on the page.
2308fn point_operand(operands: &[Object], pair: usize) -> Option<Point> {
2309    let start = pair * 2;
2310    if operands.len() < start + 2 {
2311        return None;
2312    }
2313    Some(Point::new(
2314        number(operands, start),
2315        number(operands, start + 1),
2316    ))
2317}
2318
2319fn dash_operand(operands: &[Object]) -> Dash {
2320    let pattern = match operands.first() {
2321        Some(Object::Array(items)) => items
2322            .iter()
2323            .filter_map(Object::as_real)
2324            .collect::<Vec<f64>>(),
2325        _ => Vec::new(),
2326    };
2327    let phase = number(operands, 1);
2328    Dash { pattern, phase }
2329}
2330
2331/// Skip inline image data (`BI` … `EI`), which cannot be tokenised.
2332fn skip_inline_image(parser: &mut Parser<'_>) -> crate::Result<()> {
2333    let start = parser.raw_position();
2334    let content = parser.content();
2335    let found = content
2336        .get(start..)
2337        .and_then(|rest| find_operator(rest, b"EI"))
2338        .ok_or_else(|| crate::Error::malformed("inline image without a closing EI"))?;
2339    parser.seek(start + found + 2);
2340    Ok(())
2341}
2342
2343fn find_operator(haystack: &[u8], needle: &[u8]) -> Option<usize> {
2344    let mut index = 0;
2345    while index + needle.len() <= haystack.len() {
2346        if &haystack[index..index + needle.len()] == needle {
2347            let delimiter = |byte: u8| is_whitespace(byte) || is_delimiter(byte);
2348            let before_ok = index == 0 || delimiter(haystack[index - 1]);
2349            let after = index + needle.len();
2350            let after_ok = after >= haystack.len() || delimiter(haystack[after]);
2351            if before_ok && after_ok {
2352                return Some(index);
2353            }
2354        }
2355        index += 1;
2356    }
2357    None
2358}
2359
2360#[cfg(test)]
2361mod tests {
2362    use super::{Report, dash_operand};
2363    use pdf2::Object;
2364
2365    #[test]
2366    fn reports_collect_operator_counts_in_order() {
2367        let mut report = Report::default();
2368        report.note(b"Tj");
2369        report.note(b"Tj");
2370        report.note(b"Do");
2371        assert_eq!(report.unsupported_total(), 3);
2372        assert_eq!(report.unsupported.get("Tj"), Some(&2));
2373        assert_eq!(report.to_string(), "Do×1, Tj×2");
2374    }
2375
2376    #[test]
2377    fn dash_operands_default_to_solid() {
2378        assert!(dash_operand(&[]).is_solid());
2379        let dash = dash_operand(&[
2380            Object::array([Object::Integer(4), Object::Integer(2)]),
2381            Object::Integer(1),
2382        ]);
2383        assert_eq!(dash.pattern, vec![4.0, 2.0]);
2384        assert_eq!(dash.phase, 1.0);
2385    }
2386}