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(value) = spaces.get(name).cloned() else {
1455            return Ok(());
1456        };
1457        // A `/Pattern` colour space may be an array `[/Pattern /DeviceRGB]` whose
1458        // second element is the underlying space an uncoloured pattern's colour is
1459        // given in (8.7.3.3); anything else here is a tint space `scn` converts.
1460        self.state.underlying = match &value {
1461            Object::Array(items) => items
1462                .get(1)
1463                .and_then(|item| crate::shading::parse_space(self.document, item).ok()),
1464            _ => None,
1465        };
1466        self.state.space = crate::shading::parse_space(self.document, &value).ok();
1467        Ok(())
1468    }
1469
1470    /// `scn` naming a pattern: a shading becomes the fill's paint, and a tiling
1471    /// pattern becomes a cell — with the colour `values` pours through it when it
1472    /// is uncoloured (`8.7.3.3`).
1473    fn select_pattern(&mut self, name: &[u8], values: &[f64]) -> crate::Result<()> {
1474        let Some(resources) = self.resources.clone() else {
1475            return Ok(());
1476        };
1477        let Some(entry) = resources.get(b"Pattern").cloned() else {
1478            return Ok(());
1479        };
1480        let Object::Dictionary(patterns) = resolve(self.document, Some(&entry))? else {
1481            return Ok(());
1482        };
1483        let Some(pattern) = patterns.get(name).cloned() else {
1484            return Ok(());
1485        };
1486        // A pattern object is a stream (its content paints the cell or nothing);
1487        // the type lives in its dictionary.
1488        let object = resolve(self.document, Some(&pattern))?;
1489        let dict = match &object {
1490            Object::Stream(stream) => stream.dict().clone(),
1491            Object::Dictionary(dict) => dict.clone(),
1492            _ => {
1493                self.report.note(b"pattern");
1494                return Ok(());
1495            }
1496        };
1497        match dict.get(b"PatternType").and_then(Object::as_integer) {
1498            Some(2) => {
1499                let Some(shading) = dict.get(b"Shading") else {
1500                    self.report.note(b"pattern");
1501                    return Ok(());
1502                };
1503                if let Ok(shading) = crate::shading::Shading::from_object(self.document, shading) {
1504                    self.state.pattern = Some(PatternFill::Shading(std::rc::Rc::new(shading)));
1505                } else {
1506                    self.report.note(b"pattern");
1507                }
1508            }
1509            // A tiling pattern (`8.7.3`): a coloured cell paints its own content,
1510            // an uncoloured one is a stencil poured with the colour `scn` gave —
1511            // "the entire pattern cell is painted with a separately specified
1512            // colour each time the pattern is used" (8.7.3.1).
1513            Some(1) => match &object {
1514                Object::Stream(stream) => {
1515                    match crate::pattern::Tile::from_stream(self.document, stream) {
1516                        Ok(tile) => {
1517                            let colour = match tile.paint_type {
1518                                crate::pattern::PaintType::Coloured => {
1519                                    // "For other types of patterns, these operands shall
1520                                    // not be specified" (8.6.8): extra ones are reported,
1521                                    // not silently ignored.
1522                                    if !values.is_empty() {
1523                                        self.report.note(b"scn");
1524                                    }
1525                                    None
1526                                }
1527                                crate::pattern::PaintType::Uncoloured => {
1528                                    let Some(space) = self.state.underlying.clone() else {
1529                                        // Without `[/Pattern /Device]` there is no space
1530                                        // to read the colour in.
1531                                        self.report.note(b"pattern");
1532                                        return Ok(());
1533                                    };
1534                                    Some(crate::shading::color_in(&space, values))
1535                                }
1536                            };
1537                            self.state.pattern =
1538                                Some(PatternFill::Tile(std::rc::Rc::new(tile), colour));
1539                        }
1540                        Err(_) => self.report.note(b"pattern"),
1541                    }
1542                }
1543                _ => self.report.note(b"pattern"),
1544            },
1545            _ => self.report.note(b"pattern"),
1546        }
1547        Ok(())
1548    }
1549
1550    /// `sh`: paint a `/Shading` resource (8.7.4.3).
1551    ///
1552    /// The shading is sampled per pixel inside the current clip and its own
1553    /// bounding box, with the current fill alpha and blend mode — the same
1554    /// treatment a fill gets, which is what keeps a gradient under `/ca` and
1555    /// inside a `/BM` looking like the rest of the page.
1556    fn paint_shading(&mut self, name: &[u8]) -> crate::Result<()> {
1557        let Some(resources) = self.resources.clone() else {
1558            self.report.note(b"sh");
1559            return Ok(());
1560        };
1561        let Object::Dictionary(shadings) = resolve(self.document, resources.get(b"Shading"))?
1562        else {
1563            self.report.note(b"sh");
1564            return Ok(());
1565        };
1566        let Some(entry) = shadings.get(name).cloned() else {
1567            self.report.note(b"sh");
1568            return Ok(());
1569        };
1570        let Object::Dictionary(dict) = resolve(self.document, Some(&entry))? else {
1571            self.report.note(b"sh");
1572            return Ok(());
1573        };
1574        let shading = match crate::shading::Shading::parse(self.document, &dict) {
1575            Ok(shading) => shading,
1576            Err(_) => {
1577                self.report.note(b"sh");
1578                return Ok(());
1579            }
1580        };
1581        // The shading's own space is mapped into the page by its `/Matrix` and
1582        // then the CTM; painting goes through the inverse of that product.
1583        let to_device = shading.matrix().multiply(self.state.ctm);
1584        crate::shading::paint(
1585            &shading.with_matrix(to_device),
1586            self.canvas,
1587            &self.mask,
1588            self.state.fill_alpha,
1589            self.state.blend,
1590        );
1591        Ok(())
1592    }
1593
1594    /// Draw every annotation that has an appearance stream (12.5.5).
1595    ///
1596    /// `/Rect` is the area the annotation occupies in page user space;
1597    /// `/AP /N` is the normal appearance, either a form stream or a dictionary
1598    /// of them keyed by `/AS`. Annotations flagged invisible, hidden or
1599    /// no-view are skipped, which is what a viewer does with them.
1600    fn draw_annotations(&mut self, page: &Page) -> crate::Result<()> {
1601        let Some(id) = page.id else {
1602            return Ok(());
1603        };
1604        let annotations = match self.document.get_object(id)? {
1605            Object::Dictionary(dict) => match dict.get(b"Annots") {
1606                Some(value) => resolve(self.document, Some(value))?,
1607                None => return Ok(()),
1608            },
1609            _ => return Ok(()),
1610        };
1611        let Object::Array(annotations) = annotations else {
1612            return Ok(());
1613        };
1614        for annotation in annotations {
1615            let annotation = resolve(self.document, Some(&annotation))?;
1616            let Object::Dictionary(dict) = annotation else {
1617                continue;
1618            };
1619            if annotation_is_hidden(&dict) {
1620                continue;
1621            }
1622            let Some(rect) = dict.get(b"Rect").and_then(rect_of) else {
1623                continue;
1624            };
1625            if rect.width() <= 0.0 || rect.height() <= 0.0 {
1626                continue;
1627            }
1628            let Some(appearance) = self.normal_appearance(&dict)? else {
1629                continue;
1630            };
1631            let Some(bbox) = appearance.dict().get(b"BBox").and_then(rect_of) else {
1632                continue;
1633            };
1634            let matrix = appearance
1635                .dict()
1636                .get(b"Matrix")
1637                .and_then(Object::as_array)
1638                .and_then(matrix_operand)
1639                .unwrap_or(Matrix::IDENTITY);
1640            // The appearance's box, after its own matrix, is what gets mapped
1641            // onto `/Rect`.
1642            let corners = [
1643                Point::new(bbox.x0, bbox.y0),
1644                Point::new(bbox.x1, bbox.y0),
1645                Point::new(bbox.x1, bbox.y1),
1646                Point::new(bbox.x0, bbox.y1),
1647            ]
1648            .map(|point| matrix.apply(point));
1649            let (min_x, max_x) = corners
1650                .iter()
1651                .fold((f64::MAX, f64::MIN), |(low, high), point| {
1652                    (low.min(point.x), high.max(point.x))
1653                });
1654            let (min_y, max_y) = corners
1655                .iter()
1656                .fold((f64::MAX, f64::MIN), |(low, high), point| {
1657                    (low.min(point.y), high.max(point.y))
1658                });
1659            let width = max_x - min_x;
1660            let height = max_y - min_y;
1661            if width <= 0.0 || height <= 0.0 {
1662                continue;
1663            }
1664            let scale_x = rect.width() / width;
1665            let scale_y = rect.height() / height;
1666            let place = Matrix::new(
1667                scale_x,
1668                0.0,
1669                0.0,
1670                scale_y,
1671                rect.x0 - min_x * scale_x,
1672                rect.y0 - min_y * scale_y,
1673            );
1674            self.run_form_nested(&appearance, place)?;
1675        }
1676        Ok(())
1677    }
1678
1679    /// The annotation's normal appearance: a form stream, or the `/AS` entry of
1680    /// a dictionary of them. `None` when there is nothing to draw.
1681    fn normal_appearance(&self, dict: &Dictionary) -> crate::Result<Option<pdf2::Stream>> {
1682        let Some(ap) = dict.get(b"AP") else {
1683            return Ok(None);
1684        };
1685        let Object::Dictionary(ap) = resolve(self.document, Some(ap))? else {
1686            return Ok(None);
1687        };
1688        let Some(normal) = ap.get(b"N") else {
1689            return Ok(None);
1690        };
1691        let normal = resolve(self.document, Some(normal))?;
1692        match normal {
1693            Object::Stream(stream) => Ok(Some(stream)),
1694            Object::Dictionary(states) => {
1695                // `/AS` names the state a viewer shows; without it the first
1696                // entry is the only thing to go on.
1697                let state = dict
1698                    .get(b"AS")
1699                    .and_then(Object::as_name)
1700                    .and_then(|name| states.get(name))
1701                    .cloned()
1702                    .or_else(|| states.iter().next().map(|(_, value)| value.clone()));
1703                match state {
1704                    Some(value) => match resolve(self.document, Some(&value))? {
1705                        Object::Stream(stream) => Ok(Some(stream)),
1706                        _ => Ok(None),
1707                    },
1708                    None => Ok(None),
1709                }
1710            }
1711            _ => Ok(None),
1712        }
1713    }
1714
1715    #[allow(clippy::type_complexity)]
1716    fn load_font(
1717        &mut self,
1718        name: &[u8],
1719    ) -> (
1720        Option<Font>,
1721        Option<SimpleWidths>,
1722        Option<CidFont>,
1723        Option<Type3Font>,
1724    ) {
1725        let Some(loaded) = self.font_entry(name) else {
1726            return (None, None, None, None);
1727        };
1728        if let Some(note) = loaded.note {
1729            self.report.note(note.as_bytes());
1730        }
1731        (loaded.font, loaded.widths, loaded.cid, loaded.type3)
1732    }
1733
1734    /// Everything the walker needs from a font resource, with a note when the
1735    /// family is one this renderer cannot draw.
1736    fn font_entry(&mut self, name: &[u8]) -> Option<LoadedFont> {
1737        let resources = self.resources.clone()?;
1738        let fonts = match resolve(self.document, resources.get(b"Font")) {
1739            Ok(Object::Dictionary(fonts)) => fonts,
1740            _ => return None,
1741        };
1742        let entry = fonts.get(name)?.clone();
1743        let font_object = resolve(self.document, Some(&entry)).ok()?;
1744        let Object::Dictionary(font) = font_object else {
1745            return None;
1746        };
1747        let subtype = match font.get(b"Subtype") {
1748            Some(Object::Name(name)) => name.clone(),
1749            _ => Vec::new(),
1750        };
1751        match subtype.as_slice() {
1752            b"Type0" => return Some(self.cid_entry(&font)),
1753            b"Type3" => return Some(self.type3_entry(&font)),
1754            _ => {}
1755        }
1756        let encoding = self.encoding_for(&font);
1757        let widths = self.widths_for(&font);
1758        if let Some(descriptor) = font.get(b"FontDescriptor") {
1759            let descriptor = resolve(self.document, Some(descriptor)).ok()?;
1760            if let Object::Dictionary(descriptor) = descriptor {
1761                // A simple CFF font (`/FontFile3`, `/Subtype /Type1C`) carries no
1762                // `cmap`: its codes reach glyphs through the charset's names, so
1763                // it draws once the name map is read. Other `/FontFile3`
1764                // subtypes (OpenType-wrapped CFF is handled too) and Type 1
1765                // programs (`/FontFile`, `eexec`) are still the fallback font.
1766                if let Some(Object::Reference(id)) = descriptor.get(b"FontFile3")
1767                    && let Some(font) = self
1768                        .document
1769                        .stream_data(*id)
1770                        .ok()
1771                        .and_then(|data| Font::cff(encoding.clone(), data))
1772                    && font.has_glyph_names()
1773                {
1774                    return Some(LoadedFont {
1775                        font: Some(font),
1776                        widths,
1777                        cid: None,
1778                        type3: None,
1779                        note: None,
1780                    });
1781                }
1782                // A Type 1 program (`/FontFile`) is a PostScript program with
1783                // charstrings, which `ttf-parser` cannot read: `crate::type1` does,
1784                // and a simple font's code reaches its glyphs by the *names* the
1785                // encoding declares.
1786                if let Some(Object::Reference(id)) = descriptor.get(b"FontFile")
1787                    && let Some(font) = self
1788                        .document
1789                        .stream_data(*id)
1790                        .ok()
1791                        .and_then(|data| crate::type1::Program::parse(&data))
1792                        .and_then(|program| Font::type1(encoding.clone(), program))
1793                {
1794                    return Some(LoadedFont {
1795                        font: Some(font),
1796                        widths,
1797                        cid: None,
1798                        type3: None,
1799                        note: None,
1800                    });
1801                }
1802                for (key, kind) in [
1803                    (&b"FontFile3"[..], "font:FontFile3"),
1804                    (&b"FontFile"[..], "font:FontFile"),
1805                ] {
1806                    if descriptor.get(key).is_some() {
1807                        return Some(LoadedFont {
1808                            font: Some(Font::builtin(encoding)),
1809                            widths,
1810                            cid: None,
1811                            type3: None,
1812                            note: Some(kind),
1813                        });
1814                    }
1815                }
1816                if let Some(font_file) = descriptor.get(b"FontFile2") {
1817                    let data = match font_file {
1818                        Object::Reference(id) => self.document.stream_data(*id).ok(),
1819                        _ => None,
1820                    };
1821                    if let Some(data) = data
1822                        && let Some(font) = Font::true_type(encoding.clone(), data)
1823                    {
1824                        // A program with no `cmap` cannot be decoded from its
1825                        // codes; say so here, where the font is loaded, so the
1826                        // page reports it once rather than looking blank.
1827                        let note = if font.has_character_map() {
1828                            None
1829                        } else {
1830                            Some("font:TrueType-without-cmap")
1831                        };
1832                        return Some(LoadedFont {
1833                            font: Some(font),
1834                            widths,
1835                            cid: None,
1836                            type3: None,
1837                            note,
1838                        });
1839                    }
1840                }
1841            }
1842        }
1843        Some(LoadedFont {
1844            font: Some(Font::builtin(encoding)),
1845            widths,
1846            cid: None,
1847            type3: None,
1848            note: None,
1849        })
1850    }
1851
1852    /// A Type 0 font: a descendant CIDFontType2 with an embedded program and an
1853    /// identity CMap is drawable; anything else is reported by reason.
1854    /// A Type 3 font: a `/CharProcs` dictionary of content streams, selected by
1855    /// the glyph names its `/Encoding` declares (9.6.5).
1856    ///
1857    /// Without `/Differences` there are no names to select by, and the note says
1858    /// so rather than drawing nothing.
1859    fn type3_entry(&mut self, font: &Dictionary) -> LoadedFont {
1860        let char_procs = match resolve(self.document, font.get(b"CharProcs")) {
1861            Ok(Object::Dictionary(procs)) => procs,
1862            _ => {
1863                return LoadedFont {
1864                    note: Some("font:Type3"),
1865                    ..LoadedFont::default()
1866                };
1867            }
1868        };
1869        let Some(names) = self.type3_names(font) else {
1870            return LoadedFont {
1871                note: Some("font:Type3"),
1872                ..LoadedFont::default()
1873            };
1874        };
1875        let font_matrix = font
1876            .get(b"FontMatrix")
1877            .and_then(Object::as_array)
1878            .and_then(matrix_operand)
1879            .unwrap_or(Matrix::new(0.001, 0.0, 0.0, 0.001, 0.0, 0.0));
1880        let resources = match resolve(self.document, font.get(b"Resources")) {
1881            Ok(Object::Dictionary(resources)) => Some(resources),
1882            _ => self.resources.clone(),
1883        };
1884        let widths = self.widths_for(font);
1885        LoadedFont {
1886            type3: Some(Type3Font {
1887                char_procs,
1888                names,
1889                font_matrix,
1890                resources,
1891            }),
1892            widths,
1893            ..LoadedFont::default()
1894        }
1895    }
1896
1897    /// Code → glyph name from `/Encoding`'s `/Differences`, 256 entries.
1898    fn type3_names(&mut self, font: &Dictionary) -> Option<Vec<Option<Vec<u8>>>> {
1899        let Ok(encoding) = resolve(self.document, font.get(b"Encoding")) else {
1900            return None;
1901        };
1902        let Object::Dictionary(encoding) = encoding else {
1903            // A named base encoding alone gives no glyph names this renderer has.
1904            return None;
1905        };
1906        let Ok(Object::Array(differences)) = resolve(self.document, encoding.get(b"Differences"))
1907        else {
1908            return None;
1909        };
1910        let mut names = vec![None; 256];
1911        let mut code: Option<usize> = None;
1912        for entry in &differences {
1913            match entry {
1914                Object::Integer(value) => {
1915                    code = usize::try_from(*value).ok().filter(|value| *value < 256);
1916                }
1917                Object::Name(name) => {
1918                    if let Some(slot) = code.and_then(|at| names.get_mut(at)) {
1919                        *slot = Some(name.clone());
1920                    }
1921                    code = code.and_then(|at| at.checked_add(1)).filter(|at| *at < 256);
1922                }
1923                _ => {}
1924            }
1925        }
1926        Some(names)
1927    }
1928
1929    /// Run one Type 3 glyph's content stream in glyph space (9.6.5).
1930    ///
1931    /// The char procedure paints in glyph space, so it is placed by
1932    /// `/FontMatrix`, then the text rendering matrix — which is why the font
1933    /// matrix is the *first* factor. The glyph's own state is isolated: colour,
1934    /// width and clip a char procedure sets belong to that glyph.
1935    fn run_type3_glyph(&mut self, type3: &Type3Font, code: u8) -> crate::Result<()> {
1936        let Some(name) = type3.names.get(usize::from(code)).and_then(Option::as_ref) else {
1937            return Ok(());
1938        };
1939        // A char procedure with no glyph name in `/CharProcs` draws nothing.
1940        let Some(entry) = type3.char_procs.get(name).cloned() else {
1941            return Ok(());
1942        };
1943        let Object::Reference(id) = entry else {
1944            return Ok(());
1945        };
1946        let Ok(stream) = self.document.get_object(id) else {
1947            return Ok(());
1948        };
1949        let Object::Stream(stream) = stream else {
1950            return Ok(());
1951        };
1952        let content = match self.document.decode_stream(&stream) {
1953            Ok(content) => content,
1954            Err(_) => {
1955                self.report.note(b"Tj");
1956                return Ok(());
1957            }
1958        };
1959        if self.form_depth >= MAX_FORM_DEPTH {
1960            // `ContentStreamCycleType3insideType3.pdf` is exactly this: a glyph
1961            // whose procedure shows more text in the same font.
1962            self.report.note(b"Tj");
1963            return Ok(());
1964        }
1965        // Text rendering mode 3 paints nothing (9.3.6); modes 4–7 also *clip* to
1966        // the glyph outline, and a Type 3 glyph has no outline — it is a content
1967        // stream — so the clip is reported by name instead of silently empty.
1968        if matches!(self.state.text_mode, 4..=7) {
1969            self.report.note(b"text-clip");
1970            return Ok(());
1971        }
1972        if self.state.text_mode == 3 {
1973            return Ok(());
1974        }
1975
1976        let scale = Matrix::new(
1977            self.state.font_size * self.state.horizontal_scale,
1978            0.0,
1979            0.0,
1980            self.state.font_size,
1981            0.0,
1982            self.state.rise,
1983        );
1984        let glyph_ctm = type3
1985            .font_matrix
1986            .multiply(scale)
1987            .multiply(self.state.text_matrix)
1988            .multiply(self.state.ctm);
1989
1990        let saved_state = self.state.clone();
1991        let saved_mask = self.mask.clone();
1992        let saved_resources = self.resources.clone();
1993        let saved_path = core::mem::replace(&mut self.path, Path::new());
1994
1995        self.state.ctm = glyph_ctm;
1996        // The procedure's own text runs in *its* scope, not in this font's:
1997        // `d0`/`d1` and any `Tf` inside belong to the glyph.
1998        self.state.font = None;
1999        self.state.type3 = None;
2000        self.state.cid = None;
2001        self.state.widths = None;
2002        self.resources = type3.resources.clone();
2003        self.form_depth += 1;
2004        let result = self.run(&content);
2005        self.form_depth -= 1;
2006
2007        self.state = saved_state;
2008        self.mask = saved_mask;
2009        self.resources = saved_resources;
2010        self.path = saved_path;
2011        result
2012    }
2013
2014    fn cid_entry(&mut self, font: &Dictionary) -> LoadedFont {
2015        let identity = matches!(
2016            resolve(self.document, font.get(b"Encoding")).ok(),
2017            Some(Object::Name(name)) if name.starts_with(b"Identity")
2018        );
2019        if !identity {
2020            return LoadedFont {
2021                note: Some("font:Type0-cmap"),
2022                ..LoadedFont::default()
2023            };
2024        }
2025        let descendant = match resolve(self.document, font.get(b"DescendantFonts")).ok() {
2026            Some(Object::Array(items)) => items
2027                .first()
2028                .and_then(|item| resolve(self.document, Some(item)).ok()),
2029            _ => None,
2030        };
2031        let Some(Object::Dictionary(descendant)) = descendant else {
2032            return LoadedFont {
2033                note: Some("font:Type0-descendant"),
2034                ..LoadedFont::default()
2035            };
2036        };
2037        let subtype = match descendant.get(b"Subtype") {
2038            Some(Object::Name(name)) => name.clone(),
2039            _ => Vec::new(),
2040        };
2041        // CIDFontType2 is TrueType, CIDFontType0 is CFF; both draw once the
2042        // program is wrapped, so the only difference here is which descriptor
2043        // entry carries it.
2044        if subtype != b"CIDFontType2" && subtype != b"CIDFontType0" {
2045            return LoadedFont {
2046                note: Some("font:CIDFontType0-unknown"),
2047                ..LoadedFont::default()
2048            };
2049        }
2050        let is_cff = subtype == b"CIDFontType0";
2051        let program = descendant
2052            .get(b"FontDescriptor")
2053            .and_then(|descriptor| resolve(self.document, Some(descriptor)).ok())
2054            .and_then(|descriptor| match descriptor {
2055                Object::Dictionary(descriptor) => {
2056                    let entry: &[u8] = if is_cff { b"FontFile3" } else { b"FontFile2" };
2057                    descriptor.get(entry).and_then(|file| match file {
2058                        Object::Reference(id) => self.document.stream_data(*id).ok(),
2059                        _ => None,
2060                    })
2061                }
2062                _ => None,
2063            })
2064            .and_then(|data| {
2065                if is_cff {
2066                    // CFF arrives bare (`/CIDFontType0C`) or wrapped (`/OpenType`);
2067                    // `Font::cff` accepts both.
2068                    Font::cff(Encoding::standard(), data)
2069                } else {
2070                    Font::true_type(Encoding::standard(), data)
2071                }
2072            });
2073        let Some(program) = program else {
2074            return LoadedFont {
2075                note: Some("font:Type0-no-program"),
2076                ..LoadedFont::default()
2077            };
2078        };
2079        // Read the entry unresolved: resolving it would dereference the stream
2080        // reference and lose the id the bytes are behind.
2081        let to_gid = match descendant.get(b"CIDToGIDMap") {
2082            Some(Object::Name(name)) if name == b"Identity" => CidToGid::Identity,
2083            Some(Object::Reference(id)) => self
2084                .document
2085                .stream_data(*id)
2086                .map(|data| {
2087                    CidToGid::Table(
2088                        data.as_chunks::<2>()
2089                            .0
2090                            .iter()
2091                            .map(|pair| u16::from_be_bytes(*pair))
2092                            .collect(),
2093                    )
2094                })
2095                .unwrap_or(CidToGid::Identity),
2096            // Absent means identity.
2097            _ => CidToGid::Identity,
2098        };
2099        LoadedFont {
2100            font: None,
2101            widths: None,
2102            cid: Some(CidFont {
2103                font: program,
2104                to_gid,
2105                widths: self.cid_widths(&descendant),
2106            }),
2107            type3: None,
2108            note: None,
2109        }
2110    }
2111
2112    /// `/W` runs and `/DW` from a CID font dictionary (9.7.4.3).
2113    fn cid_widths(&self, descendant: &Dictionary) -> CidWidths {
2114        let mut ranges = vec![];
2115        if let Ok(Object::Array(items)) = resolve(self.document, descendant.get(b"W")) {
2116            let number = |item: Option<&Object>| {
2117                item.and_then(|item| resolve(self.document, Some(item)).ok())
2118                    .and_then(|item| item.as_real())
2119            };
2120            let mut index = 0;
2121            while index + 1 < items.len() {
2122                let Some(first) = number(items.get(index)) else {
2123                    break;
2124                };
2125                match items.get(index + 1) {
2126                    Some(Object::Array(list)) => {
2127                        let widths = list
2128                            .iter()
2129                            .map(Object::as_real)
2130                            .map(|w| w.unwrap_or(0.0))
2131                            .collect();
2132                        ranges.push((first as u32, widths));
2133                        index += 2;
2134                    }
2135                    second => {
2136                        let Some(last) = number(second) else { break };
2137                        let Some(width) = number(items.get(index + 2)) else {
2138                            break;
2139                        };
2140                        let count = (last - first).max(0.0) as usize + 1;
2141                        ranges.push((first as u32, vec![width; count]));
2142                        index += 3;
2143                    }
2144                }
2145            }
2146        }
2147        let default = number_of(self.document, descendant.get(b"DW")).unwrap_or(1000.0);
2148        CidWidths { ranges, default }
2149    }
2150
2151    /// `/Widths` plus the descriptor's `/MissingWidth`, when the font states
2152    /// them. A base-14 font usually does not, and then the glyph's own advance
2153    /// is the best available answer.
2154    fn widths_for(&self, font: &Dictionary) -> Option<SimpleWidths> {
2155        let first = font.get(b"FirstChar").and_then(Object::as_integer)?;
2156        let Object::Array(items) = resolve(self.document, font.get(b"Widths")).ok()? else {
2157            return None;
2158        };
2159        let widths: Vec<f64> = items
2160            .iter()
2161            .map(|item| number_of(self.document, Some(item)).unwrap_or(0.0))
2162            .collect();
2163        let missing = font
2164            .get(b"FontDescriptor")
2165            .and_then(|descriptor| resolve(self.document, Some(descriptor)).ok())
2166            .and_then(|descriptor| match descriptor {
2167                Object::Dictionary(descriptor) => {
2168                    number_of(self.document, descriptor.get(b"MissingWidth"))
2169                }
2170                _ => None,
2171            })
2172            .unwrap_or(0.0);
2173        Some(SimpleWidths {
2174            first,
2175            widths,
2176            missing,
2177        })
2178    }
2179
2180    fn encoding_for(&self, font: &Dictionary) -> Encoding {
2181        let Some(encoding_object) = font.get(b"Encoding") else {
2182            return Encoding::standard();
2183        };
2184        let Ok(encoding_object) = resolve(self.document, Some(encoding_object)) else {
2185            return Encoding::standard();
2186        };
2187        let mut encoding = Encoding::from_object(Some(&encoding_object)).unwrap_or_default();
2188        if let Object::Dictionary(dict) = &encoding_object
2189            && let Some(differences) = dict.get(b"Differences")
2190            && let Ok(Object::Array(items)) = resolve(self.document, Some(differences))
2191        {
2192            let _ = encoding.apply_differences(&items);
2193        }
2194        encoding
2195    }
2196
2197    fn apply_pending_clip(&mut self) {
2198        let Some(even_odd) = self.pending_clip.take() else {
2199            return;
2200        };
2201        let polylines = self.path.flatten(self.state.ctm);
2202        let mask = clip_mask(
2203            self.canvas.width(),
2204            self.canvas.height(),
2205            &polylines,
2206            even_odd,
2207        );
2208        self.mask.intersect(&mask);
2209    }
2210}
2211
2212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2213enum Paint {
2214    Fill,
2215    Stroke,
2216    Both,
2217}
2218
2219fn determinant_scale(ctm: Matrix) -> f64 {
2220    let determinant = ctm.a * ctm.d - ctm.b * ctm.c;
2221    determinant.abs().sqrt()
2222}
2223
2224fn number(operands: &[Object], index: usize) -> f64 {
2225    operands.get(index).and_then(Object::as_real).unwrap_or(0.0)
2226}
2227
2228fn integer(operands: &[Object], index: usize) -> i64 {
2229    operands
2230        .get(index)
2231        .and_then(Object::as_integer)
2232        .unwrap_or(0)
2233}
2234
2235fn number_of(document: &Document, object: Option<&Object>) -> Option<f64> {
2236    resolve(document, object)
2237        .ok()
2238        .and_then(|object| object.as_real())
2239}
2240
2241/// Whether an annotation's `/F` flags say a viewer hides it (12.5.3, table 165):
2242/// invisible (bit 1), hidden (bit 2) and no-view (bit 6).
2243fn annotation_is_hidden(dict: &Dictionary) -> bool {
2244    let flags = dict
2245        .get(b"F")
2246        .and_then(Object::as_integer)
2247        .unwrap_or_default();
2248    flags & 0b100011 != 0
2249}
2250
2251/// A `/BBox` (or any four-number rectangle) as a [`pdf2::Rect`].
2252fn rect_of(object: &Object) -> Option<pdf2::Rect> {
2253    let items = object.as_array()?;
2254    if items.len() < 4 {
2255        return None;
2256    }
2257    let value = |index: usize| items.get(index).and_then(|item| item.as_real());
2258    let (x0, y0, x1, y1) = (value(0)?, value(1)?, value(2)?, value(3)?);
2259    Some(pdf2::Rect::new(
2260        x0.min(x1),
2261        y0.min(y1),
2262        x0.max(x1),
2263        y0.max(y1),
2264    ))
2265}
2266
2267fn matrix_operand(operands: &[Object]) -> Option<Matrix> {
2268    if operands.len() < 6 {
2269        return None;
2270    }
2271    Some(Matrix::new(
2272        number(operands, 0),
2273        number(operands, 1),
2274        number(operands, 2),
2275        number(operands, 3),
2276        number(operands, 4),
2277        number(operands, 5),
2278    ))
2279}
2280
2281/// The `pair`th point in the operands, if all of its numbers are there.
2282///
2283/// Callers name a *point*, not a number: `c` takes three of them at slots 0, 1
2284/// and 2, which are the numbers `(0, 1)`, `(2, 3)` and `(4, 5)`. Reading the
2285/// slot as a number index silently turned every curve's last control point into
2286/// its end point, which is what a wrong index looks like on the page.
2287fn point_operand(operands: &[Object], pair: usize) -> Option<Point> {
2288    let start = pair * 2;
2289    if operands.len() < start + 2 {
2290        return None;
2291    }
2292    Some(Point::new(
2293        number(operands, start),
2294        number(operands, start + 1),
2295    ))
2296}
2297
2298fn dash_operand(operands: &[Object]) -> Dash {
2299    let pattern = match operands.first() {
2300        Some(Object::Array(items)) => items
2301            .iter()
2302            .filter_map(Object::as_real)
2303            .collect::<Vec<f64>>(),
2304        _ => Vec::new(),
2305    };
2306    let phase = number(operands, 1);
2307    Dash { pattern, phase }
2308}
2309
2310/// Skip inline image data (`BI` … `EI`), which cannot be tokenised.
2311fn skip_inline_image(parser: &mut Parser<'_>) -> crate::Result<()> {
2312    let start = parser.raw_position();
2313    let content = parser.content();
2314    let found = content
2315        .get(start..)
2316        .and_then(|rest| find_operator(rest, b"EI"))
2317        .ok_or_else(|| crate::Error::malformed("inline image without a closing EI"))?;
2318    parser.seek(start + found + 2);
2319    Ok(())
2320}
2321
2322fn find_operator(haystack: &[u8], needle: &[u8]) -> Option<usize> {
2323    let mut index = 0;
2324    while index + needle.len() <= haystack.len() {
2325        if &haystack[index..index + needle.len()] == needle {
2326            let delimiter = |byte: u8| is_whitespace(byte) || is_delimiter(byte);
2327            let before_ok = index == 0 || delimiter(haystack[index - 1]);
2328            let after = index + needle.len();
2329            let after_ok = after >= haystack.len() || delimiter(haystack[after]);
2330            if before_ok && after_ok {
2331                return Some(index);
2332            }
2333        }
2334        index += 1;
2335    }
2336    None
2337}
2338
2339#[cfg(test)]
2340mod tests {
2341    use super::{Report, dash_operand};
2342    use pdf2::Object;
2343
2344    #[test]
2345    fn reports_collect_operator_counts_in_order() {
2346        let mut report = Report::default();
2347        report.note(b"Tj");
2348        report.note(b"Tj");
2349        report.note(b"Do");
2350        assert_eq!(report.unsupported_total(), 3);
2351        assert_eq!(report.unsupported.get("Tj"), Some(&2));
2352        assert_eq!(report.to_string(), "Do×1, Tj×2");
2353    }
2354
2355    #[test]
2356    fn dash_operands_default_to_solid() {
2357        assert!(dash_operand(&[]).is_solid());
2358        let dash = dash_operand(&[
2359            Object::array([Object::Integer(4), Object::Integer(2)]),
2360            Object::Integer(1),
2361        ]);
2362        assert_eq!(dash.pattern, vec![4.0, 2.0]);
2363        assert_eq!(dash.phase, 1.0);
2364    }
2365}