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::{Canvas, ClipMask, Color};
16use crate::font::Font;
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/// What a page render should look like.
23#[derive(Debug, Clone, PartialEq)]
24pub struct RenderOptions {
25    /// Device pixels per PDF point: `1.0` is 72 dpi.
26    pub scale: f64,
27    /// Canvas background.
28    pub background: Color,
29}
30
31impl Default for RenderOptions {
32    fn default() -> Self {
33        Self {
34            scale: 1.0,
35            background: Color::WHITE,
36        }
37    }
38}
39
40/// What happened while rendering, beyond the pixels.
41#[derive(Debug, Clone, Default, PartialEq)]
42pub struct Report {
43    /// Operators that were recognised but not drawn, with how often each
44    /// appeared. Text and image operators land here until they are implemented.
45    pub unsupported: BTreeMap<String, usize>,
46}
47
48impl Report {
49    /// Total unsupported operators.
50    pub fn unsupported_total(&self) -> usize {
51        self.unsupported.values().sum()
52    }
53
54    fn note(&mut self, operator: &[u8]) {
55        let name = String::from_utf8_lossy(operator).into_owned();
56        *self.unsupported.entry(name).or_insert(0) += 1;
57    }
58}
59
60impl fmt::Display for Report {
61    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
62        if self.unsupported.is_empty() {
63            return write!(formatter, "all operators supported");
64        }
65        let mut first = true;
66        for (name, count) in &self.unsupported {
67            if !first {
68                write!(formatter, ", ")?;
69            }
70            first = false;
71            write!(formatter, "{name}×{count}")?;
72        }
73        Ok(())
74    }
75}
76
77/// A rendered page.
78#[derive(Debug, Clone)]
79pub struct RenderedPage {
80    /// The raster.
81    pub canvas: Canvas,
82    /// What was skipped.
83    pub report: Report,
84}
85
86/// A document, page number (zero based) and rasterisation scale in one call.
87pub fn render_page_number(
88    document: &Document,
89    page_index: usize,
90    options: &RenderOptions,
91) -> crate::Result<RenderedPage> {
92    let page = document.page(page_index)?;
93    render_page(document, &page, options)
94}
95
96/// `/Widths` of a simple font, in 1/1000 em, with the descriptor's
97/// `/MissingWidth` for codes the array does not cover (9.2.4).
98#[derive(Debug, Clone, Default, PartialEq)]
99struct SimpleWidths {
100    first: i64,
101    widths: Vec<f64>,
102    missing: f64,
103}
104
105impl SimpleWidths {
106    fn advance(&self, code: u8) -> f64 {
107        let code = i64::from(code);
108        let index = code - self.first;
109        if index >= 0 {
110            #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
111            if let Some(width) = self.widths.get(index as usize) {
112                return width / 1000.0;
113            }
114        }
115        self.missing / 1000.0
116    }
117}
118
119/// Rasterise one page.
120pub fn render_page(
121    document: &Document,
122    page: &Page,
123    options: &RenderOptions,
124) -> crate::Result<RenderedPage> {
125    let scale = if options.scale.is_finite() && options.scale > 0.0 {
126        options.scale
127    } else {
128        1.0
129    };
130    let media = page
131        .media_box
132        .unwrap_or(pdf2::Rect::new(0.0, 0.0, 612.0, 792.0));
133    // `/Rotate` turns the page clockwise for display, so a quarter turn swaps
134    // the canvas dimensions.
135    let rotate = page.rotate.rem_euclid(360);
136    let landscape = rotate == 90 || rotate == 270;
137    let (width_points, height_points) = if landscape {
138        (media.height(), media.width())
139    } else {
140        (media.width(), media.height())
141    };
142    let width = ((width_points * scale).round().max(1.0)) as u32;
143    let height = ((height_points * scale).round().max(1.0)) as u32;
144    let mut canvas = Canvas::new(width, height, options.background);
145    let mut report = Report::default();
146
147    // PDF user space to device space. Every case shifts the media box origin to
148    // (0, 0); the y axis grows downwards in the raster, and `/Rotate` composes
149    // a clockwise quarter turn (or two) on top of that flip.
150    let base = match rotate {
151        90 => Matrix::new(0.0, scale, scale, 0.0, -media.y0 * scale, -media.x0 * scale),
152        180 => Matrix::new(-scale, 0.0, 0.0, scale, media.x1 * scale, -media.y0 * scale),
153        270 => Matrix::new(0.0, scale, -scale, 0.0, media.y1 * scale, -media.x0 * scale),
154        _ => Matrix::new(scale, 0.0, 0.0, -scale, -media.x0 * scale, media.y1 * scale),
155    };
156
157    let content = document.page_content(page)?;
158    let mut walker = Walker {
159        canvas: &mut canvas,
160        report: &mut report,
161        document,
162        resources: page.resources.clone(),
163        state: State::new(base),
164        stack: Vec::new(),
165        path: Path::new(),
166        pending_clip: None,
167        mask: ClipMask::all(width, height),
168    };
169    walker.run(&content)?;
170    Ok(RenderedPage { canvas, report })
171}
172
173/// The part of the graphics state that painting depends on.
174#[derive(Debug, Clone)]
175struct State {
176    ctm: Matrix,
177    line_width: f64,
178    cap: Cap,
179    join: Join,
180    dash: Dash,
181    fill: Color,
182    stroke: Color,
183    font: Option<Font>,
184    font_size: f64,
185    miter_limit: f64,
186    widths: Option<SimpleWidths>,
187    char_spacing: f64,
188    word_spacing: f64,
189    horizontal_scale: f64,
190    leading: f64,
191    rise: f64,
192    text_matrix: Matrix,
193    line_matrix: Matrix,
194}
195
196impl State {
197    fn new(ctm: Matrix) -> Self {
198        Self {
199            ctm,
200            line_width: 1.0,
201            cap: Cap::Butt,
202            join: Join::Miter,
203            dash: Dash::solid(),
204            fill: Color::BLACK,
205            stroke: Color::BLACK,
206            font: None,
207            font_size: 0.0,
208            miter_limit: 10.0,
209            widths: None,
210            char_spacing: 0.0,
211            word_spacing: 0.0,
212            horizontal_scale: 1.0,
213            leading: 0.0,
214            rise: 0.0,
215            text_matrix: Matrix::IDENTITY,
216            line_matrix: Matrix::IDENTITY,
217        }
218    }
219}
220
221struct Walker<'a> {
222    canvas: &'a mut Canvas,
223    report: &'a mut Report,
224    document: &'a Document,
225    resources: Option<Dictionary>,
226    state: State,
227    stack: Vec<(State, ClipMask)>,
228    path: Path,
229    pending_clip: Option<bool>,
230    mask: ClipMask,
231}
232
233impl Walker<'_> {
234    fn run(&mut self, content: &[u8]) -> crate::Result<()> {
235        let mut parser = Parser::new(content);
236        let mut operands: Vec<Object> = Vec::new();
237        loop {
238            match parser.peek_token()? {
239                Token::Eof => break,
240                Token::Keyword(_) => {
241                    let operator = match parser.next_token()? {
242                        Token::Keyword(operator) => operator,
243                        _ => return Err(crate::Error::malformed("content-stream operator")),
244                    };
245                    self.execute(&operator, &mut operands, &mut parser)?;
246                    operands.clear();
247                }
248                _ => {
249                    operands.push(parser.parse_object()?);
250                }
251            }
252        }
253        Ok(())
254    }
255
256    fn execute(
257        &mut self,
258        operator: &[u8],
259        operands: &mut [Object],
260        parser: &mut Parser<'_>,
261    ) -> crate::Result<()> {
262        match operator {
263            b"q" => {
264                self.stack.push((self.state.clone(), self.mask.clone()));
265            }
266            b"Q" => {
267                if let Some((state, mask)) = self.stack.pop() {
268                    self.state = state;
269                    self.mask = mask;
270                }
271            }
272            b"cm" => {
273                if let Some(matrix) = matrix_operand(operands) {
274                    self.state.ctm = matrix.multiply(self.state.ctm);
275                }
276            }
277            b"w" => self.state.line_width = number(operands, 0),
278            b"J" => {
279                self.state.cap = match integer(operands, 0) {
280                    1 => Cap::Round,
281                    2 => Cap::Square,
282                    _ => Cap::Butt,
283                }
284            }
285            b"j" => {
286                self.state.join = match integer(operands, 0) {
287                    1 => Join::Round,
288                    2 => Join::Bevel,
289                    _ => Join::Miter,
290                }
291            }
292            b"M" => self.state.miter_limit = number(operands, 0).max(1.0),
293            b"d" => self.state.dash = dash_operand(operands),
294            b"m" => {
295                if let Some(point) = point_operand(operands, 0) {
296                    self.path.move_to(point);
297                }
298            }
299            b"l" => {
300                if let Some(point) = point_operand(operands, 0) {
301                    self.path.line_to(point);
302                }
303            }
304            b"c" => {
305                if let (Some(c1), Some(c2), Some(to)) = (
306                    point_operand(operands, 0),
307                    point_operand(operands, 1),
308                    point_operand(operands, 2),
309                ) {
310                    self.path.curve_to(c1, c2, to);
311                }
312            }
313            b"v" | b"y" => {
314                // `v` and `y` are shorthand curves; draw them as a straight
315                // line to the end point, which keeps the path closed.
316                if let Some(to) = point_operand(operands, 1) {
317                    self.path.line_to(to);
318                }
319            }
320            b"h" => self.path.close(),
321            b"re" => {
322                let x = number(operands, 0);
323                let y = number(operands, 1);
324                let width = number(operands, 2);
325                let height = number(operands, 3);
326                self.path.add_rect(x, y, width, height);
327            }
328            b"S" => self.paint(Paint::Stroke, false)?,
329            b"s" => {
330                self.path.close();
331                self.paint(Paint::Stroke, false)?;
332            }
333            b"f" | b"F" => self.paint(Paint::Fill, false)?,
334            b"f*" => self.paint(Paint::Fill, true)?,
335            b"B" => self.paint(Paint::Both, false)?,
336            b"B*" => self.paint(Paint::Both, true)?,
337            b"b" => {
338                self.path.close();
339                self.paint(Paint::Both, false)?;
340            }
341            b"b*" => {
342                self.path.close();
343                self.paint(Paint::Both, true)?;
344            }
345            b"W" => self.pending_clip = Some(false),
346            b"W*" => self.pending_clip = Some(true),
347            b"n" => {
348                self.apply_pending_clip();
349                self.path = Path::new();
350            }
351            b"g" => {
352                self.state.fill = Color::rgb(
353                    number(operands, 0),
354                    number(operands, 0),
355                    number(operands, 0),
356                )
357            }
358            b"G" => {
359                self.state.stroke = Color::rgb(
360                    number(operands, 0),
361                    number(operands, 0),
362                    number(operands, 0),
363                )
364            }
365            b"rg" => {
366                self.state.fill = Color::rgb(
367                    number(operands, 0),
368                    number(operands, 1),
369                    number(operands, 2),
370                );
371            }
372            b"RG" => {
373                self.state.stroke = Color::rgb(
374                    number(operands, 0),
375                    number(operands, 1),
376                    number(operands, 2),
377                );
378            }
379            b"k" => {
380                self.state.fill = Color::from_cmyk(
381                    number(operands, 0),
382                    number(operands, 1),
383                    number(operands, 2),
384                    number(operands, 3),
385                );
386            }
387            b"K" => {
388                self.state.stroke = Color::from_cmyk(
389                    number(operands, 0),
390                    number(operands, 1),
391                    number(operands, 2),
392                    number(operands, 3),
393                );
394            }
395            b"BT" => {
396                self.state.text_matrix = Matrix::IDENTITY;
397                self.state.line_matrix = Matrix::IDENTITY;
398            }
399            b"ET" => {}
400            b"Tf" => {
401                let name = match operands.first() {
402                    Some(Object::Name(name)) => name.clone(),
403                    _ => return Err(crate::Error::malformed("/Tf needs a font name")),
404                };
405                self.state.font_size = number(operands, 1);
406                let (font, widths) = self.load_font(&name);
407                self.state.font = font;
408                self.state.widths = widths;
409            }
410            b"Td" | b"TD" => {
411                let tx = number(operands, 0);
412                let ty = number(operands, 1);
413                self.state.line_matrix =
414                    Matrix::new(1.0, 0.0, 0.0, 1.0, tx, ty).multiply(self.state.line_matrix);
415                self.state.text_matrix = self.state.line_matrix;
416                if operator == b"TD" {
417                    self.state.leading = -ty;
418                }
419            }
420            b"T*" => {
421                self.state.line_matrix = Matrix::new(1.0, 0.0, 0.0, 1.0, 0.0, -self.state.leading)
422                    .multiply(self.state.line_matrix);
423                self.state.text_matrix = self.state.line_matrix;
424            }
425            b"Tm" => {
426                if let Some(matrix) = matrix_operand(operands) {
427                    self.state.line_matrix = matrix;
428                    self.state.text_matrix = matrix;
429                }
430            }
431            b"TL" => self.state.leading = number(operands, 0),
432            b"Tc" => self.state.char_spacing = number(operands, 0),
433            b"Tw" => self.state.word_spacing = number(operands, 0),
434            b"Tz" => self.state.horizontal_scale = number(operands, 0) / 100.0,
435            b"Ts" => self.state.rise = number(operands, 0),
436            b"Tj" => {
437                if let Some(Object::String(string)) = operands.first() {
438                    let bytes = string.as_bytes().to_vec();
439                    self.show_text(&bytes)?;
440                }
441            }
442            b"'" => {
443                self.state.line_matrix = Matrix::new(1.0, 0.0, 0.0, 1.0, 0.0, -self.state.leading)
444                    .multiply(self.state.line_matrix);
445                self.state.text_matrix = self.state.line_matrix;
446                if let Some(Object::String(string)) = operands.first() {
447                    let bytes = string.as_bytes().to_vec();
448                    self.show_text(&bytes)?;
449                }
450            }
451            b"\"" => {
452                self.state.word_spacing = number(operands, 0);
453                self.state.char_spacing = number(operands, 1);
454                self.state.line_matrix = Matrix::new(1.0, 0.0, 0.0, 1.0, 0.0, -self.state.leading)
455                    .multiply(self.state.line_matrix);
456                self.state.text_matrix = self.state.line_matrix;
457                if let Some(Object::String(string)) = operands.get(2) {
458                    let bytes = string.as_bytes().to_vec();
459                    self.show_text(&bytes)?;
460                }
461            }
462            b"TJ" => {
463                if let Some(Object::Array(items)) = operands.first() {
464                    for item in items {
465                        match item {
466                            Object::String(string) => {
467                                let bytes = string.as_bytes().to_vec();
468                                self.show_text(&bytes)?;
469                            }
470                            Object::Integer(adjustment) => {
471                                self.adjust_text(*adjustment as f64);
472                            }
473                            Object::Real(adjustment) => self.adjust_text(*adjustment),
474                            _ => {}
475                        }
476                    }
477                }
478            }
479            b"Do" => {
480                if let Some(Object::Name(name)) = operands.first() {
481                    let name = name.clone();
482                    self.draw_image(&name)?;
483                }
484            }
485            b"BI" => {
486                skip_inline_image(parser)?;
487                self.report.note(operator);
488            }
489            _ => self.report.note(operator),
490        }
491        Ok(())
492    }
493
494    fn paint(&mut self, what: Paint, even_odd: bool) -> crate::Result<()> {
495        self.apply_pending_clip();
496        let ctm = self.state.ctm;
497        let scale = determinant_scale(ctm);
498        let polylines = self.path.flatten(ctm);
499        let painted = match what {
500            Paint::Fill | Paint::Both => true,
501            Paint::Stroke => false,
502        };
503        if painted && !polylines.is_empty() {
504            fill_polygons(
505                self.canvas,
506                &self.mask,
507                &polylines,
508                self.state.fill,
509                even_odd,
510                1.0,
511            );
512        }
513        if matches!(what, Paint::Stroke | Paint::Both) {
514            let mut stroked: Vec<Vec<Point>> = Vec::new();
515            for polyline in &polylines {
516                stroked.extend(dash_polyline(polyline, &self.state.dash, scale));
517            }
518            let outline = stroke_outline(
519                &stroked,
520                self.state.line_width * scale,
521                self.state.cap,
522                self.state.join,
523                self.state.miter_limit,
524            );
525            if !outline.is_empty() {
526                fill_polygons(
527                    self.canvas,
528                    &self.mask,
529                    &outline,
530                    self.state.stroke,
531                    false,
532                    1.0,
533                );
534            }
535        }
536        self.path = Path::new();
537        Ok(())
538    }
539
540    fn adjust_text(&mut self, adjustment: f64) {
541        let tx = -adjustment / 1000.0 * self.state.font_size * self.state.horizontal_scale;
542        self.state.text_matrix =
543            Matrix::new(1.0, 0.0, 0.0, 1.0, tx, 0.0).multiply(self.state.text_matrix);
544    }
545
546    fn show_text(&mut self, bytes: &[u8]) -> crate::Result<()> {
547        let Some(font) = self.state.font.clone() else {
548            return Ok(());
549        };
550        for &code in bytes {
551            if let Some(glyph) = font.glyph(code) {
552                if !glyph.contours.is_empty() {
553                    let scale = Matrix::new(
554                        self.state.font_size * self.state.horizontal_scale,
555                        0.0,
556                        0.0,
557                        self.state.font_size,
558                        0.0,
559                        self.state.rise,
560                    );
561                    let transform = scale
562                        .multiply(self.state.text_matrix)
563                        .multiply(self.state.ctm);
564                    let polygons: Vec<Vec<Point>> = glyph
565                        .contours
566                        .iter()
567                        .map(|contour| {
568                            contour
569                                .iter()
570                                .map(|point| transform.apply(*point))
571                                .collect()
572                        })
573                        .collect();
574                    fill_polygons(
575                        self.canvas,
576                        &self.mask,
577                        &polygons,
578                        self.state.fill,
579                        false,
580                        1.0,
581                    );
582                }
583            }
584            let em = self
585                .state
586                .widths
587                .as_ref()
588                .map_or_else(|| font.advance(code), |widths| widths.advance(code));
589            let mut advance = em * self.state.font_size + self.state.char_spacing;
590            if code == b' ' {
591                advance += self.state.word_spacing;
592            }
593            advance *= self.state.horizontal_scale;
594            self.state.text_matrix =
595                Matrix::new(1.0, 0.0, 0.0, 1.0, advance, 0.0).multiply(self.state.text_matrix);
596        }
597        Ok(())
598    }
599
600    fn draw_image(&mut self, name: &[u8]) -> crate::Result<()> {
601        let Some(resources) = self.resources.clone() else {
602            self.report.note(b"Do");
603            return Ok(());
604        };
605        let xobjects = match resolve(self.document, resources.get(b"XObject")) {
606            Ok(Object::Dictionary(xobjects)) => xobjects,
607            _ => {
608                self.report.note(b"Do");
609                return Ok(());
610            }
611        };
612        let entry = match xobjects.get(name) {
613            Some(entry) => entry.clone(),
614            None => {
615                self.report.note(b"Do");
616                return Ok(());
617            }
618        };
619        let object = resolve(self.document, Some(&entry))?;
620        let Object::Stream(stream) = object else {
621            self.report.note(b"Do");
622            return Ok(());
623        };
624        if !matches!(stream.dict().get(b"Subtype"), Some(Object::Name(name)) if name == b"Image") {
625            self.report.note(b"Do");
626            return Ok(());
627        }
628        match Image::from_stream(self.document, &stream) {
629            Ok(image) => {
630                image.paint(self.canvas, &self.mask, self.state.ctm);
631            }
632            // An image we cannot decode is reported, not fatal: the rest of the
633            // page still renders.
634            Err(_) => self.report.note(b"Do"),
635        }
636        Ok(())
637    }
638
639    fn load_font(&mut self, name: &[u8]) -> (Option<Font>, Option<SimpleWidths>) {
640        let Some((font, widths, unsupported)) = self.font_entry(name) else {
641            return (None, None);
642        };
643        if let Some(kind) = unsupported {
644            self.report.note(kind.as_bytes());
645        }
646        (font, widths)
647    }
648
649    /// The font dictionary behind a resource name, its widths and, when the
650    /// family is not one this renderer draws, the name to report.
651    fn font_entry(
652        &mut self,
653        name: &[u8],
654    ) -> Option<(Option<Font>, Option<SimpleWidths>, Option<&'static str>)> {
655        let resources = self.resources.clone()?;
656        let fonts = match resolve(self.document, resources.get(b"Font")) {
657            Ok(Object::Dictionary(fonts)) => fonts,
658            _ => return None,
659        };
660        let entry = fonts.get(name)?.clone();
661        let font_object = resolve(self.document, Some(&entry)).ok()?;
662        let Object::Dictionary(font) = font_object else {
663            return None;
664        };
665        let subtype = match font.get(b"Subtype") {
666            Some(Object::Name(name)) => name.clone(),
667            _ => Vec::new(),
668        };
669        // Type 0 (CID), Type 3 and embedded Type 1/CFF programs are not drawn
670        // yet; report them by name instead of painting fallback glyphs as if
671        // they were the document's font.
672        match subtype.as_slice() {
673            b"Type0" => return Some((None, None, Some("font:Type0"))),
674            b"Type3" => return Some((None, None, Some("font:Type3"))),
675            _ => {}
676        }
677        let encoding = self.encoding_for(&font);
678        let widths = self.widths_for(&font);
679        if let Some(descriptor) = font.get(b"FontDescriptor") {
680            let descriptor = resolve(self.document, Some(descriptor)).ok()?;
681            if let Object::Dictionary(descriptor) = descriptor {
682                for (key, kind) in [
683                    (&b"FontFile3"[..], "font:FontFile3"),
684                    (&b"FontFile"[..], "font:FontFile"),
685                ] {
686                    if descriptor.get(key).is_some() {
687                        return Some((Some(Font::builtin(encoding)), widths, Some(kind)));
688                    }
689                }
690                if let Some(font_file) = descriptor.get(b"FontFile2") {
691                    let data = match font_file {
692                        Object::Reference(id) => self.document.stream_data(*id).ok(),
693                        _ => None,
694                    };
695                    if let Some(data) = data {
696                        if let Some(font) = Font::true_type(encoding.clone(), data) {
697                            return Some((Some(font), widths, None));
698                        }
699                    }
700                }
701            }
702        }
703        Some((Some(Font::builtin(encoding)), widths, None))
704    }
705
706    /// `/Widths` plus the descriptor's `/MissingWidth`, when the font states
707    /// them. A base-14 font usually does not, and then the glyph's own advance
708    /// is the best available answer.
709    fn widths_for(&self, font: &Dictionary) -> Option<SimpleWidths> {
710        let first = font.get(b"FirstChar").and_then(Object::as_integer)?;
711        let Object::Array(items) = resolve(self.document, font.get(b"Widths")).ok()? else {
712            return None;
713        };
714        let widths: Vec<f64> = items
715            .iter()
716            .map(|item| {
717                resolve(self.document, Some(item))
718                    .ok()
719                    .and_then(|item| item.as_real())
720            })
721            .map(|width| width.unwrap_or(0.0))
722            .collect();
723        let missing = font
724            .get(b"FontDescriptor")
725            .and_then(|descriptor| resolve(self.document, Some(descriptor)).ok())
726            .and_then(|descriptor| match descriptor {
727                Object::Dictionary(descriptor) => {
728                    descriptor.get(b"MissingWidth").and_then(Object::as_real)
729                }
730                _ => None,
731            })
732            .unwrap_or(0.0);
733        Some(SimpleWidths {
734            first,
735            widths,
736            missing,
737        })
738    }
739
740    fn encoding_for(&self, font: &Dictionary) -> Encoding {
741        let Some(encoding_object) = font.get(b"Encoding") else {
742            return Encoding::standard();
743        };
744        let Ok(encoding_object) = resolve(self.document, Some(encoding_object)) else {
745            return Encoding::standard();
746        };
747        let mut encoding = Encoding::from_object(Some(&encoding_object)).unwrap_or_default();
748        if let Object::Dictionary(dict) = &encoding_object {
749            if let Some(differences) = dict.get(b"Differences") {
750                if let Ok(Object::Array(items)) = resolve(self.document, Some(differences)) {
751                    let _ = encoding.apply_differences(&items);
752                }
753            }
754        }
755        encoding
756    }
757
758    fn apply_pending_clip(&mut self) {
759        let Some(even_odd) = self.pending_clip.take() else {
760            return;
761        };
762        let polylines = self.path.flatten(self.state.ctm);
763        let mask = clip_mask(
764            self.canvas.width(),
765            self.canvas.height(),
766            &polylines,
767            even_odd,
768        );
769        self.mask.intersect(&mask);
770    }
771}
772
773#[derive(Debug, Clone, Copy, PartialEq, Eq)]
774enum Paint {
775    Fill,
776    Stroke,
777    Both,
778}
779
780fn determinant_scale(ctm: Matrix) -> f64 {
781    let determinant = ctm.a * ctm.d - ctm.b * ctm.c;
782    determinant.abs().sqrt()
783}
784
785fn number(operands: &[Object], index: usize) -> f64 {
786    operands.get(index).and_then(Object::as_real).unwrap_or(0.0)
787}
788
789fn integer(operands: &[Object], index: usize) -> i64 {
790    operands
791        .get(index)
792        .and_then(Object::as_integer)
793        .unwrap_or(0)
794}
795
796fn matrix_operand(operands: &[Object]) -> Option<Matrix> {
797    if operands.len() < 6 {
798        return None;
799    }
800    Some(Matrix::new(
801        number(operands, 0),
802        number(operands, 1),
803        number(operands, 2),
804        number(operands, 3),
805        number(operands, 4),
806        number(operands, 5),
807    ))
808}
809
810/// The `pair`th point in the operands, if all of its numbers are there.
811///
812/// Callers name a *point*, not a number: `c` takes three of them at slots 0, 1
813/// and 2, which are the numbers `(0, 1)`, `(2, 3)` and `(4, 5)`. Reading the
814/// slot as a number index silently turned every curve's last control point into
815/// its end point, which is what a wrong index looks like on the page.
816fn point_operand(operands: &[Object], pair: usize) -> Option<Point> {
817    let start = pair * 2;
818    if operands.len() < start + 2 {
819        return None;
820    }
821    Some(Point::new(
822        number(operands, start),
823        number(operands, start + 1),
824    ))
825}
826
827fn dash_operand(operands: &[Object]) -> Dash {
828    let pattern = match operands.first() {
829        Some(Object::Array(items)) => items
830            .iter()
831            .filter_map(Object::as_real)
832            .collect::<Vec<f64>>(),
833        _ => Vec::new(),
834    };
835    let phase = number(operands, 1);
836    Dash { pattern, phase }
837}
838
839/// Skip inline image data (`BI` … `EI`), which cannot be tokenised.
840fn skip_inline_image(parser: &mut Parser<'_>) -> crate::Result<()> {
841    let start = parser.raw_position();
842    let content = parser.content();
843    let found = content
844        .get(start..)
845        .and_then(|rest| find_operator(rest, b"EI"))
846        .ok_or_else(|| crate::Error::malformed("inline image without a closing EI"))?;
847    parser.seek(start + found + 2);
848    Ok(())
849}
850
851fn find_operator(haystack: &[u8], needle: &[u8]) -> Option<usize> {
852    let mut index = 0;
853    while index + needle.len() <= haystack.len() {
854        if &haystack[index..index + needle.len()] == needle {
855            let delimiter = |byte: u8| is_whitespace(byte) || is_delimiter(byte);
856            let before_ok = index == 0 || delimiter(haystack[index - 1]);
857            let after = index + needle.len();
858            let after_ok = after >= haystack.len() || delimiter(haystack[after]);
859            if before_ok && after_ok {
860                return Some(index);
861            }
862        }
863        index += 1;
864    }
865    None
866}
867
868#[cfg(test)]
869mod tests {
870    use super::{dash_operand, Report};
871    use pdf2::Object;
872
873    #[test]
874    fn reports_collect_operator_counts_in_order() {
875        let mut report = Report::default();
876        report.note(b"Tj");
877        report.note(b"Tj");
878        report.note(b"Do");
879        assert_eq!(report.unsupported_total(), 3);
880        assert_eq!(report.unsupported.get("Tj"), Some(&2));
881        assert_eq!(report.to_string(), "Do×1, Tj×2");
882    }
883
884    #[test]
885    fn dash_operands_default_to_solid() {
886        assert!(dash_operand(&[]).is_solid());
887        let dash = dash_operand(&[
888            Object::array([Object::Integer(4), Object::Integer(2)]),
889            Object::Integer(1),
890        ]);
891        assert_eq!(dash.pattern, vec![4.0, 2.0]);
892        assert_eq!(dash.phase, 1.0);
893    }
894}