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