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, 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/// 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/// What a font resource yields, with the reason it is not drawable when it is
120/// not.
121#[derive(Debug, Clone, Default)]
122struct LoadedFont {
123    font: Option<Font>,
124    widths: Option<SimpleWidths>,
125    cid: Option<CidFont>,
126    note: Option<&'static str>,
127}
128
129/// A composite (Type 0) font: two-byte codes, CIDs mapped to glyph ids through
130/// `/CIDToGIDMap`, and advances from `/W` with `/DW` as the default (9.7.4).
131#[derive(Debug, Clone)]
132struct CidFont {
133    font: Font,
134    to_gid: CidToGid,
135    widths: CidWidths,
136}
137
138#[derive(Debug, Clone)]
139enum CidToGid {
140    Identity,
141    Table(Vec<u16>),
142}
143
144#[derive(Debug, Clone, Default)]
145struct CidWidths {
146    /// `(first CID, widths)` runs from `/W`, in 1/1000 em.
147    ranges: Vec<(u32, Vec<f64>)>,
148    /// `/DW`, which the standard sets to 1000 when absent.
149    default: f64,
150}
151
152impl CidFont {
153    fn glyph_id(&self, cid: u16) -> u16 {
154        match &self.to_gid {
155            CidToGid::Identity => cid,
156            CidToGid::Table(table) => table.get(usize::from(cid)).copied().unwrap_or(0),
157        }
158    }
159
160    fn advance(&self, cid: u16) -> f64 {
161        for (start, widths) in &self.widths.ranges {
162            let index = u32::from(cid).wrapping_sub(*start);
163            if let Some(width) = widths.get(index as usize) {
164                return width / 1000.0;
165            }
166        }
167        self.widths.default / 1000.0
168    }
169}
170
171/// Rasterise one page.
172pub fn render_page(
173    document: &Document,
174    page: &Page,
175    options: &RenderOptions,
176) -> crate::Result<RenderedPage> {
177    let scale = if options.scale.is_finite() && options.scale > 0.0 {
178        options.scale
179    } else {
180        1.0
181    };
182    // The visible box is `/CropBox` when the page states one (14.11.2): it
183    // defines the raster and the origin, and the media box only bounds it.
184    let media = page
185        .crop_box
186        .or(page.media_box)
187        .unwrap_or(pdf2::Rect::new(0.0, 0.0, 612.0, 792.0));
188    // `/UserUnit` scales default user space (7.7.3.4), so it multiplies the
189    // device resolution rather than the page's coordinates.
190    let scale = scale * document.page_user_unit(page).unwrap_or(1.0);
191    // `/Rotate` turns the page clockwise for display, so a quarter turn swaps
192    // the canvas dimensions.
193    let rotate = page.rotate.rem_euclid(360);
194    let landscape = rotate == 90 || rotate == 270;
195    let (width_points, height_points) = if landscape {
196        (media.height(), media.width())
197    } else {
198        (media.width(), media.height())
199    };
200    let width = ((width_points * scale).round().max(1.0)) as u32;
201    let height = ((height_points * scale).round().max(1.0)) as u32;
202    let mut canvas = Canvas::new(width, height, options.background);
203    let mut report = Report::default();
204
205    // PDF user space to device space. Every case shifts the media box origin to
206    // (0, 0); the y axis grows downwards in the raster, and `/Rotate` composes
207    // a clockwise quarter turn (or two) on top of that flip.
208    let base = match rotate {
209        90 => Matrix::new(0.0, scale, scale, 0.0, -media.y0 * scale, -media.x0 * scale),
210        180 => Matrix::new(-scale, 0.0, 0.0, scale, media.x1 * scale, -media.y0 * scale),
211        270 => Matrix::new(0.0, scale, -scale, 0.0, media.y1 * scale, -media.x0 * scale),
212        _ => Matrix::new(scale, 0.0, 0.0, -scale, -media.x0 * scale, media.y1 * scale),
213    };
214
215    let content = document.page_content(page)?;
216    let mut walker = Walker {
217        canvas: &mut canvas,
218        report: &mut report,
219        document,
220        resources: page.resources.clone(),
221        state: State::new(base),
222        stack: Vec::new(),
223        path: Path::new(),
224        pending_clip: None,
225        mask: ClipMask::all(width, height),
226    };
227    walker.run(&content)?;
228    Ok(RenderedPage { canvas, report })
229}
230
231/// The part of the graphics state that painting depends on.
232#[derive(Debug, Clone)]
233struct State {
234    ctm: Matrix,
235    line_width: f64,
236    cap: Cap,
237    join: Join,
238    dash: Dash,
239    fill: Color,
240    stroke: Color,
241    font: Option<Font>,
242    font_size: f64,
243    miter_limit: f64,
244    widths: Option<SimpleWidths>,
245    cid: Option<CidFont>,
246    char_spacing: f64,
247    word_spacing: f64,
248    horizontal_scale: f64,
249    leading: f64,
250    rise: f64,
251    /// `Tr`: 0 fill, 1 stroke, 2 both, 3 neither (invisible), 4–7 the same with
252    /// clipping (9.3).
253    text_mode: i64,
254    text_matrix: Matrix,
255    line_matrix: Matrix,
256}
257
258impl State {
259    fn new(ctm: Matrix) -> Self {
260        Self {
261            ctm,
262            line_width: 1.0,
263            cap: Cap::Butt,
264            join: Join::Miter,
265            dash: Dash::solid(),
266            fill: Color::BLACK,
267            stroke: Color::BLACK,
268            font: None,
269            font_size: 0.0,
270            miter_limit: 10.0,
271            widths: None,
272            cid: None,
273            char_spacing: 0.0,
274            word_spacing: 0.0,
275            horizontal_scale: 1.0,
276            leading: 0.0,
277            rise: 0.0,
278            text_mode: 0,
279            text_matrix: Matrix::IDENTITY,
280            line_matrix: Matrix::IDENTITY,
281        }
282    }
283}
284
285struct Walker<'a> {
286    canvas: &'a mut Canvas,
287    report: &'a mut Report,
288    document: &'a Document,
289    resources: Option<Dictionary>,
290    state: State,
291    stack: Vec<(State, ClipMask)>,
292    path: Path,
293    pending_clip: Option<bool>,
294    mask: ClipMask,
295}
296
297impl Walker<'_> {
298    fn run(&mut self, content: &[u8]) -> crate::Result<()> {
299        let mut parser = Parser::new(content);
300        let mut operands: Vec<Object> = Vec::new();
301        loop {
302            match parser.peek_token()? {
303                Token::Eof => break,
304                Token::Keyword(_) => {
305                    let operator = match parser.next_token()? {
306                        Token::Keyword(operator) => operator,
307                        _ => return Err(crate::Error::malformed("content-stream operator")),
308                    };
309                    self.execute(&operator, &mut operands, &mut parser)?;
310                    operands.clear();
311                }
312                _ => {
313                    operands.push(parser.parse_object()?);
314                }
315            }
316        }
317        Ok(())
318    }
319
320    fn execute(
321        &mut self,
322        operator: &[u8],
323        operands: &mut [Object],
324        parser: &mut Parser<'_>,
325    ) -> crate::Result<()> {
326        match operator {
327            b"q" => {
328                self.stack.push((self.state.clone(), self.mask.clone()));
329            }
330            b"Q" => {
331                if let Some((state, mask)) = self.stack.pop() {
332                    self.state = state;
333                    self.mask = mask;
334                }
335            }
336            b"cm" => {
337                if let Some(matrix) = matrix_operand(operands) {
338                    self.state.ctm = matrix.multiply(self.state.ctm);
339                }
340            }
341            b"w" => self.state.line_width = number(operands, 0),
342            b"J" => {
343                self.state.cap = match integer(operands, 0) {
344                    1 => Cap::Round,
345                    2 => Cap::Square,
346                    _ => Cap::Butt,
347                }
348            }
349            b"j" => {
350                self.state.join = match integer(operands, 0) {
351                    1 => Join::Round,
352                    2 => Join::Bevel,
353                    _ => Join::Miter,
354                }
355            }
356            b"M" => self.state.miter_limit = number(operands, 0).max(1.0),
357            b"d" => self.state.dash = dash_operand(operands),
358            b"m" => {
359                if let Some(point) = point_operand(operands, 0) {
360                    self.path.move_to(point);
361                }
362            }
363            b"l" => {
364                if let Some(point) = point_operand(operands, 0) {
365                    self.path.line_to(point);
366                }
367            }
368            b"c" => {
369                if let (Some(c1), Some(c2), Some(to)) = (
370                    point_operand(operands, 0),
371                    point_operand(operands, 1),
372                    point_operand(operands, 2),
373                ) {
374                    self.path.curve_to(c1, c2, to);
375                }
376            }
377            b"v" | b"y" => {
378                // `v` and `y` are shorthand curves; draw them as a straight
379                // line to the end point, which keeps the path closed.
380                if let Some(to) = point_operand(operands, 1) {
381                    self.path.line_to(to);
382                }
383            }
384            b"h" => self.path.close(),
385            b"re" => {
386                let x = number(operands, 0);
387                let y = number(operands, 1);
388                let width = number(operands, 2);
389                let height = number(operands, 3);
390                self.path.add_rect(x, y, width, height);
391            }
392            b"S" => self.paint(Paint::Stroke, false)?,
393            b"s" => {
394                self.path.close();
395                self.paint(Paint::Stroke, false)?;
396            }
397            b"f" | b"F" => self.paint(Paint::Fill, false)?,
398            b"f*" => self.paint(Paint::Fill, true)?,
399            b"B" => self.paint(Paint::Both, false)?,
400            b"B*" => self.paint(Paint::Both, true)?,
401            b"b" => {
402                self.path.close();
403                self.paint(Paint::Both, false)?;
404            }
405            b"b*" => {
406                self.path.close();
407                self.paint(Paint::Both, true)?;
408            }
409            b"W" => self.pending_clip = Some(false),
410            b"W*" => self.pending_clip = Some(true),
411            b"n" => {
412                self.apply_pending_clip();
413                self.path = Path::new();
414            }
415            b"g" => {
416                self.state.fill = Color::rgb(
417                    number(operands, 0),
418                    number(operands, 0),
419                    number(operands, 0),
420                )
421            }
422            b"G" => {
423                self.state.stroke = Color::rgb(
424                    number(operands, 0),
425                    number(operands, 0),
426                    number(operands, 0),
427                )
428            }
429            b"rg" => {
430                self.state.fill = Color::rgb(
431                    number(operands, 0),
432                    number(operands, 1),
433                    number(operands, 2),
434                );
435            }
436            b"RG" => {
437                self.state.stroke = Color::rgb(
438                    number(operands, 0),
439                    number(operands, 1),
440                    number(operands, 2),
441                );
442            }
443            b"k" => {
444                self.state.fill = Color::from_cmyk(
445                    number(operands, 0),
446                    number(operands, 1),
447                    number(operands, 2),
448                    number(operands, 3),
449                );
450            }
451            b"K" => {
452                self.state.stroke = Color::from_cmyk(
453                    number(operands, 0),
454                    number(operands, 1),
455                    number(operands, 2),
456                    number(operands, 3),
457                );
458            }
459            b"BT" => {
460                self.state.text_matrix = Matrix::IDENTITY;
461                self.state.line_matrix = Matrix::IDENTITY;
462            }
463            b"ET" => {}
464            b"Tf" => {
465                let name = match operands.first() {
466                    Some(Object::Name(name)) => name.clone(),
467                    _ => return Err(crate::Error::malformed("/Tf needs a font name")),
468                };
469                self.state.font_size = number(operands, 1);
470                let (font, widths, cid) = self.load_font(&name);
471                self.state.font = font;
472                self.state.widths = widths;
473                self.state.cid = cid;
474            }
475            b"Td" | b"TD" => {
476                let tx = number(operands, 0);
477                let ty = number(operands, 1);
478                self.state.line_matrix =
479                    Matrix::new(1.0, 0.0, 0.0, 1.0, tx, ty).multiply(self.state.line_matrix);
480                self.state.text_matrix = self.state.line_matrix;
481                if operator == b"TD" {
482                    self.state.leading = -ty;
483                }
484            }
485            b"T*" => {
486                self.state.line_matrix = Matrix::new(1.0, 0.0, 0.0, 1.0, 0.0, -self.state.leading)
487                    .multiply(self.state.line_matrix);
488                self.state.text_matrix = self.state.line_matrix;
489            }
490            b"Tm" => {
491                if let Some(matrix) = matrix_operand(operands) {
492                    self.state.line_matrix = matrix;
493                    self.state.text_matrix = matrix;
494                }
495            }
496            b"TL" => self.state.leading = number(operands, 0),
497            b"Tc" => self.state.char_spacing = number(operands, 0),
498            b"Tw" => self.state.word_spacing = number(operands, 0),
499            b"Tz" => self.state.horizontal_scale = number(operands, 0) / 100.0,
500            b"Ts" => self.state.rise = number(operands, 0),
501            b"Tr" => {
502                let mode = number(operands, 0);
503                let mode = if mode.is_finite() {
504                    #[allow(clippy::cast_possible_truncation)]
505                    let mode = mode as i64;
506                    mode.clamp(0, 7)
507                } else {
508                    0
509                };
510                // Modes 4–7 add clipping, which the rasteriser does not model
511                // yet; the fill and stroke halves are what a page shows.
512                self.state.text_mode = mode;
513            }
514            b"Tj" => {
515                if let Some(Object::String(string)) = operands.first() {
516                    let bytes = string.as_bytes().to_vec();
517                    self.show_text(&bytes)?;
518                }
519            }
520            b"'" => {
521                self.state.line_matrix = Matrix::new(1.0, 0.0, 0.0, 1.0, 0.0, -self.state.leading)
522                    .multiply(self.state.line_matrix);
523                self.state.text_matrix = self.state.line_matrix;
524                if let Some(Object::String(string)) = operands.first() {
525                    let bytes = string.as_bytes().to_vec();
526                    self.show_text(&bytes)?;
527                }
528            }
529            b"\"" => {
530                self.state.word_spacing = number(operands, 0);
531                self.state.char_spacing = number(operands, 1);
532                self.state.line_matrix = Matrix::new(1.0, 0.0, 0.0, 1.0, 0.0, -self.state.leading)
533                    .multiply(self.state.line_matrix);
534                self.state.text_matrix = self.state.line_matrix;
535                if let Some(Object::String(string)) = operands.get(2) {
536                    let bytes = string.as_bytes().to_vec();
537                    self.show_text(&bytes)?;
538                }
539            }
540            b"TJ" => {
541                if let Some(Object::Array(items)) = operands.first() {
542                    for item in items {
543                        match item {
544                            Object::String(string) => {
545                                let bytes = string.as_bytes().to_vec();
546                                self.show_text(&bytes)?;
547                            }
548                            Object::Integer(adjustment) => {
549                                self.adjust_text(*adjustment as f64);
550                            }
551                            Object::Real(adjustment) => self.adjust_text(*adjustment),
552                            _ => {}
553                        }
554                    }
555                }
556            }
557            b"Do" => {
558                if let Some(Object::Name(name)) = operands.first() {
559                    let name = name.clone();
560                    self.draw_image(&name)?;
561                }
562            }
563            b"BI" => {
564                skip_inline_image(parser)?;
565                self.report.note(operator);
566            }
567            _ => self.report.note(operator),
568        }
569        Ok(())
570    }
571
572    fn paint(&mut self, what: Paint, even_odd: bool) -> crate::Result<()> {
573        self.apply_pending_clip();
574        let ctm = self.state.ctm;
575        let scale = determinant_scale(ctm);
576        let polylines = self.path.flatten(ctm);
577        let painted = match what {
578            Paint::Fill | Paint::Both => true,
579            Paint::Stroke => false,
580        };
581        if painted && !polylines.is_empty() {
582            fill_polygons(
583                self.canvas,
584                &self.mask,
585                &polylines,
586                self.state.fill,
587                even_odd,
588                1.0,
589            );
590        }
591        if matches!(what, Paint::Stroke | Paint::Both) {
592            let mut stroked: Vec<Vec<Point>> = Vec::new();
593            for polyline in &polylines {
594                stroked.extend(dash_polyline(polyline, &self.state.dash, scale));
595            }
596            let outline = stroke_outline(
597                &stroked,
598                self.state.line_width * scale,
599                self.state.cap,
600                self.state.join,
601                self.state.miter_limit,
602            );
603            if !outline.is_empty() {
604                fill_polygons(
605                    self.canvas,
606                    &self.mask,
607                    &outline,
608                    self.state.stroke,
609                    false,
610                    1.0,
611                );
612            }
613        }
614        self.path = Path::new();
615        Ok(())
616    }
617
618    fn adjust_text(&mut self, adjustment: f64) {
619        let tx = -adjustment / 1000.0 * self.state.font_size * self.state.horizontal_scale;
620        self.state.text_matrix =
621            Matrix::new(1.0, 0.0, 0.0, 1.0, tx, 0.0).multiply(self.state.text_matrix);
622    }
623
624    fn show_text(&mut self, bytes: &[u8]) -> crate::Result<()> {
625        if let Some(cid) = self.state.cid.clone() {
626            // Identity-H and friends: the string is a run of two-byte codes.
627            for pair in bytes.chunks_exact(2) {
628                let code = u16::from_be_bytes([pair[0], pair[1]]);
629                if let Some(glyph) = cid.font.glyph_by_id(cid.glyph_id(code)) {
630                    self.place_glyph(&glyph);
631                }
632                let advance = cid.advance(code) * self.state.font_size + self.state.char_spacing;
633                self.advance_text(advance * self.state.horizontal_scale);
634            }
635            return Ok(());
636        }
637        let Some(font) = self.state.font.clone() else {
638            return Ok(());
639        };
640        for &code in bytes {
641            if let Some(glyph) = font.glyph(code) {
642                self.place_glyph(&glyph);
643            }
644            let em = self
645                .state
646                .widths
647                .as_ref()
648                .map_or_else(|| font.advance(code), |widths| widths.advance(code));
649            let mut advance = em * self.state.font_size + self.state.char_spacing;
650            if code == b' ' {
651                advance += self.state.word_spacing;
652            }
653            self.advance_text(advance * self.state.horizontal_scale);
654        }
655        Ok(())
656    }
657
658    /// Fill one glyph outline at the current text position.
659    fn place_glyph(&mut self, glyph: &Glyph) {
660        if glyph.contours.is_empty() {
661            return;
662        }
663        // `Tr` 3 and 7 draw nothing; 1, 5 stroke only; 2, 6 fill and stroke.
664        let mode = self.state.text_mode;
665        let invisible = matches!(mode, 3 | 7);
666        if invisible {
667            return;
668        }
669        let scale = Matrix::new(
670            self.state.font_size * self.state.horizontal_scale,
671            0.0,
672            0.0,
673            self.state.font_size,
674            0.0,
675            self.state.rise,
676        );
677        let transform = scale
678            .multiply(self.state.text_matrix)
679            .multiply(self.state.ctm);
680        let polygons: Vec<Vec<Point>> = glyph
681            .contours
682            .iter()
683            .map(|contour| {
684                contour
685                    .iter()
686                    .map(|point| transform.apply(*point))
687                    .collect()
688            })
689            .collect();
690        let filled = matches!(mode, 0 | 2 | 4 | 6);
691        if filled {
692            fill_polygons(
693                self.canvas,
694                &self.mask,
695                &polygons,
696                self.state.fill,
697                false,
698                1.0,
699            );
700        }
701        if matches!(mode, 1 | 2 | 5 | 6) {
702            // A stroked glyph uses the text state's line width, cap and join.
703            let mut outline = Vec::new();
704            for polygon in &polygons {
705                let mut closed = polygon.clone();
706                if let Some(first) = closed.first().copied() {
707                    closed.push(first);
708                }
709                outline.extend(stroke_outline(
710                    &[closed],
711                    self.state.line_width,
712                    self.state.cap,
713                    self.state.join,
714                    self.state.miter_limit,
715                ));
716            }
717            if !outline.is_empty() {
718                fill_polygons(
719                    self.canvas,
720                    &self.mask,
721                    &outline,
722                    self.state.stroke,
723                    false,
724                    1.0,
725                );
726            }
727        }
728    }
729
730    /// Move the text position by `advance` in unscaled text space.
731    fn advance_text(&mut self, advance: f64) {
732        self.state.text_matrix =
733            Matrix::new(1.0, 0.0, 0.0, 1.0, advance, 0.0).multiply(self.state.text_matrix);
734    }
735
736    fn draw_image(&mut self, name: &[u8]) -> crate::Result<()> {
737        let Some(resources) = self.resources.clone() else {
738            self.report.note(b"Do");
739            return Ok(());
740        };
741        let xobjects = match resolve(self.document, resources.get(b"XObject")) {
742            Ok(Object::Dictionary(xobjects)) => xobjects,
743            _ => {
744                self.report.note(b"Do");
745                return Ok(());
746            }
747        };
748        let entry = match xobjects.get(name) {
749            Some(entry) => entry.clone(),
750            None => {
751                self.report.note(b"Do");
752                return Ok(());
753            }
754        };
755        let object = resolve(self.document, Some(&entry))?;
756        let Object::Stream(stream) = object else {
757            self.report.note(b"Do");
758            return Ok(());
759        };
760        if !matches!(stream.dict().get(b"Subtype"), Some(Object::Name(name)) if name == b"Image") {
761            self.report.note(b"Do");
762            return Ok(());
763        }
764        match Image::from_stream(self.document, &stream) {
765            Ok(image) => {
766                image.paint(self.canvas, &self.mask, self.state.ctm);
767            }
768            // An image we cannot decode is reported, not fatal: the rest of the
769            // page still renders.
770            Err(_) => self.report.note(b"Do"),
771        }
772        Ok(())
773    }
774
775    fn load_font(&mut self, name: &[u8]) -> (Option<Font>, Option<SimpleWidths>, Option<CidFont>) {
776        let Some(loaded) = self.font_entry(name) else {
777            return (None, None, None);
778        };
779        if let Some(note) = loaded.note {
780            self.report.note(note.as_bytes());
781        }
782        (loaded.font, loaded.widths, loaded.cid)
783    }
784
785    /// Everything the walker needs from a font resource, with a note when the
786    /// family is one this renderer cannot draw.
787    fn font_entry(&mut self, name: &[u8]) -> Option<LoadedFont> {
788        let resources = self.resources.clone()?;
789        let fonts = match resolve(self.document, resources.get(b"Font")) {
790            Ok(Object::Dictionary(fonts)) => fonts,
791            _ => return None,
792        };
793        let entry = fonts.get(name)?.clone();
794        let font_object = resolve(self.document, Some(&entry)).ok()?;
795        let Object::Dictionary(font) = font_object else {
796            return None;
797        };
798        let subtype = match font.get(b"Subtype") {
799            Some(Object::Name(name)) => name.clone(),
800            _ => Vec::new(),
801        };
802        match subtype.as_slice() {
803            b"Type0" => return Some(self.cid_entry(&font)),
804            b"Type3" => {
805                return Some(LoadedFont {
806                    note: Some("font:Type3"),
807                    ..LoadedFont::default()
808                })
809            }
810            _ => {}
811        }
812        let encoding = self.encoding_for(&font);
813        let widths = self.widths_for(&font);
814        if let Some(descriptor) = font.get(b"FontDescriptor") {
815            let descriptor = resolve(self.document, Some(descriptor)).ok()?;
816            if let Object::Dictionary(descriptor) = descriptor {
817                for (key, kind) in [
818                    (&b"FontFile3"[..], "font:FontFile3"),
819                    (&b"FontFile"[..], "font:FontFile"),
820                ] {
821                    if descriptor.get(key).is_some() {
822                        return Some(LoadedFont {
823                            font: Some(Font::builtin(encoding)),
824                            widths,
825                            cid: None,
826                            note: Some(kind),
827                        });
828                    }
829                }
830                if let Some(font_file) = descriptor.get(b"FontFile2") {
831                    let data = match font_file {
832                        Object::Reference(id) => self.document.stream_data(*id).ok(),
833                        _ => None,
834                    };
835                    if let Some(data) = data {
836                        if let Some(font) = Font::true_type(encoding.clone(), data) {
837                            return Some(LoadedFont {
838                                font: Some(font),
839                                widths,
840                                cid: None,
841                                note: None,
842                            });
843                        }
844                    }
845                }
846            }
847        }
848        Some(LoadedFont {
849            font: Some(Font::builtin(encoding)),
850            widths,
851            cid: None,
852            note: None,
853        })
854    }
855
856    /// A Type 0 font: a descendant CIDFontType2 with an embedded program and an
857    /// identity CMap is drawable; anything else is reported by reason.
858    fn cid_entry(&mut self, font: &Dictionary) -> LoadedFont {
859        let identity = matches!(
860            resolve(self.document, font.get(b"Encoding")).ok(),
861            Some(Object::Name(name)) if name.starts_with(b"Identity")
862        );
863        if !identity {
864            return LoadedFont {
865                note: Some("font:Type0-cmap"),
866                ..LoadedFont::default()
867            };
868        }
869        let descendant = match resolve(self.document, font.get(b"DescendantFonts")).ok() {
870            Some(Object::Array(items)) => items
871                .first()
872                .and_then(|item| resolve(self.document, Some(item)).ok()),
873            _ => None,
874        };
875        let Some(Object::Dictionary(descendant)) = descendant else {
876            return LoadedFont {
877                note: Some("font:Type0-descendant"),
878                ..LoadedFont::default()
879            };
880        };
881        let subtype = match descendant.get(b"Subtype") {
882            Some(Object::Name(name)) => name.clone(),
883            _ => Vec::new(),
884        };
885        // CIDFontType2 is TrueType, CIDFontType0 is CFF; both draw once the
886        // program is wrapped, so the only difference here is which descriptor
887        // entry carries it.
888        if subtype != b"CIDFontType2" && subtype != b"CIDFontType0" {
889            return LoadedFont {
890                note: Some("font:CIDFontType0-unknown"),
891                ..LoadedFont::default()
892            };
893        }
894        let is_cff = subtype == b"CIDFontType0";
895        let program = descendant
896            .get(b"FontDescriptor")
897            .and_then(|descriptor| resolve(self.document, Some(descriptor)).ok())
898            .and_then(|descriptor| match descriptor {
899                Object::Dictionary(descriptor) => {
900                    let entry: &[u8] = if is_cff { b"FontFile3" } else { b"FontFile2" };
901                    descriptor.get(entry).and_then(|file| match file {
902                        Object::Reference(id) => self.document.stream_data(*id).ok(),
903                        _ => None,
904                    })
905                }
906                _ => None,
907            })
908            .and_then(|data| {
909                if is_cff {
910                    // CFF arrives bare (`/CIDFontType0C`) or wrapped (`/OpenType`);
911                    // `Font::cff` accepts both.
912                    Font::cff(Encoding::standard(), data)
913                } else {
914                    Font::true_type(Encoding::standard(), data)
915                }
916            });
917        let Some(program) = program else {
918            return LoadedFont {
919                note: Some("font:Type0-no-program"),
920                ..LoadedFont::default()
921            };
922        };
923        // Read the entry unresolved: resolving it would dereference the stream
924        // reference and lose the id the bytes are behind.
925        let to_gid = match descendant.get(b"CIDToGIDMap") {
926            Some(Object::Name(name)) if name == b"Identity" => CidToGid::Identity,
927            Some(Object::Reference(id)) => self
928                .document
929                .stream_data(*id)
930                .map(|data| {
931                    CidToGid::Table(
932                        data.chunks_exact(2)
933                            .map(|pair| u16::from_be_bytes([pair[0], pair[1]]))
934                            .collect(),
935                    )
936                })
937                .unwrap_or(CidToGid::Identity),
938            // Absent means identity.
939            _ => CidToGid::Identity,
940        };
941        LoadedFont {
942            font: None,
943            widths: None,
944            cid: Some(CidFont {
945                font: program,
946                to_gid,
947                widths: self.cid_widths(&descendant),
948            }),
949            note: None,
950        }
951    }
952
953    /// `/W` runs and `/DW` from a CID font dictionary (9.7.4.3).
954    fn cid_widths(&self, descendant: &Dictionary) -> CidWidths {
955        let mut ranges = vec![];
956        if let Ok(Object::Array(items)) = resolve(self.document, descendant.get(b"W")) {
957            let number = |item: Option<&Object>| {
958                item.and_then(|item| resolve(self.document, Some(item)).ok())
959                    .and_then(|item| item.as_real())
960            };
961            let mut index = 0;
962            while index + 1 < items.len() {
963                let Some(first) = number(items.get(index)) else {
964                    break;
965                };
966                match items.get(index + 1) {
967                    Some(Object::Array(list)) => {
968                        let widths = list
969                            .iter()
970                            .map(Object::as_real)
971                            .map(|w| w.unwrap_or(0.0))
972                            .collect();
973                        ranges.push((first as u32, widths));
974                        index += 2;
975                    }
976                    second => {
977                        let Some(last) = number(second) else { break };
978                        let Some(width) = number(items.get(index + 2)) else {
979                            break;
980                        };
981                        let count = (last - first).max(0.0) as usize + 1;
982                        ranges.push((first as u32, vec![width; count]));
983                        index += 3;
984                    }
985                }
986            }
987        }
988        let default = number_of(self.document, descendant.get(b"DW")).unwrap_or(1000.0);
989        CidWidths { ranges, default }
990    }
991
992    /// `/Widths` plus the descriptor's `/MissingWidth`, when the font states
993    /// them. A base-14 font usually does not, and then the glyph's own advance
994    /// is the best available answer.
995    fn widths_for(&self, font: &Dictionary) -> Option<SimpleWidths> {
996        let first = font.get(b"FirstChar").and_then(Object::as_integer)?;
997        let Object::Array(items) = resolve(self.document, font.get(b"Widths")).ok()? else {
998            return None;
999        };
1000        let widths: Vec<f64> = items
1001            .iter()
1002            .map(|item| number_of(self.document, Some(item)).unwrap_or(0.0))
1003            .collect();
1004        let missing = font
1005            .get(b"FontDescriptor")
1006            .and_then(|descriptor| resolve(self.document, Some(descriptor)).ok())
1007            .and_then(|descriptor| match descriptor {
1008                Object::Dictionary(descriptor) => {
1009                    number_of(self.document, descriptor.get(b"MissingWidth"))
1010                }
1011                _ => None,
1012            })
1013            .unwrap_or(0.0);
1014        Some(SimpleWidths {
1015            first,
1016            widths,
1017            missing,
1018        })
1019    }
1020
1021    fn encoding_for(&self, font: &Dictionary) -> Encoding {
1022        let Some(encoding_object) = font.get(b"Encoding") else {
1023            return Encoding::standard();
1024        };
1025        let Ok(encoding_object) = resolve(self.document, Some(encoding_object)) else {
1026            return Encoding::standard();
1027        };
1028        let mut encoding = Encoding::from_object(Some(&encoding_object)).unwrap_or_default();
1029        if let Object::Dictionary(dict) = &encoding_object {
1030            if let Some(differences) = dict.get(b"Differences") {
1031                if let Ok(Object::Array(items)) = resolve(self.document, Some(differences)) {
1032                    let _ = encoding.apply_differences(&items);
1033                }
1034            }
1035        }
1036        encoding
1037    }
1038
1039    fn apply_pending_clip(&mut self) {
1040        let Some(even_odd) = self.pending_clip.take() else {
1041            return;
1042        };
1043        let polylines = self.path.flatten(self.state.ctm);
1044        let mask = clip_mask(
1045            self.canvas.width(),
1046            self.canvas.height(),
1047            &polylines,
1048            even_odd,
1049        );
1050        self.mask.intersect(&mask);
1051    }
1052}
1053
1054#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1055enum Paint {
1056    Fill,
1057    Stroke,
1058    Both,
1059}
1060
1061fn determinant_scale(ctm: Matrix) -> f64 {
1062    let determinant = ctm.a * ctm.d - ctm.b * ctm.c;
1063    determinant.abs().sqrt()
1064}
1065
1066fn number(operands: &[Object], index: usize) -> f64 {
1067    operands.get(index).and_then(Object::as_real).unwrap_or(0.0)
1068}
1069
1070fn integer(operands: &[Object], index: usize) -> i64 {
1071    operands
1072        .get(index)
1073        .and_then(Object::as_integer)
1074        .unwrap_or(0)
1075}
1076
1077fn number_of(document: &Document, object: Option<&Object>) -> Option<f64> {
1078    resolve(document, object)
1079        .ok()
1080        .and_then(|object| object.as_real())
1081}
1082
1083fn matrix_operand(operands: &[Object]) -> Option<Matrix> {
1084    if operands.len() < 6 {
1085        return None;
1086    }
1087    Some(Matrix::new(
1088        number(operands, 0),
1089        number(operands, 1),
1090        number(operands, 2),
1091        number(operands, 3),
1092        number(operands, 4),
1093        number(operands, 5),
1094    ))
1095}
1096
1097/// The `pair`th point in the operands, if all of its numbers are there.
1098///
1099/// Callers name a *point*, not a number: `c` takes three of them at slots 0, 1
1100/// and 2, which are the numbers `(0, 1)`, `(2, 3)` and `(4, 5)`. Reading the
1101/// slot as a number index silently turned every curve's last control point into
1102/// its end point, which is what a wrong index looks like on the page.
1103fn point_operand(operands: &[Object], pair: usize) -> Option<Point> {
1104    let start = pair * 2;
1105    if operands.len() < start + 2 {
1106        return None;
1107    }
1108    Some(Point::new(
1109        number(operands, start),
1110        number(operands, start + 1),
1111    ))
1112}
1113
1114fn dash_operand(operands: &[Object]) -> Dash {
1115    let pattern = match operands.first() {
1116        Some(Object::Array(items)) => items
1117            .iter()
1118            .filter_map(Object::as_real)
1119            .collect::<Vec<f64>>(),
1120        _ => Vec::new(),
1121    };
1122    let phase = number(operands, 1);
1123    Dash { pattern, phase }
1124}
1125
1126/// Skip inline image data (`BI` … `EI`), which cannot be tokenised.
1127fn skip_inline_image(parser: &mut Parser<'_>) -> crate::Result<()> {
1128    let start = parser.raw_position();
1129    let content = parser.content();
1130    let found = content
1131        .get(start..)
1132        .and_then(|rest| find_operator(rest, b"EI"))
1133        .ok_or_else(|| crate::Error::malformed("inline image without a closing EI"))?;
1134    parser.seek(start + found + 2);
1135    Ok(())
1136}
1137
1138fn find_operator(haystack: &[u8], needle: &[u8]) -> Option<usize> {
1139    let mut index = 0;
1140    while index + needle.len() <= haystack.len() {
1141        if &haystack[index..index + needle.len()] == needle {
1142            let delimiter = |byte: u8| is_whitespace(byte) || is_delimiter(byte);
1143            let before_ok = index == 0 || delimiter(haystack[index - 1]);
1144            let after = index + needle.len();
1145            let after_ok = after >= haystack.len() || delimiter(haystack[after]);
1146            if before_ok && after_ok {
1147                return Some(index);
1148            }
1149        }
1150        index += 1;
1151    }
1152    None
1153}
1154
1155#[cfg(test)]
1156mod tests {
1157    use super::{dash_operand, Report};
1158    use pdf2::Object;
1159
1160    #[test]
1161    fn reports_collect_operator_counts_in_order() {
1162        let mut report = Report::default();
1163        report.note(b"Tj");
1164        report.note(b"Tj");
1165        report.note(b"Do");
1166        assert_eq!(report.unsupported_total(), 3);
1167        assert_eq!(report.unsupported.get("Tj"), Some(&2));
1168        assert_eq!(report.to_string(), "Do×1, Tj×2");
1169    }
1170
1171    #[test]
1172    fn dash_operands_default_to_solid() {
1173        assert!(dash_operand(&[]).is_solid());
1174        let dash = dash_operand(&[
1175            Object::array([Object::Integer(4), Object::Integer(2)]),
1176            Object::Integer(1),
1177        ]);
1178        assert_eq!(dash.pattern, vec![4.0, 2.0]);
1179        assert_eq!(dash.phase, 1.0);
1180    }
1181}