Skip to main content

docling_pdf/render/
content.rs

1//! The content-stream interpreter (ISO 32000-1, 8–9): graphics state, path
2//! construction and painting, clipping, text, XObjects, inline images,
3//! shadings and patterns, ExtGState, and the widget annotations' appearance
4//! streams — drawn onto a tiny-skia canvas in device space.
5//!
6//! Where docling-parse's renderer makes a choice, this one follows it: a
7//! stroke is at least one device pixel wide and a `0 w` hairline is one
8//! pixel; a line width scales by `sqrt(|det CTM|)`; ExtGState alpha and
9//! blend modes apply, soft masks and transparency groups do not (the group
10//! is drawn straight onto the page); dash patterns are drawn (docling-parse
11//! drops them); only Widget annotations are rendered, from their `/AP /N`
12//! appearance; a glyph with no face at all leaves a thin blue box.
13
14use std::cell::RefCell;
15use std::collections::HashMap;
16use std::rc::Rc;
17
18use lopdf::{Dictionary, Document, Object, ObjectId};
19use tiny_skia::{
20    BlendMode, FillRule, FilterQuality, GradientStop, LineCap, LineJoin, Mask, Paint, Path,
21    PathBuilder, Pixmap, PixmapPaint, Point, SpreadMode, Stroke, StrokeDash, Transform,
22};
23
24use super::color::{to_u8, CmykCache, ColorSpace};
25use super::font::{FontCache, LoadedFont};
26use super::function::Function;
27use super::geom::{Box2, Mat};
28use super::image;
29use super::objects::{
30    as_dict, as_stream, deref, get, get_bool, get_dict, get_int, get_name, get_num, name, num,
31    nums, resource,
32};
33
34const MAX_OPS: usize = 2_000_000;
35const MAX_DEPTH: usize = 14;
36
37/// A mesh vertex: device point and RGB.
38type Vertex = ((f64, f64), [f64; 3]);
39/// A flat-shaded mesh triangle (types 4/5): corners and their mean colour.
40type Triangle = ([(f64, f64); 3], [f64; 3]);
41/// A flat-shaded Coons/tensor patch (types 6/7): its boundary and mean colour.
42type Patch = (Vec<(f64, f64)>, [f64; 3]);
43
44#[derive(Clone)]
45struct TextState {
46    font: Option<Rc<LoadedFont>>,
47    size: f64,
48    char_spacing: f64,
49    word_spacing: f64,
50    hscale: f64,
51    leading: f64,
52    rise: f64,
53    render_mode: i64,
54}
55
56#[derive(Clone)]
57struct GState {
58    ctm: Mat,
59    fill_cs: ColorSpace,
60    stroke_cs: ColorSpace,
61    /// Device RGB, `None` = paints nothing (Separation /None, an unresolved pattern).
62    fill_rgb: Option<[f64; 3]>,
63    stroke_rgb: Option<[f64; 3]>,
64    /// A pattern selected with `scn` / `SCN` (`/Pattern` colour space).
65    fill_pattern: Option<Object>,
66    stroke_pattern: Option<Object>,
67    line_width: f64,
68    line_cap: LineCap,
69    line_join: LineJoin,
70    miter_limit: f64,
71    dash: Option<(Vec<f64>, f64)>,
72    fill_alpha: f64,
73    stroke_alpha: f64,
74    blend: BlendMode,
75    /// The clip: an axis-aligned rectangle (device space) when nothing else
76    /// has been intersected, and a coverage mask once a shape has.
77    clip_box: Box2,
78    clip_mask: Option<Rc<Mask>>,
79    text: TextState,
80    /// An uncoloured tiling pattern's cell: colour operators are ignored.
81    fixed_color: bool,
82    /// The constant alpha and blend mode in force at the `Do` of the
83    /// enclosing transparency group(s), applied to everything drawn inside
84    /// (docling-parse's `enter_transparency_group`: the group is not
85    /// composited as a unit, its parameters are pushed down instead).
86    group_alpha: f64,
87    group_blend: BlendMode,
88}
89
90impl GState {
91    fn eff_fill_alpha(&self) -> f64 {
92        self.fill_alpha * self.group_alpha
93    }
94    fn eff_stroke_alpha(&self) -> f64 {
95        self.stroke_alpha * self.group_alpha
96    }
97    /// Content that does not blend on its own inherits the group's mode.
98    fn eff_blend(&self) -> BlendMode {
99        if self.blend == BlendMode::SourceOver {
100            self.group_blend
101        } else {
102            self.blend
103        }
104    }
105}
106
107/// The caches one document's renders share: parsed fonts, the CMYK
108/// conversion table and decoded image samples. The pipeline renders every
109/// page twice (the layout scale and the OCR scale), so decoding a page's
110/// photographs once pays for itself; the store is bounded by
111/// [`IMAGE_BUDGET`] bytes and cleared wholesale when it overflows.
112pub struct Shared {
113    fonts: RefCell<FontCache>,
114    cmyk: RefCell<CmykCache>,
115    images: RefCell<ImageStore>,
116    /// Images drawn as a placeholder (or not drawn) since the last
117    /// [`super::Renderer::take_omissions`] (#916).
118    omissions: RefCell<Vec<super::Omission>>,
119    /// docling-parse's `bitmap_target_pixels_per_unit`: the resolution, in
120    /// pixels per PDF unit, a JPEG needs to be decoded at for the page it is
121    /// drawn on ([`image::codec_reduction_shift`]). docling renders with
122    /// `render_scale` 1.0 and re-renders the same decoders at the model
123    /// scales, so 1.0 is the pipeline's value whatever the canvas scale;
124    /// `0.0` disables the reduced decode (every image at full size).
125    bitmap_hint: f64,
126}
127
128impl Default for Shared {
129    fn default() -> Self {
130        Shared {
131            fonts: RefCell::default(),
132            cmyk: RefCell::default(),
133            images: RefCell::default(),
134            omissions: RefCell::default(),
135            bitmap_hint: 1.0,
136        }
137    }
138}
139
140impl Shared {
141    /// Caches for a renderer decoding its JPEGs for `bitmap_hint` pixels per
142    /// PDF unit (see the field).
143    pub fn with_bitmap_hint(bitmap_hint: f64) -> Shared {
144        Shared {
145            bitmap_hint,
146            ..Shared::default()
147        }
148    }
149
150    /// Drain what the renders since the last call left out.
151    pub fn take_omissions(&self) -> Vec<super::Omission> {
152        std::mem::take(&mut *self.omissions.borrow_mut())
153    }
154
155    fn omit(&self, id: Option<ObjectId>, rect: [f64; 4], reason: String) {
156        self.omissions.borrow_mut().push(super::Omission {
157            object: id,
158            rect,
159            reason,
160        });
161    }
162
163    /// The renderer's default `bitmap_target_pixels_per_unit`.
164    pub fn bitmap_hint(&self) -> f64 {
165        self.bitmap_hint
166    }
167}
168
169/// Decoded image samples per source stream (`image::load`'s result), by
170/// (object id, reduction shift).
171#[derive(Default)]
172struct ImageStore {
173    by_id: HashMap<(ObjectId, u32), Rc<image::LoadedImage>>,
174    bytes: usize,
175}
176
177/// The decoded-sample budget of one document's image store (256 MB): a
178/// scanned book's pages are ~8 MB each at 300 dpi, so the two-scale render
179/// of a page always hits, and a document that overflows merely re-decodes.
180const IMAGE_BUDGET: usize = 256 << 20;
181
182impl Shared {
183    fn font(&self, doc: &Document, obj: &Object) -> Option<Rc<LoadedFont>> {
184        self.fonts.borrow_mut().get(doc, obj)
185    }
186
187    /// `image::load` memoised by object id (inline and direct images are
188    /// decoded every time).
189    fn load_image(
190        &self,
191        doc: &Document,
192        stream: &lopdf::Stream,
193        id: Option<ObjectId>,
194        res: Option<&Dictionary>,
195        reduction_shift: u32,
196    ) -> Result<Rc<image::LoadedImage>, String> {
197        if let Some(id) = id {
198            if let Some(img) = self.images.borrow().by_id.get(&(id, reduction_shift)) {
199                return Ok(img.clone());
200            }
201        }
202        let img = Rc::new(image::load(doc, stream, res, reduction_shift)?);
203        if let Some(id) = id {
204            let mut store = self.images.borrow_mut();
205            let bytes = img.bytes();
206            if store.bytes + bytes > IMAGE_BUDGET {
207                store.by_id.clear();
208                store.bytes = 0;
209            }
210            if bytes <= IMAGE_BUDGET {
211                store.bytes += bytes;
212                store.by_id.insert((id, reduction_shift), img.clone());
213            }
214        }
215        Ok(img)
216    }
217}
218
219pub struct Interp<'a> {
220    doc: &'a Document,
221    canvas: Pixmap,
222    /// Device box of the whole canvas.
223    device: Box2,
224    /// Per-document caches, shared by every render of the document.
225    shared: Rc<Shared>,
226    /// Images rasterized for this canvas, by (object id, reduction, fill
227    /// colour for stencils).
228    images: HashMap<(ObjectId, u32, u32, [u8; 3]), Rc<image::DecodedImage>>,
229    /// Rectangle clip masks by rounded coordinates (many text objects share one).
230    rect_masks: HashMap<[i32; 4], Rc<Mask>>,
231    /// Shape clip masks by (path hash, parent mask, rule): a page that sets
232    /// the same rounded frame before each of its figures builds it once.
233    shape_masks: HashMap<(u64, usize, bool), Rc<Mask>>,
234    ops: usize,
235    /// Fonts that drew a blue fallback box at least once (warned once).
236    warned_no_face: bool,
237    /// Type 3 glyph procedures being run, to stop recursion.
238    type3_depth: usize,
239    /// The page's base CTM: pattern space (8.7.3.1).
240    base: Mat,
241    /// `bitmap_target_pixels_per_unit` for this render (see
242    /// [`Shared::bitmap_hint`]): the model-input renders take docling's 1.0,
243    /// a bitmap kept for OCR or handed to a caller takes 0.0 (full size).
244    bitmap_hint: f64,
245}
246
247/// One painted sub-path being built (user space, transformed at paint time).
248struct PathState {
249    builder: PathBuilder,
250    /// The current point and the sub-path start in user space.
251    current: Option<(f64, f64)>,
252    start: Option<(f64, f64)>,
253    /// `re` operands seen so far, when the path is nothing but rectangles.
254    rects: Vec<[f64; 4]>,
255    only_rects: bool,
256    pending_clip: Option<FillRule>,
257    empty: bool,
258}
259
260impl PathState {
261    fn new() -> PathState {
262        PathState {
263            builder: PathBuilder::new(),
264            current: None,
265            start: None,
266            rects: Vec::new(),
267            only_rects: true,
268            pending_clip: None,
269            empty: true,
270        }
271    }
272}
273
274impl<'a> Interp<'a> {
275    /// A white canvas of `width` × `height` device pixels.
276    pub fn new(
277        doc: &'a Document,
278        width: u32,
279        height: u32,
280        shared: Rc<Shared>,
281        bitmap_hint: f64,
282    ) -> Option<Interp<'a>> {
283        let mut canvas = Pixmap::new(width, height)?;
284        canvas.fill(tiny_skia::Color::WHITE);
285        Some(Interp {
286            doc,
287            canvas,
288            device: Box2::new(0.0, 0.0, f64::from(width), f64::from(height)),
289            shared,
290            bitmap_hint,
291            images: HashMap::new(),
292            rect_masks: HashMap::new(),
293            shape_masks: HashMap::new(),
294            ops: 0,
295            warned_no_face: false,
296            type3_depth: 0,
297            base: Mat::IDENTITY,
298        })
299    }
300
301    pub fn into_canvas(self) -> Pixmap {
302        self.canvas
303    }
304
305    fn initial_state(&self, ctm: Mat) -> GState {
306        GState {
307            ctm,
308            fill_cs: ColorSpace::DeviceGray,
309            stroke_cs: ColorSpace::DeviceGray,
310            fill_rgb: Some([0.0, 0.0, 0.0]),
311            stroke_rgb: Some([0.0, 0.0, 0.0]),
312            fill_pattern: None,
313            stroke_pattern: None,
314            line_width: 1.0,
315            line_cap: LineCap::Butt,
316            line_join: LineJoin::Miter,
317            miter_limit: 10.0,
318            dash: None,
319            fill_alpha: 1.0,
320            stroke_alpha: 1.0,
321            blend: BlendMode::SourceOver,
322            clip_box: self.device,
323            clip_mask: None,
324            text: TextState {
325                font: None,
326                size: 0.0,
327                char_spacing: 0.0,
328                word_spacing: 0.0,
329                hscale: 1.0,
330                leading: 0.0,
331                rise: 0.0,
332                render_mode: 0,
333            },
334            fixed_color: false,
335            group_alpha: 1.0,
336            group_blend: BlendMode::SourceOver,
337        }
338    }
339
340    /// Draw a page's content under `base` (user space → device).
341    pub fn run_page(&mut self, content: &[u8], resources: Option<&Dictionary>, base: Mat) {
342        self.base = base;
343        let st = self.initial_state(base);
344        self.run(content, resources, st, 0);
345    }
346
347    /// Draw the page's Widget annotations (`/AP /N`, honouring `/AS` and the
348    /// Hidden / NoView flags) — what docling-parse renders of the annotations.
349    pub fn run_widgets(&mut self, page: &Dictionary, base: Mat) {
350        let doc = self.doc;
351        let Some(Object::Array(annots)) = get(doc, page, b"Annots") else {
352            return;
353        };
354        for a in annots {
355            let Some(ad) = as_dict(doc, a) else { continue };
356            if get_name(doc, ad, b"Subtype") != Some(b"Widget") {
357                continue;
358            }
359            let flags = get_int(doc, ad, b"F").unwrap_or(0);
360            if flags & 2 != 0 || flags & 32 != 0 {
361                continue;
362            }
363            let Some(rect) = get(doc, ad, b"Rect")
364                .and_then(|o| nums(doc, o))
365                .filter(|r| r.len() == 4)
366            else {
367                continue;
368            };
369            let Some(ap) = get_dict(doc, ad, b"AP") else {
370                continue;
371            };
372            let Some(n) = get(doc, ap, b"N") else {
373                continue;
374            };
375            let stream = match n {
376                Object::Stream(s) => Some(s),
377                Object::Dictionary(states) => {
378                    let as_name = get_name(doc, ad, b"AS");
379                    match as_name {
380                        Some(st) => states.get(st).ok().and_then(|o| as_stream(doc, o)),
381                        None if states.len() == 1 => {
382                            states.iter().next().and_then(|(_, o)| as_stream(doc, o))
383                        }
384                        None => None,
385                    }
386                }
387                _ => None,
388            };
389            let Some(stream) = stream else { continue };
390            // 12.5.5: the form's BBox through its Matrix, fitted to Rect.
391            let bbox = get(doc, &stream.dict, b"BBox")
392                .and_then(|o| nums(doc, o))
393                .filter(|b| b.len() == 4);
394            let matrix = get(doc, &stream.dict, b"Matrix")
395                .and_then(|o| nums(doc, o))
396                .and_then(|v| Mat::from_slice(&v))
397                .unwrap_or(Mat::IDENTITY);
398            let rx0 = rect[0].min(rect[2]);
399            let ry0 = rect[1].min(rect[3]);
400            let rx1 = rect[0].max(rect[2]);
401            let ry1 = rect[1].max(rect[3]);
402            let a = match bbox {
403                Some(b) => {
404                    let tb = Box2::new(b[0], b[1], b[2], b[3]).transformed(matrix);
405                    let sx = if tb.width() > 1e-9 {
406                        (rx1 - rx0) / tb.width()
407                    } else {
408                        1.0
409                    };
410                    let sy = if tb.height() > 1e-9 {
411                        (ry1 - ry0) / tb.height()
412                    } else {
413                        1.0
414                    };
415                    Mat::new(sx, 0.0, 0.0, sy, rx0 - tb.x0 * sx, ry0 - tb.y0 * sy)
416                }
417                None => Mat::IDENTITY,
418            };
419            let mut st = self.initial_state(a.then(base));
420            st.clip_box = self.device;
421            self.draw_form(stream, &st, None, 1);
422        }
423    }
424
425    fn run(&mut self, content: &[u8], resources: Option<&Dictionary>, init: GState, depth: usize) {
426        if depth > MAX_DEPTH {
427            return;
428        }
429        // Inline images and `d0`/`d1` go through the pre-pass (lopdf's
430        // lexer drops or splits them).
431        let prepared = super::prepass::prepare(content, self.doc, resources);
432        let Ok(ops) = lopdf::content::Content::decode(&prepared.content) else {
433            return;
434        };
435        let inline = &prepared.inline;
436        let doc = self.doc;
437        let mut stack: Vec<GState> = Vec::new();
438        let mut st = init.clone();
439        let mut path = PathState::new();
440        // Text object state.
441        let mut tm = Mat::IDENTITY;
442        let mut tlm = Mat::IDENTITY;
443        let mut compat = 0usize;
444        for op in &ops.operations {
445            self.ops += 1;
446            if self.ops > MAX_OPS {
447                return;
448            }
449            let args = &op.operands;
450            let n = |i: usize| args.get(i).and_then(num).unwrap_or(0.0);
451            match op.operator.as_str() {
452                // --- graphics state ------------------------------------------
453                "q" => {
454                    stack.push(st.clone());
455                    if stack.len() > 64 {
456                        stack.remove(0);
457                    }
458                }
459                "Q" => {
460                    if let Some(s) = stack.pop() {
461                        st = s;
462                    }
463                }
464                "cm" => {
465                    if args.len() >= 6 {
466                        let v: Vec<f64> = (0..6).map(n).collect();
467                        if let Some(m) = Mat::from_slice(&v) {
468                            st.ctm = m.then(st.ctm);
469                        }
470                    }
471                }
472                "w" => st.line_width = n(0).abs(),
473                "J" => {
474                    st.line_cap = match n(0) as i64 {
475                        1 => LineCap::Round,
476                        2 => LineCap::Square,
477                        _ => LineCap::Butt,
478                    }
479                }
480                "j" => {
481                    st.line_join = match n(0) as i64 {
482                        1 => LineJoin::Round,
483                        2 => LineJoin::Bevel,
484                        _ => LineJoin::Miter,
485                    }
486                }
487                "M" => st.miter_limit = n(0).max(1.0),
488                "d" => {
489                    let arr: Vec<f64> = args
490                        .first()
491                        .and_then(|o| nums(doc, o))
492                        .unwrap_or_default()
493                        .into_iter()
494                        .filter(|v| v.is_finite() && *v >= 0.0)
495                        .collect();
496                    st.dash = if arr.is_empty() || arr.iter().all(|v| *v <= 0.0) {
497                        None
498                    } else {
499                        Some((arr, n(1)))
500                    };
501                }
502                "ri" | "i" => {}
503                "gs" => {
504                    if let Some(gs) = args
505                        .first()
506                        .and_then(name)
507                        .and_then(|nm| resource(doc, resources, b"ExtGState", nm))
508                        .and_then(|o| as_dict(doc, o))
509                    {
510                        self.apply_extgstate(&mut st, gs, resources);
511                    }
512                }
513                // --- path construction ---------------------------------------
514                "m" => {
515                    if args.len() >= 2 {
516                        let (x, y) = (n(0), n(1));
517                        path.builder.move_to(x as f32, y as f32);
518                        path.current = Some((x, y));
519                        path.start = Some((x, y));
520                        path.only_rects = false;
521                        path.empty = false;
522                    }
523                }
524                "l" => {
525                    if args.len() >= 2 {
526                        let (x, y) = (n(0), n(1));
527                        if path.current.is_none() {
528                            path.builder.move_to(x as f32, y as f32);
529                            path.start = Some((x, y));
530                        } else {
531                            path.builder.line_to(x as f32, y as f32);
532                        }
533                        path.current = Some((x, y));
534                        path.only_rects = false;
535                        path.empty = false;
536                    }
537                }
538                "c" | "v" | "y" => {
539                    let cur = path.current.unwrap_or((n(0), n(1)));
540                    let (x1, y1, x2, y2, x3, y3) = match op.operator.as_str() {
541                        "c" if args.len() >= 6 => (n(0), n(1), n(2), n(3), n(4), n(5)),
542                        "v" if args.len() >= 4 => (cur.0, cur.1, n(0), n(1), n(2), n(3)),
543                        "y" if args.len() >= 4 => (n(0), n(1), n(2), n(3), n(2), n(3)),
544                        _ => continue,
545                    };
546                    if path.current.is_none() {
547                        path.builder.move_to(cur.0 as f32, cur.1 as f32);
548                        path.start = Some(cur);
549                    }
550                    path.builder.cubic_to(
551                        x1 as f32, y1 as f32, x2 as f32, y2 as f32, x3 as f32, y3 as f32,
552                    );
553                    path.current = Some((x3, y3));
554                    path.only_rects = false;
555                    path.empty = false;
556                }
557                "h" => {
558                    if path.current.is_some() {
559                        path.builder.close();
560                        path.current = path.start;
561                    }
562                }
563                "re" => {
564                    if args.len() >= 4 {
565                        let (x, y, w, h) = (n(0), n(1), n(2), n(3));
566                        path.builder.move_to(x as f32, y as f32);
567                        path.builder.line_to((x + w) as f32, y as f32);
568                        path.builder.line_to((x + w) as f32, (y + h) as f32);
569                        path.builder.line_to(x as f32, (y + h) as f32);
570                        path.builder.close();
571                        path.current = Some((x, y));
572                        path.start = Some((x, y));
573                        path.rects.push([x, y, w, h]);
574                        path.empty = false;
575                    }
576                }
577                // --- path painting -------------------------------------------
578                "S" | "s" | "f" | "F" | "f*" | "B" | "B*" | "b" | "b*" | "n" => {
579                    let o = op.operator.as_str();
580                    if matches!(o, "s" | "b" | "b*") && path.current.is_some() {
581                        path.builder.close();
582                    }
583                    let rule = if o.ends_with('*') {
584                        FillRule::EvenOdd
585                    } else {
586                        FillRule::Winding
587                    };
588                    let fill = matches!(o, "f" | "F" | "f*" | "B" | "B*" | "b" | "b*");
589                    let stroke = matches!(o, "S" | "s" | "B" | "B*" | "b" | "b*");
590                    let mut finished = std::mem::replace(&mut path, PathState::new());
591                    let user_path =
592                        std::mem::replace(&mut finished.builder, PathBuilder::new()).finish();
593                    if let Some(up) = &user_path {
594                        if let Some(dev) = up.clone().transform(st.ctm.to_ts()) {
595                            if fill {
596                                self.fill_device_path(&dev, rule, &st, resources, false);
597                            }
598                            if stroke {
599                                self.stroke_device_path(&dev, up, &st, resources);
600                            }
601                        }
602                    }
603                    if let Some(clip_rule) = finished.pending_clip {
604                        crate::timing::timed("render.apply_clip", || {
605                            self.apply_clip(&mut st, user_path.as_ref(), &finished, clip_rule)
606                        });
607                    }
608                }
609                "W" => path.pending_clip = Some(FillRule::Winding),
610                "W*" => path.pending_clip = Some(FillRule::EvenOdd),
611                // --- colour ----------------------------------------------------
612                "CS" | "cs" => {
613                    if st.fixed_color {
614                        continue;
615                    }
616                    let cs = args
617                        .first()
618                        .and_then(|o| ColorSpace::parse(doc, o, resources))
619                        .unwrap_or(ColorSpace::DeviceGray);
620                    let initial = cs.initial();
621                    let rgb = match cs {
622                        ColorSpace::Pattern(_) => None,
623                        _ => cs.to_rgb(&initial),
624                    };
625                    if op.operator == "cs" {
626                        st.fill_cs = cs;
627                        st.fill_rgb = rgb;
628                        st.fill_pattern = None;
629                    } else {
630                        st.stroke_cs = cs;
631                        st.stroke_rgb = rgb;
632                        st.stroke_pattern = None;
633                    }
634                }
635                "SC" | "SCN" | "sc" | "scn" => {
636                    if st.fixed_color {
637                        continue;
638                    }
639                    let is_fill = op.operator.starts_with('s');
640                    let cs = if is_fill { &st.fill_cs } else { &st.stroke_cs };
641                    let (rgb, pattern) = match cs {
642                        ColorSpace::Pattern(base) => {
643                            let pat_name = args.last().and_then(name);
644                            let pat = pat_name
645                                .and_then(|nm| resource(doc, resources, b"Pattern", nm))
646                                .cloned();
647                            // An uncoloured pattern's colour operands in the base space.
648                            let comps: Vec<f64> = args.iter().filter_map(num).collect();
649                            let rgb = match (base, comps.is_empty()) {
650                                (Some(b), false) => b.to_rgb(&comps),
651                                _ => Some([0.5, 0.5, 0.5]),
652                            };
653                            (rgb, pat)
654                        }
655                        cs => {
656                            let comps: Vec<f64> = args.iter().filter_map(num).collect();
657                            if comps.is_empty() {
658                                continue;
659                            }
660                            (cs.to_rgb(&comps), None)
661                        }
662                    };
663                    if is_fill {
664                        st.fill_rgb = rgb;
665                        st.fill_pattern = pattern;
666                    } else {
667                        st.stroke_rgb = rgb;
668                        st.stroke_pattern = pattern;
669                    }
670                }
671                "g" | "G" | "rg" | "RG" | "k" | "K" => {
672                    if st.fixed_color {
673                        continue;
674                    }
675                    let cs = match op.operator.as_str() {
676                        "g" | "G" => ColorSpace::DeviceGray,
677                        "rg" | "RG" => ColorSpace::DeviceRGB,
678                        _ => ColorSpace::DeviceCMYK,
679                    };
680                    let comps: Vec<f64> = args.iter().filter_map(num).collect();
681                    let rgb = cs.to_rgb(&comps);
682                    if op
683                        .operator
684                        .chars()
685                        .next()
686                        .is_some_and(|c| c.is_ascii_lowercase())
687                    {
688                        st.fill_cs = cs;
689                        st.fill_rgb = rgb;
690                        st.fill_pattern = None;
691                    } else {
692                        st.stroke_cs = cs;
693                        st.stroke_rgb = rgb;
694                        st.stroke_pattern = None;
695                    }
696                }
697                // --- text --------------------------------------------------------
698                "BT" => {
699                    tm = Mat::IDENTITY;
700                    tlm = Mat::IDENTITY;
701                }
702                "ET" => {}
703                "Tc" => st.text.char_spacing = n(0),
704                "Tw" => st.text.word_spacing = n(0),
705                "Tz" => st.text.hscale = n(0) / 100.0,
706                "TL" => st.text.leading = n(0),
707                "Ts" => st.text.rise = n(0),
708                "Tr" => st.text.render_mode = n(0) as i64,
709                "Tf" => {
710                    st.text.size = n(1);
711                    st.text.font = args
712                        .first()
713                        .and_then(name)
714                        .and_then(|nm| resource(doc, resources, b"Font", nm))
715                        .and_then(|o| self.shared.font(doc, o));
716                    if st.text.font.is_none() {
717                        // A missing font resource: Helvetica-like fallback so the
718                        // text still lands on the page.
719                        let mut d = Dictionary::new();
720                        d.set("BaseFont", Object::Name(b"Helvetica".to_vec()));
721                        st.text.font = self.shared.font(doc, &Object::Dictionary(d));
722                    }
723                }
724                "Td" => {
725                    tlm = Mat::translate(n(0), n(1)).then(tlm);
726                    tm = tlm;
727                }
728                "TD" => {
729                    st.text.leading = -n(1);
730                    tlm = Mat::translate(n(0), n(1)).then(tlm);
731                    tm = tlm;
732                }
733                "Tm" => {
734                    if args.len() >= 6 {
735                        let v: Vec<f64> = (0..6).map(n).collect();
736                        if let Some(m) = Mat::from_slice(&v) {
737                            tlm = m;
738                            tm = tlm;
739                        }
740                    }
741                }
742                "T*" => {
743                    tlm = Mat::translate(0.0, -st.text.leading).then(tlm);
744                    tm = tlm;
745                }
746                "Tj" | "'" | "\"" => {
747                    if op.operator != "Tj" {
748                        if op.operator == "\"" && args.len() >= 3 {
749                            st.text.word_spacing = n(0);
750                            st.text.char_spacing = n(1);
751                        }
752                        tlm = Mat::translate(0.0, -st.text.leading).then(tlm);
753                        tm = tlm;
754                    }
755                    if let Some(Object::String(s, _)) = args.last() {
756                        self.show_text(s, &mut tm, &st, resources, depth);
757                    }
758                }
759                "TJ" => {
760                    if let Some(Object::Array(items)) = args.first() {
761                        for it in items {
762                            match it {
763                                Object::String(s, _) => {
764                                    self.show_text(s, &mut tm, &st, resources, depth)
765                                }
766                                o => {
767                                    if let Some(adj) = num(o) {
768                                        let tx = -adj / 1000.0 * st.text.size * st.text.hscale;
769                                        let vertical =
770                                            st.text.font.as_ref().is_some_and(|f| f.vertical);
771                                        tm = if vertical {
772                                            Mat::translate(0.0, -adj / 1000.0 * st.text.size)
773                                                .then(tm)
774                                        } else {
775                                            Mat::translate(tx, 0.0).then(tm)
776                                        };
777                                    }
778                                }
779                            }
780                        }
781                    }
782                }
783                // Type 3 glyph metrics (rewritten by the pre-pass); a `d1`
784                // glyph is a stencil — its colour operators are ignored and
785                // the text fill colour paints it.
786                "dZero" => {}
787                "dOne" => st.fixed_color = true,
788                // --- XObjects, images, shadings -----------------------------------
789                "Do" => {
790                    if let Some(xobj) = args
791                        .first()
792                        .and_then(name)
793                        .and_then(|nm| resource(doc, resources, b"XObject", nm))
794                    {
795                        let id = match xobj {
796                            Object::Reference(id) => Some(*id),
797                            _ => None,
798                        };
799                        if let Some(stream) = as_stream(doc, xobj) {
800                            match get_name(doc, &stream.dict, b"Subtype") {
801                                Some(b"Image") => crate::timing::timed("render.image", || {
802                                    self.draw_image(stream, id, &st, resources)
803                                }),
804                                Some(b"Form") => self.draw_form(stream, &st, resources, depth + 1),
805                                Some(b"PS") => {}
806                                _ => {
807                                    if stream.dict.has(b"BBox") {
808                                        self.draw_form(stream, &st, resources, depth + 1);
809                                    } else if stream.dict.has(b"Width") {
810                                        self.draw_image(stream, id, &st, resources);
811                                    }
812                                }
813                            }
814                        }
815                    }
816                }
817                "BIX" => {
818                    // An inline image the pre-pass cut out (`/I<n> BIX`).
819                    if let Some(s) = args
820                        .first()
821                        .and_then(super::prepass::inline_index)
822                        .and_then(|n| inline.get(n))
823                    {
824                        self.draw_image(s, None, &st, resources);
825                    }
826                }
827                "sh" => {
828                    if let Some(sh) = args
829                        .first()
830                        .and_then(name)
831                        .and_then(|nm| resource(doc, resources, b"Shading", nm))
832                    {
833                        let sh_obj = deref(doc, sh).clone();
834                        crate::timing::timed("render.sh", || {
835                            self.paint_shading(
836                                &sh_obj,
837                                st.ctm,
838                                &st,
839                                None,
840                                st.eff_fill_alpha(),
841                                true,
842                            )
843                        });
844                    }
845                }
846                "BX" => compat += 1,
847                "EX" => compat = compat.saturating_sub(1),
848                "BMC" | "BDC" | "EMC" | "MP" | "DP" => {}
849                _ => {}
850            }
851        }
852        let _ = compat;
853    }
854
855    // ---------------------------------------------------------------------
856    // ExtGState
857    // ---------------------------------------------------------------------
858
859    fn apply_extgstate(
860        &mut self,
861        st: &mut GState,
862        gs: &Dictionary,
863        resources: Option<&Dictionary>,
864    ) {
865        let doc = self.doc;
866        for (k, v) in gs.iter() {
867            let v = deref(doc, v);
868            match k.as_slice() {
869                b"LW" => {
870                    if let Some(w) = num(v) {
871                        st.line_width = w.abs();
872                    }
873                }
874                b"LC" => {
875                    st.line_cap = match num(v).unwrap_or(0.0) as i64 {
876                        1 => LineCap::Round,
877                        2 => LineCap::Square,
878                        _ => LineCap::Butt,
879                    }
880                }
881                b"LJ" => {
882                    st.line_join = match num(v).unwrap_or(0.0) as i64 {
883                        1 => LineJoin::Round,
884                        2 => LineJoin::Bevel,
885                        _ => LineJoin::Miter,
886                    }
887                }
888                b"ML" => {
889                    if let Some(m) = num(v) {
890                        st.miter_limit = m.max(1.0);
891                    }
892                }
893                b"D" => {
894                    if let Object::Array(a) = v {
895                        let arr: Vec<f64> =
896                            a.first().and_then(|o| nums(doc, o)).unwrap_or_default();
897                        let phase = a.get(1).and_then(|o| num(deref(doc, o))).unwrap_or(0.0);
898                        st.dash = if arr.is_empty() || arr.iter().all(|x| *x <= 0.0) {
899                            None
900                        } else {
901                            Some((arr, phase))
902                        };
903                    }
904                }
905                b"CA" => {
906                    if let Some(a) = num(v) {
907                        st.stroke_alpha = a.clamp(0.0, 1.0);
908                    }
909                }
910                b"ca" => {
911                    if let Some(a) = num(v) {
912                        st.fill_alpha = a.clamp(0.0, 1.0);
913                    }
914                }
915                b"BM" => {
916                    let nm = match v {
917                        Object::Name(n) => Some(n.as_slice()),
918                        Object::Array(a) => a.first().and_then(name),
919                        _ => None,
920                    };
921                    st.blend = match nm {
922                        Some(b"Multiply") => BlendMode::Multiply,
923                        Some(b"Screen") => BlendMode::Screen,
924                        Some(b"Overlay") => BlendMode::Overlay,
925                        Some(b"Darken") => BlendMode::Darken,
926                        Some(b"Lighten") => BlendMode::Lighten,
927                        Some(b"ColorDodge") => BlendMode::ColorDodge,
928                        Some(b"ColorBurn") => BlendMode::ColorBurn,
929                        Some(b"HardLight") => BlendMode::HardLight,
930                        Some(b"SoftLight") => BlendMode::SoftLight,
931                        Some(b"Difference") => BlendMode::Difference,
932                        Some(b"Exclusion") => BlendMode::Exclusion,
933                        Some(b"Hue") => BlendMode::Hue,
934                        Some(b"Saturation") => BlendMode::Saturation,
935                        Some(b"Color") => BlendMode::Color,
936                        Some(b"Luminosity") => BlendMode::Luminosity,
937                        _ => BlendMode::SourceOver,
938                    };
939                }
940                b"Font" => {
941                    if let Object::Array(a) = v {
942                        if let (Some(f), Some(sz)) =
943                            (a.first(), a.get(1).and_then(|o| num(deref(doc, o))))
944                        {
945                            if let Some(font) = self.shared.font(doc, f) {
946                                st.text.font = Some(font);
947                                st.text.size = sz;
948                            }
949                        }
950                    }
951                }
952                _ => {}
953            }
954        }
955        let _ = resources;
956    }
957
958    // ---------------------------------------------------------------------
959    // Clipping
960    // ---------------------------------------------------------------------
961
962    /// Intersect the clip with the just-painted path.
963    fn apply_clip(
964        &mut self,
965        st: &mut GState,
966        user_path: Option<&Path>,
967        ps: &PathState,
968        rule: FillRule,
969    ) {
970        // An empty path clips everything.
971        let Some(up) = user_path else {
972            st.clip_box = Box2::new(0.0, 0.0, 0.0, 0.0);
973            return;
974        };
975        // A single axis-aligned rectangle (the common `re W n`) stays a box.
976        if ps.only_rects && ps.rects.len() == 1 && st.ctm.b.abs() < 1e-9 && st.ctm.c.abs() < 1e-9 {
977            let r = ps.rects[0];
978            let b = Box2::new(r[0], r[1], r[0] + r[2], r[1] + r[3]).transformed(st.ctm);
979            st.clip_box = st.clip_box.intersect(b);
980            if st.clip_box.is_empty() {
981                st.clip_box = Box2::new(0.0, 0.0, 0.0, 0.0);
982            }
983            return;
984        }
985        let Some(dev) = up.clone().transform(st.ctm.to_ts()) else {
986            return;
987        };
988        let bb = dev.bounds();
989        let pb = Box2::new(
990            f64::from(bb.left()),
991            f64::from(bb.top()),
992            f64::from(bb.right()),
993            f64::from(bb.bottom()),
994        );
995        // A rectangle drawn with m/l/l/l/h (what most producers emit) is a
996        // box clip too: every vertex sits on a corner of the bounding box.
997        if device_path_is_rect(&dev) {
998            st.clip_box = st.clip_box.intersect(pb);
999            if st.clip_box.is_empty() {
1000                st.clip_box = Box2::new(0.0, 0.0, 0.0, 0.0);
1001            }
1002            return;
1003        }
1004        let new_box = st.clip_box.intersect(pb);
1005        if new_box.is_empty() {
1006            st.clip_box = Box2::new(0.0, 0.0, 0.0, 0.0);
1007            st.clip_mask = None;
1008            return;
1009        }
1010        let parent_ptr = st
1011            .clip_mask
1012            .as_ref()
1013            .map(|m| Rc::as_ptr(m) as usize)
1014            .unwrap_or(0);
1015        let key = (
1016            path_hash(&dev, st.clip_box),
1017            parent_ptr,
1018            rule == FillRule::EvenOdd,
1019        );
1020        if let Some(m) = self.shape_masks.get(&key) {
1021            st.clip_mask = Some(m.clone());
1022            st.clip_box = new_box;
1023            return;
1024        }
1025        let mask = crate::timing::timed("render.clip_mask", || {
1026            shape_mask(
1027                self.canvas.width(),
1028                self.canvas.height(),
1029                &dev,
1030                rule,
1031                new_box,
1032                st.clip_mask.as_deref(),
1033            )
1034        });
1035        let Some(mask) = mask else { return };
1036        let mask = Rc::new(mask);
1037        if self.shape_masks.len() > 256 {
1038            self.shape_masks.clear();
1039        }
1040        self.shape_masks.insert(key, mask.clone());
1041        st.clip_mask = Some(mask);
1042        st.clip_box = new_box;
1043    }
1044
1045    /// The mask to draw with: the shape mask, or a cached one for the
1046    /// rectangle clip — none when the clip is the whole canvas, or when
1047    /// `bounds` (the shape's device box) lies inside the rectangle anyway,
1048    /// which is nearly every glyph of a clipped text block.
1049    fn clip_mask_for(&mut self, st: &GState, bounds: Option<tiny_skia::Rect>) -> Option<Rc<Mask>> {
1050        if let Some(m) = &st.clip_mask {
1051            return Some(m.clone());
1052        }
1053        let cb = st.clip_box;
1054        if cb.x0 <= 0.0 && cb.y0 <= 0.0 && cb.x1 >= self.device.x1 && cb.y1 >= self.device.y1 {
1055            return None;
1056        }
1057        if let Some(b) = bounds {
1058            if f64::from(b.left()) >= cb.x0 - 1e-6
1059                && f64::from(b.top()) >= cb.y0 - 1e-6
1060                && f64::from(b.right()) <= cb.x1 + 1e-6
1061                && f64::from(b.bottom()) <= cb.y1 + 1e-6
1062            {
1063                return None;
1064            }
1065        }
1066        let key = [
1067            (cb.x0 * 4.0).round() as i32,
1068            (cb.y0 * 4.0).round() as i32,
1069            (cb.x1 * 4.0).round() as i32,
1070            (cb.y1 * 4.0).round() as i32,
1071        ];
1072        if let Some(m) = self.rect_masks.get(&key) {
1073            return Some(m.clone());
1074        }
1075        let mut m = Mask::new(self.canvas.width(), self.canvas.height())?;
1076        let r = tiny_skia::Rect::from_ltrb(cb.x0 as f32, cb.y0 as f32, cb.x1 as f32, cb.y1 as f32)?;
1077        m.fill_path(
1078            &PathBuilder::from_rect(r),
1079            FillRule::Winding,
1080            true,
1081            Transform::identity(),
1082        );
1083        let m = Rc::new(m);
1084        if self.rect_masks.len() > 64 {
1085            self.rect_masks.clear();
1086        }
1087        self.rect_masks.insert(key, m.clone());
1088        Some(m)
1089    }
1090
1091    fn visible(&self, st: &GState, dev_bounds: tiny_skia::Rect) -> bool {
1092        let b = Box2::new(
1093            f64::from(dev_bounds.left()),
1094            f64::from(dev_bounds.top()),
1095            f64::from(dev_bounds.right()),
1096            f64::from(dev_bounds.bottom()),
1097        );
1098        !st.clip_box.intersect(b).is_empty()
1099            || (b.width() == 0.0 || b.height() == 0.0) && !st.clip_box.is_empty()
1100    }
1101
1102    // ---------------------------------------------------------------------
1103    // Painting
1104    // ---------------------------------------------------------------------
1105
1106    fn paint_for(rgb: [f64; 3], alpha: f64, blend: BlendMode) -> Paint<'static> {
1107        let mut p = Paint::default();
1108        p.set_color_rgba8(to_u8(rgb[0]), to_u8(rgb[1]), to_u8(rgb[2]), to_u8(alpha));
1109        p.anti_alias = true;
1110        p.blend_mode = blend;
1111        p
1112    }
1113
1114    /// Fill a device-space path with the fill colour or pattern.
1115    fn fill_device_path(
1116        &mut self,
1117        dev: &Path,
1118        rule: FillRule,
1119        st: &GState,
1120        resources: Option<&Dictionary>,
1121        is_text: bool,
1122    ) {
1123        if st.eff_fill_alpha() <= 1.0 / 512.0 || !self.visible(st, dev.bounds()) {
1124            return;
1125        }
1126        if let Some(pat) = st.fill_pattern.clone() {
1127            crate::timing::timed("render.pattern_fill", || {
1128                self.fill_with_pattern(dev, rule, &pat, st, resources)
1129            });
1130            return;
1131        }
1132        let Some(rgb) = st.fill_rgb else { return };
1133        let paint = Self::paint_for(rgb, st.eff_fill_alpha(), st.eff_blend());
1134        let mask = self.clip_mask_for(st, Some(dev.bounds()));
1135        let stage = if is_text {
1136            "render.glyph_fill"
1137        } else {
1138            "render.path_fill"
1139        };
1140        crate::timing::timed(stage, || {
1141            self.canvas
1142                .fill_path(dev, &paint, rule, Transform::identity(), mask.as_deref())
1143        });
1144    }
1145
1146    fn stroke_of(&self, st: &GState) -> Stroke {
1147        let scale = st.ctm.mean_scale();
1148        let width = (st.line_width * scale).max(1.0);
1149        let dash = st.dash.as_ref().and_then(|(arr, phase)| {
1150            let mut a: Vec<f32> = arr.iter().map(|v| (v * scale) as f32).collect();
1151            if a.len() % 2 == 1 {
1152                let c = a.clone();
1153                a.extend(c);
1154            }
1155            if a.iter().all(|v| *v <= 0.0) || a.iter().any(|v| !v.is_finite()) {
1156                return None;
1157            }
1158            StrokeDash::new(a, (phase * scale) as f32)
1159        });
1160        Stroke {
1161            width: width as f32,
1162            miter_limit: st.miter_limit as f32,
1163            line_cap: st.line_cap,
1164            line_join: st.line_join,
1165            dash,
1166        }
1167    }
1168
1169    fn stroke_device_path(
1170        &mut self,
1171        dev: &Path,
1172        _user: &Path,
1173        st: &GState,
1174        resources: Option<&Dictionary>,
1175    ) {
1176        if st.eff_stroke_alpha() <= 1.0 / 512.0 {
1177            return;
1178        }
1179        let stroke = self.stroke_of(st);
1180        let bb = dev.bounds();
1181        let grow = stroke.width;
1182        let Some(bb) = tiny_skia::Rect::from_ltrb(
1183            bb.left() - grow,
1184            bb.top() - grow,
1185            bb.right() + grow,
1186            bb.bottom() + grow,
1187        ) else {
1188            return;
1189        };
1190        if !self.visible(st, bb) {
1191            return;
1192        }
1193        if let Some(pat) = st.stroke_pattern.clone() {
1194            // Stroke with a pattern: the stroked outline, filled by the pattern.
1195            if let Some(outline) = dev.stroke(&stroke, 1.0) {
1196                self.fill_with_pattern(&outline, FillRule::Winding, &pat, st, resources);
1197            }
1198            return;
1199        }
1200        let Some(rgb) = st.stroke_rgb else { return };
1201        let paint = Self::paint_for(rgb, st.eff_stroke_alpha(), st.eff_blend());
1202        let mask = self.clip_mask_for(st, Some(bb));
1203        crate::timing::timed("render.stroke", || {
1204            self.canvas
1205                .stroke_path(dev, &paint, &stroke, Transform::identity(), mask.as_deref())
1206        });
1207    }
1208
1209    // ---------------------------------------------------------------------
1210    // Text
1211    // ---------------------------------------------------------------------
1212
1213    fn show_text(
1214        &mut self,
1215        bytes: &[u8],
1216        tm: &mut Mat,
1217        st: &GState,
1218        resources: Option<&Dictionary>,
1219        depth: usize,
1220    ) {
1221        let Some(font) = st.text.font.clone() else {
1222            return;
1223        };
1224        let ts = &st.text;
1225        let mode = ts.render_mode;
1226        let invisible = mode == 3 || mode == 7;
1227        let do_fill = matches!(mode, 0 | 2 | 4 | 6);
1228        let do_stroke = matches!(mode, 1 | 2 | 5 | 6);
1229        for (code, cid, single_byte) in font.decode(bytes) {
1230            let w0 = font.advance(code, cid);
1231            let trm = Mat::new(ts.size * ts.hscale, 0.0, 0.0, ts.size, 0.0, ts.rise)
1232                .then(*tm)
1233                .then(st.ctm);
1234            if !invisible {
1235                if let Some(t3) = &font.type3 {
1236                    self.draw_type3_glyph(&font, t3, code, trm, st, resources, depth);
1237                } else if let Some(glyph) = font.glyph(code, cid) {
1238                    if let Some(dev) = (*glyph).clone().transform(trm.to_ts()) {
1239                        if do_fill {
1240                            self.fill_device_path(&dev, FillRule::Winding, st, resources, true);
1241                        }
1242                        if do_stroke {
1243                            let mut sst = st.clone();
1244                            // Text stroke width is in user space, not text space.
1245                            sst.line_width = st.line_width;
1246                            self.stroke_device_path(&dev, &dev, &sst, resources);
1247                        }
1248                    }
1249                } else if !font.has_program() && (do_fill || do_stroke) {
1250                    self.draw_missing_glyph_box(w0, trm, st);
1251                }
1252            }
1253            let mut adv = if font.vertical {
1254                // Vertical writing: advance down by the default 1 em.
1255                0.0
1256            } else {
1257                w0 * ts.size + ts.char_spacing
1258            };
1259            if single_byte && code == 32 {
1260                adv += ts.word_spacing;
1261            }
1262            if font.vertical {
1263                let ty = -(ts.size
1264                    + ts.char_spacing
1265                    + if single_byte && code == 32 {
1266                        ts.word_spacing
1267                    } else {
1268                        0.0
1269                    });
1270                *tm = Mat::translate(0.0, ty).then(*tm);
1271            } else {
1272                *tm = Mat::translate(adv * ts.hscale, 0.0).then(*tm);
1273            }
1274        }
1275    }
1276
1277    /// docling-parse's fallback for a cell no face could draw: a 0.5 px
1278    /// outline in `#1070C0` around the glyph box.
1279    fn draw_missing_glyph_box(&mut self, w0: f64, trm: Mat, st: &GState) {
1280        if !self.warned_no_face {
1281            self.warned_no_face = true;
1282            eprintln!(
1283                "docling-pdf: no fallback font face on this host — text without an embedded font is drawn as boxes \
1284                 (install Liberation/DejaVu fonts, or point DOCLING_RS_FONT_DIRS at a font directory)"
1285            );
1286        }
1287        let w = if w0 > 0.0 { w0 } else { 0.5 };
1288        let pts = [
1289            trm.apply(0.0, -0.2),
1290            trm.apply(w, -0.2),
1291            trm.apply(w, 0.8),
1292            trm.apply(0.0, 0.8),
1293        ];
1294        let mut pb = PathBuilder::new();
1295        pb.move_to(pts[0].0 as f32, pts[0].1 as f32);
1296        for p in &pts[1..] {
1297            pb.line_to(p.0 as f32, p.1 as f32);
1298        }
1299        pb.close();
1300        let Some(path) = pb.finish() else { return };
1301        let mut paint = Paint::default();
1302        paint.set_color_rgba8(0x10, 0x70, 0xC0, 0xFF);
1303        paint.anti_alias = true;
1304        let stroke = Stroke {
1305            width: 0.5,
1306            ..Stroke::default()
1307        };
1308        let mask = self.clip_mask_for(st, Some(path.bounds()));
1309        self.canvas.stroke_path(
1310            &path,
1311            &paint,
1312            &stroke,
1313            Transform::identity(),
1314            mask.as_deref(),
1315        );
1316    }
1317
1318    #[allow(clippy::too_many_arguments)]
1319    fn draw_type3_glyph(
1320        &mut self,
1321        font: &LoadedFont,
1322        t3: &super::font::Type3,
1323        code: u32,
1324        trm: Mat,
1325        st: &GState,
1326        resources: Option<&Dictionary>,
1327        depth: usize,
1328    ) {
1329        if self.type3_depth > 4 || depth > MAX_DEPTH {
1330            return;
1331        }
1332        let name = font_type3_name(font, code);
1333        let Some(name) = name else { return };
1334        let Some(id) = t3.char_procs.get(&name) else {
1335            return;
1336        };
1337        let Ok(Object::Stream(proc_stream)) = self.doc.get_object(*id) else {
1338            return;
1339        };
1340        let Ok(content) = proc_stream.decompressed_content() else {
1341            return;
1342        };
1343        let mut gst = st.clone();
1344        gst.ctm = t3.font_matrix.then(trm);
1345        // A glyph procedure starts with the text's fill colour; `d1` glyphs
1346        // ignore colour operators (their ink is the fill colour).
1347        let res = t3.resources.as_ref().or(resources);
1348        self.type3_depth += 1;
1349        self.run(&content, res, gst, depth + 1);
1350        self.type3_depth -= 1;
1351    }
1352
1353    // ---------------------------------------------------------------------
1354    // XObjects
1355    // ---------------------------------------------------------------------
1356
1357    fn draw_form(
1358        &mut self,
1359        stream: &lopdf::Stream,
1360        st: &GState,
1361        parent_res: Option<&Dictionary>,
1362        depth: usize,
1363    ) {
1364        if depth > MAX_DEPTH {
1365            return;
1366        }
1367        let doc = self.doc;
1368        let d = &stream.dict;
1369        let mut gst = st.clone();
1370        if get_dict(doc, d, b"Group").is_some() {
1371            // 11.6.6: the group composites as a unit with the alpha and blend
1372            // mode in force at the `Do`; without a group buffer they are
1373            // pushed down onto its contents, and an inner `gs` sets alpha
1374            // relative to them.
1375            gst.group_alpha = st.eff_fill_alpha();
1376            gst.group_blend = st.eff_blend();
1377            gst.fill_alpha = 1.0;
1378            gst.stroke_alpha = 1.0;
1379            gst.blend = BlendMode::SourceOver;
1380        }
1381        if let Some(m) = get(doc, d, b"Matrix")
1382            .and_then(|o| nums(doc, o))
1383            .and_then(|v| Mat::from_slice(&v))
1384        {
1385            gst.ctm = m.then(gst.ctm);
1386        }
1387        if let Some(b) = get(doc, d, b"BBox")
1388            .and_then(|o| nums(doc, o))
1389            .filter(|b| b.len() == 4)
1390        {
1391            // Clip to the BBox in form space.
1392            let mut pb = PathBuilder::new();
1393            let (x0, y0, x1, y1) = (
1394                b[0].min(b[2]),
1395                b[1].min(b[3]),
1396                b[0].max(b[2]),
1397                b[1].max(b[3]),
1398            );
1399            pb.move_to(x0 as f32, y0 as f32);
1400            pb.line_to(x1 as f32, y0 as f32);
1401            pb.line_to(x1 as f32, y1 as f32);
1402            pb.line_to(x0 as f32, y1 as f32);
1403            pb.close();
1404            let ps = PathState {
1405                builder: PathBuilder::new(),
1406                current: None,
1407                start: None,
1408                rects: vec![[x0, y0, x1 - x0, y1 - y0]],
1409                only_rects: true,
1410                pending_clip: None,
1411                empty: false,
1412            };
1413            let up = pb.finish();
1414            self.apply_clip(&mut gst, up.as_ref(), &ps, FillRule::Winding);
1415            if gst.clip_box.is_empty() {
1416                return;
1417            }
1418        }
1419        let res = get_dict(doc, d, b"Resources").or(parent_res);
1420        let Ok(content) = stream.decompressed_content() else {
1421            return;
1422        };
1423        self.run(&content, res, gst, depth);
1424    }
1425
1426    fn draw_image(
1427        &mut self,
1428        stream: &lopdf::Stream,
1429        id: Option<ObjectId>,
1430        st: &GState,
1431        resources: Option<&Dictionary>,
1432    ) {
1433        if st.eff_fill_alpha() <= 1.0 / 512.0 {
1434            return;
1435        }
1436        let doc = self.doc;
1437        // The unit square's device extent decides the reduction factor.
1438        let (bx0, by0, bx1, by1) = st.ctm.unit_bbox();
1439        let dev_box = Box2::new(bx0, by0, bx1, by1);
1440        if st.clip_box.intersect(dev_box).is_empty() {
1441            return;
1442        }
1443        let dst_w = st.ctm.apply_vec(1.0, 0.0);
1444        let dst_h = st.ctm.apply_vec(0.0, 1.0);
1445        let dst_w = dst_w.0.hypot(dst_w.1).max(1.0);
1446        let dst_h = dst_h.0.hypot(dst_h.1).max(1.0);
1447        let target = (dst_w.ceil() as u32, dst_h.ceil() as u32);
1448        let is_mask = get_bool(doc, &stream.dict, b"ImageMask")
1449            .or_else(|| get_bool(doc, &stream.dict, b"IM"))
1450            .unwrap_or(false);
1451        let fill = match (is_mask, st.fill_rgb) {
1452            (true, Some(rgb)) => [to_u8(rgb[0]), to_u8(rgb[1]), to_u8(rgb[2])],
1453            (true, None) => return,
1454            _ => [0, 0, 0],
1455        };
1456        // docling-parse decodes a JPEG no larger than the page needs at its
1457        // bitmap hint (a scan at a quarter for the 72 dpi hint, then blitted
1458        // up onto this canvas): the drawn extent in PDF units against the
1459        // declared size picks the reduced inverse DCT.
1460        let reduction = image::declared_size(doc, &stream.dict)
1461            .map(|(sw, sh)| {
1462                let ux = self.base.a.hypot(self.base.b).max(1e-9);
1463                let uy = self.base.c.hypot(self.base.d).max(1e-9);
1464                image::codec_reduction_shift(
1465                    (bx1 - bx0) / ux,
1466                    (by1 - by0) / uy,
1467                    sw,
1468                    sh,
1469                    self.bitmap_hint,
1470                )
1471            })
1472            .unwrap_or(0);
1473        let key = id.map(|id| (id, target.0, target.1, fill));
1474        let img = match key.and_then(|k| self.images.get(&k).cloned()) {
1475            Some(i) => i,
1476            None => {
1477                let rect = [bx0, by0, bx1, by1];
1478                let mut placeholder = None;
1479                let decoded = match crate::timing::timed("render.image_decode", || {
1480                    let loaded = self
1481                        .shared
1482                        .load_image(doc, stream, id, resources, reduction)?;
1483                    placeholder = loaded.placeholder_reason().map(str::to_string);
1484                    let mut cmyk = self.shared.cmyk.borrow_mut();
1485                    image::rasterize(&loaded, fill, Some(target), &mut cmyk)
1486                }) {
1487                    Ok(d) => Rc::new(d),
1488                    Err(e) => {
1489                        docling_core::debug_log!("docling-pdf render: image skipped ({e})");
1490                        self.shared.omit(id, rect, format!("image not drawn ({e})"));
1491                        return;
1492                    }
1493                };
1494                if let Some(why) = placeholder {
1495                    self.shared.omit(id, rect, why);
1496                }
1497                if let Some(k) = key {
1498                    if self.images.len() > 256 {
1499                        self.images.clear();
1500                    }
1501                    self.images.insert(k, decoded.clone());
1502                }
1503                decoded
1504            }
1505        };
1506        // Image space (w × h, y down) → unit square → device.
1507        let (pw, ph) = (
1508            f64::from(img.pixmap.width()),
1509            f64::from(img.pixmap.height()),
1510        );
1511        docling_core::debug_log!(
1512            "docling-pdf render: image {:?} reduction 1/{} → pixmap {pw}×{ph} (src {}×{}) for {target:?} px",
1513            id,
1514            1u32 << reduction,
1515            img.src_width,
1516            img.src_height
1517        );
1518        let to_unit = Mat::new(1.0 / pw, 0.0, 0.0, -1.0 / ph, 0.0, 1.0);
1519        let m = to_unit.then(st.ctm);
1520        let paint = PixmapPaint {
1521            opacity: st.eff_fill_alpha() as f32,
1522            blend_mode: st.eff_blend(),
1523            quality: if dst_w >= pw && dst_h >= ph && pw * ph < 4.0 {
1524                FilterQuality::Nearest
1525            } else {
1526                FilterQuality::Bilinear
1527            },
1528        };
1529        let img_bounds = tiny_skia::Rect::from_ltrb(
1530            dev_box.x0 as f32,
1531            dev_box.y0 as f32,
1532            dev_box.x1 as f32,
1533            dev_box.y1 as f32,
1534        );
1535        let mask = self.clip_mask_for(st, img_bounds);
1536        self.canvas.draw_pixmap(
1537            0,
1538            0,
1539            img.pixmap.as_ref(),
1540            &paint,
1541            m.to_ts(),
1542            mask.as_deref(),
1543        );
1544    }
1545
1546    // ---------------------------------------------------------------------
1547    // Shadings and patterns
1548    // ---------------------------------------------------------------------
1549
1550    /// Paint a shading dictionary/stream through `matrix` (shading space →
1551    /// device), restricted to `area` (a device path) or to the clip.
1552    fn paint_shading(
1553        &mut self,
1554        sh: &Object,
1555        matrix: Mat,
1556        st: &GState,
1557        area: Option<(&Path, FillRule)>,
1558        alpha: f64,
1559        background: bool,
1560    ) {
1561        let doc = self.doc;
1562        let Some(d) = as_dict(doc, sh) else { return };
1563        let stype = get_int(doc, d, b"ShadingType").unwrap_or(0);
1564        let cs = get(doc, d, b"ColorSpace")
1565            .and_then(|o| ColorSpace::parse(doc, o, None))
1566            .unwrap_or(ColorSpace::DeviceRGB);
1567        let func = d
1568            .get(b"Function")
1569            .ok()
1570            .and_then(|o| Function::parse(doc, o));
1571        let mask = self.clip_mask_for(st, area.map(|(p, _)| p.bounds()));
1572        // The region to paint: the given path, else the clip box.
1573        let region: Path = match area {
1574            Some((p, _)) => p.clone(),
1575            None => {
1576                let cb = st.clip_box;
1577                let Some(r) = tiny_skia::Rect::from_ltrb(
1578                    cb.x0 as f32,
1579                    cb.y0 as f32,
1580                    cb.x1 as f32,
1581                    cb.y1 as f32,
1582                ) else {
1583                    return;
1584                };
1585                PathBuilder::from_rect(r)
1586            }
1587        };
1588        let rule = area.map(|(_, r)| r).unwrap_or(FillRule::Winding);
1589        let _ = background;
1590        match stype {
1591            2 | 3 => {
1592                let Some(coords) = get(doc, d, b"Coords").and_then(|o| nums(doc, o)) else {
1593                    return;
1594                };
1595                let domain = get(doc, d, b"Domain")
1596                    .and_then(|o| nums(doc, o))
1597                    .unwrap_or(vec![0.0, 1.0]);
1598                let extend = get(doc, d, b"Extend")
1599                    .and_then(|o| match o {
1600                        Object::Array(a) => Some(
1601                            a.iter()
1602                                .map(|b| matches!(deref(doc, b), Object::Boolean(true)))
1603                                .collect::<Vec<bool>>(),
1604                        ),
1605                        _ => None,
1606                    })
1607                    .unwrap_or(vec![false, false]);
1608                let (e0, e1) = (
1609                    extend.first().copied().unwrap_or(false),
1610                    extend.get(1).copied().unwrap_or(false),
1611                );
1612                let Some(f) = func.as_ref() else { return };
1613                let stops = sample_stops(f, &cs, &domain, alpha, e0, e1);
1614                if stops.len() < 2 {
1615                    return;
1616                }
1617                let shader = if stype == 2 {
1618                    if coords.len() < 4 {
1619                        return;
1620                    }
1621                    tiny_skia::LinearGradient::new(
1622                        Point::from_xy(coords[0] as f32, coords[1] as f32),
1623                        Point::from_xy(coords[2] as f32, coords[3] as f32),
1624                        stops,
1625                        SpreadMode::Pad,
1626                        matrix.to_ts(),
1627                    )
1628                } else {
1629                    if coords.len() < 6 {
1630                        return;
1631                    }
1632                    tiny_skia::RadialGradient::new(
1633                        Point::from_xy(coords[0] as f32, coords[1] as f32),
1634                        coords[2].max(0.0) as f32,
1635                        Point::from_xy(coords[3] as f32, coords[4] as f32),
1636                        coords[5].max(0.0) as f32,
1637                        stops,
1638                        SpreadMode::Pad,
1639                        matrix.to_ts(),
1640                    )
1641                };
1642                let Some(shader) = shader else { return };
1643                let paint = Paint {
1644                    shader,
1645                    blend_mode: st.eff_blend(),
1646                    anti_alias: true,
1647                    force_hq_pipeline: false,
1648                    colorspace: tiny_skia::ColorSpace::Linear,
1649                };
1650                self.canvas.fill_path(
1651                    &region,
1652                    &paint,
1653                    rule,
1654                    Transform::identity(),
1655                    mask.as_deref(),
1656                );
1657            }
1658            1 => {
1659                // Function-based: sample the domain on a grid, draw as an image.
1660                let domain = get(doc, d, b"Domain")
1661                    .and_then(|o| nums(doc, o))
1662                    .unwrap_or(vec![0.0, 1.0, 0.0, 1.0]);
1663                let fm = get(doc, d, b"Matrix")
1664                    .and_then(|o| nums(doc, o))
1665                    .and_then(|v| Mat::from_slice(&v))
1666                    .unwrap_or(Mat::IDENTITY);
1667                let Some(f) = func.as_ref() else { return };
1668                if domain.len() < 4 {
1669                    return;
1670                }
1671                const N: u32 = 64;
1672                let Some(mut pm) = Pixmap::new(N, N) else {
1673                    return;
1674                };
1675                {
1676                    let px = pm.pixels_mut();
1677                    for j in 0..N {
1678                        for i in 0..N {
1679                            let x = domain[0]
1680                                + (domain[1] - domain[0]) * (f64::from(i) + 0.5) / f64::from(N);
1681                            let y = domain[2]
1682                                + (domain[3] - domain[2]) * (f64::from(j) + 0.5) / f64::from(N);
1683                            let out = f.eval(&[x, y]);
1684                            let rgb = cs.to_rgb(&out).unwrap_or([0.0, 0.0, 0.0]);
1685                            px[(j * N + i) as usize] = tiny_skia::PremultipliedColorU8::from_rgba(
1686                                to_u8(rgb[0]),
1687                                to_u8(rgb[1]),
1688                                to_u8(rgb[2]),
1689                                255,
1690                            )
1691                            .unwrap_or(tiny_skia::PremultipliedColorU8::TRANSPARENT);
1692                        }
1693                    }
1694                }
1695                // pixmap (N×N, y down) → domain rect → shading space → device.
1696                let to_domain = Mat::new(
1697                    (domain[1] - domain[0]) / f64::from(N),
1698                    0.0,
1699                    0.0,
1700                    (domain[3] - domain[2]) / f64::from(N),
1701                    domain[0],
1702                    domain[2],
1703                );
1704                let m = to_domain.then(fm).then(matrix);
1705                let shader = tiny_skia::Pattern::new(
1706                    pm.as_ref(),
1707                    SpreadMode::Pad,
1708                    FilterQuality::Bilinear,
1709                    alpha as f32,
1710                    m.to_ts(),
1711                );
1712                let paint = Paint {
1713                    shader,
1714                    blend_mode: st.eff_blend(),
1715                    anti_alias: true,
1716                    force_hq_pipeline: false,
1717                    colorspace: tiny_skia::ColorSpace::Linear,
1718                };
1719                self.canvas.fill_path(
1720                    &region,
1721                    &paint,
1722                    rule,
1723                    Transform::identity(),
1724                    mask.as_deref(),
1725                );
1726            }
1727            4..=7 => {
1728                let Some(stream) = as_stream(doc, sh) else {
1729                    return;
1730                };
1731                let Ok(data) = stream.decompressed_content() else {
1732                    return;
1733                };
1734                let region_mask = if area.is_some() {
1735                    // Mesh patches are clipped to the fill region through a mask.
1736                    let mut m = match mask.as_deref() {
1737                        Some(m) => m.clone(),
1738                        None => {
1739                            let Some(m) = Mask::new(self.canvas.width(), self.canvas.height())
1740                            else {
1741                                return;
1742                            };
1743                            let mut m = m;
1744                            m.fill_path(
1745                                &PathBuilder::from_rect(
1746                                    tiny_skia::Rect::from_ltrb(
1747                                        0.0,
1748                                        0.0,
1749                                        self.device.x1 as f32,
1750                                        self.device.y1 as f32,
1751                                    )
1752                                    .unwrap(),
1753                                ),
1754                                FillRule::Winding,
1755                                true,
1756                                Transform::identity(),
1757                            );
1758                            m
1759                        }
1760                    };
1761                    m.intersect_path(&region, rule, true, Transform::identity());
1762                    Some(Rc::new(m))
1763                } else {
1764                    mask.clone()
1765                };
1766                self.paint_mesh(
1767                    stype,
1768                    d,
1769                    &data,
1770                    &cs,
1771                    func.as_ref(),
1772                    matrix,
1773                    st,
1774                    region_mask.as_deref(),
1775                    alpha,
1776                );
1777            }
1778            _ => {}
1779        }
1780    }
1781
1782    /// Mesh shadings (types 4–7): each triangle / patch filled flat with the
1783    /// mean of its corner colours — the picture the layout model needs.
1784    #[allow(clippy::too_many_arguments)]
1785    fn paint_mesh(
1786        &mut self,
1787        stype: i64,
1788        d: &Dictionary,
1789        data: &[u8],
1790        cs: &ColorSpace,
1791        func: Option<&Function>,
1792        matrix: Mat,
1793        st: &GState,
1794        mask: Option<&Mask>,
1795        alpha: f64,
1796    ) {
1797        let doc = self.doc;
1798        let bpc = get_int(doc, d, b"BitsPerCoordinate")
1799            .unwrap_or(16)
1800            .clamp(1, 32) as u32;
1801        let bpcomp = get_int(doc, d, b"BitsPerComponent")
1802            .unwrap_or(16)
1803            .clamp(1, 16) as u32;
1804        let bpf = get_int(doc, d, b"BitsPerFlag").unwrap_or(8).clamp(2, 8) as u32;
1805        let decode = get(doc, d, b"Decode")
1806            .and_then(|o| nums(doc, o))
1807            .unwrap_or_default();
1808        let ncomp = if func.is_some() { 1 } else { cs.components() };
1809        if decode.len() < 4 + 2 * ncomp {
1810            return;
1811        }
1812        let mut reader = BitReader::new(data);
1813        let read_val = |r: &mut BitReader, bits: u32, dmin: f64, dmax: f64| -> Option<f64> {
1814            let v = r.read(bits)?;
1815            let max = if bits >= 32 {
1816                u32::MAX as f64
1817            } else {
1818                ((1u64 << bits) - 1) as f64
1819            };
1820            Some(dmin + f64::from(v) * (dmax - dmin) / max)
1821        };
1822        let color_of = |comps: &[f64]| -> [f64; 3] {
1823            let out = match func {
1824                Some(f) => f.eval(&comps[..1]),
1825                None => comps.to_vec(),
1826            };
1827            cs.to_rgb(&out).unwrap_or([0.0, 0.0, 0.0])
1828        };
1829        let mut triangles: Vec<Triangle> = Vec::new();
1830        let mut patches: Vec<Patch> = Vec::new();
1831        let read_vertex = |r: &mut BitReader| -> Option<Vertex> {
1832            let x = read_val(r, bpc, decode[0], decode[1])?;
1833            let y = read_val(r, bpc, decode[2], decode[3])?;
1834            let mut comps = Vec::with_capacity(ncomp);
1835            for c in 0..ncomp {
1836                comps.push(read_val(r, bpcomp, decode[4 + 2 * c], decode[5 + 2 * c])?);
1837            }
1838            Some(((x, y), color_of(&comps)))
1839        };
1840        match stype {
1841            4 => {
1842                let mut prev: Vec<((f64, f64), [f64; 3])> = Vec::new();
1843                let mut count = 0;
1844                while let Some(flag) = reader.read(bpf) {
1845                    let Some(v) = read_vertex(&mut reader) else {
1846                        break;
1847                    };
1848                    reader.align();
1849                    if flag == 0 {
1850                        // Start a new triangle: two more vertices with flags.
1851                        let mut tri = vec![v];
1852                        for _ in 0..2 {
1853                            let _ = reader.read(bpf);
1854                            let Some(v2) = read_vertex(&mut reader) else {
1855                                break;
1856                            };
1857                            reader.align();
1858                            tri.push(v2);
1859                        }
1860                        if tri.len() == 3 {
1861                            prev = tri;
1862                        } else {
1863                            break;
1864                        }
1865                    } else if prev.len() == 3 {
1866                        if flag == 1 {
1867                            prev = vec![prev[1], prev[2], v];
1868                        } else {
1869                            prev = vec![prev[0], prev[2], v];
1870                        }
1871                    } else {
1872                        break;
1873                    }
1874                    let pts = [prev[0].0, prev[1].0, prev[2].0];
1875                    let col = mean3(&[prev[0].1, prev[1].1, prev[2].1]);
1876                    triangles.push((pts, col));
1877                    count += 1;
1878                    if count > 200_000 {
1879                        break;
1880                    }
1881                }
1882            }
1883            5 => {
1884                let per_row = get_int(doc, d, b"VerticesPerRow").unwrap_or(2).max(2) as usize;
1885                let mut rows: Vec<Vec<Vertex>> = Vec::new();
1886                loop {
1887                    let mut row = Vec::with_capacity(per_row);
1888                    for _ in 0..per_row {
1889                        match read_vertex(&mut reader) {
1890                            Some(v) => row.push(v),
1891                            None => break,
1892                        }
1893                    }
1894                    if row.len() < per_row {
1895                        break;
1896                    }
1897                    rows.push(row);
1898                    if rows.len() > 4096 {
1899                        break;
1900                    }
1901                }
1902                for r in 1..rows.len() {
1903                    for c in 1..per_row {
1904                        let (a, b, cc, dd) = (
1905                            rows[r - 1][c - 1],
1906                            rows[r - 1][c],
1907                            rows[r][c - 1],
1908                            rows[r][c],
1909                        );
1910                        triangles.push(([a.0, b.0, cc.0], mean3(&[a.1, b.1, cc.1])));
1911                        triangles.push(([b.0, dd.0, cc.0], mean3(&[b.1, dd.1, cc.1])));
1912                    }
1913                }
1914            }
1915            6 | 7 => {
1916                let npts = if stype == 6 { 12 } else { 16 };
1917                let mut prev_pts: Vec<(f64, f64)> = Vec::new();
1918                let mut prev_cols: Vec<[f64; 3]> = Vec::new();
1919                while let Some(flag) = reader.read(bpf) {
1920                    let (np, nc) = if flag == 0 { (npts, 4) } else { (npts - 4, 2) };
1921                    let mut pts = Vec::with_capacity(16);
1922                    let mut ok = true;
1923                    for _ in 0..np {
1924                        match (
1925                            read_val(&mut reader, bpc, decode[0], decode[1]),
1926                            read_val(&mut reader, bpc, decode[2], decode[3]),
1927                        ) {
1928                            (Some(x), Some(y)) => pts.push((x, y)),
1929                            _ => {
1930                                ok = false;
1931                                break;
1932                            }
1933                        }
1934                    }
1935                    if !ok {
1936                        break;
1937                    }
1938                    let mut cols = Vec::with_capacity(4);
1939                    for _ in 0..nc {
1940                        let mut comps = Vec::with_capacity(ncomp);
1941                        for c in 0..ncomp {
1942                            match read_val(
1943                                &mut reader,
1944                                bpcomp,
1945                                decode[4 + 2 * c],
1946                                decode[5 + 2 * c],
1947                            ) {
1948                                Some(v) => comps.push(v),
1949                                None => {
1950                                    ok = false;
1951                                    break;
1952                                }
1953                            }
1954                        }
1955                        if !ok {
1956                            break;
1957                        }
1958                        cols.push(color_of(&comps));
1959                    }
1960                    if !ok {
1961                        break;
1962                    }
1963                    reader.align();
1964                    // Shared edge from the previous patch (8.7.4.5.7, Table 85).
1965                    let (full_pts, full_cols) = if flag == 0 || prev_pts.len() < 12 {
1966                        if flag != 0 {
1967                            break;
1968                        }
1969                        (pts.clone(), cols.clone())
1970                    } else {
1971                        let p = &prev_pts;
1972                        let edge: [(f64, f64); 4] = match flag {
1973                            1 => [p[3], p[4], p[5], p[6]],
1974                            2 => [p[6], p[7], p[8], p[9]],
1975                            _ => [p[9], p[10], p[11], p[0]],
1976                        };
1977                        let pc = &prev_cols;
1978                        let ec: [[f64; 3]; 2] = match flag {
1979                            1 => [pc[1], pc[2]],
1980                            2 => [pc[2], pc[3]],
1981                            _ => [pc[3], pc[0]],
1982                        };
1983                        let mut fp = edge.to_vec();
1984                        fp.extend(pts.iter().copied());
1985                        let mut fc = ec.to_vec();
1986                        fc.extend(cols.iter().copied());
1987                        (fp, fc)
1988                    };
1989                    if full_pts.len() < 12 || full_cols.len() < 4 {
1990                        break;
1991                    }
1992                    patches.push((full_pts[..12].to_vec(), mean4(&full_cols)));
1993                    prev_pts = full_pts;
1994                    prev_cols = full_cols;
1995                    if patches.len() > 50_000 {
1996                        break;
1997                    }
1998                }
1999            }
2000            _ => {}
2001        }
2002        let ts = matrix.to_ts();
2003        for (pts, col) in &triangles {
2004            let mut pb = PathBuilder::new();
2005            pb.move_to(pts[0].0 as f32, pts[0].1 as f32);
2006            pb.line_to(pts[1].0 as f32, pts[1].1 as f32);
2007            pb.line_to(pts[2].0 as f32, pts[2].1 as f32);
2008            pb.close();
2009            if let Some(p) = pb.finish().and_then(|p| p.transform(ts)) {
2010                let mut paint = Self::paint_for(*col, alpha, st.eff_blend());
2011                paint.anti_alias = false;
2012                self.canvas
2013                    .fill_path(&p, &paint, FillRule::Winding, Transform::identity(), mask);
2014            }
2015        }
2016        for (pts, col) in &patches {
2017            // The boundary: four cubics p0 p1 p2 p3 | p3 p4 p5 p6 | p6 p7 p8 p9 | p9 p10 p11 p0.
2018            let mut pb = PathBuilder::new();
2019            pb.move_to(pts[0].0 as f32, pts[0].1 as f32);
2020            for k in 0..4 {
2021                let (a, b, c) = (
2022                    pts[(3 * k + 1) % 12],
2023                    pts[(3 * k + 2) % 12],
2024                    pts[(3 * k + 3) % 12],
2025                );
2026                pb.cubic_to(
2027                    a.0 as f32, a.1 as f32, b.0 as f32, b.1 as f32, c.0 as f32, c.1 as f32,
2028                );
2029            }
2030            pb.close();
2031            if let Some(p) = pb.finish().and_then(|p| p.transform(ts)) {
2032                let mut paint = Self::paint_for(*col, alpha, st.eff_blend());
2033                paint.anti_alias = false;
2034                self.canvas
2035                    .fill_path(&p, &paint, FillRule::Winding, Transform::identity(), mask);
2036            }
2037        }
2038    }
2039
2040    /// Fill `dev` with a pattern: a shading pattern paints its shading
2041    /// through the path; a tiling pattern renders one cell into a pixmap and
2042    /// repeats it.
2043    fn fill_with_pattern(
2044        &mut self,
2045        dev: &Path,
2046        rule: FillRule,
2047        pat: &Object,
2048        st: &GState,
2049        resources: Option<&Dictionary>,
2050    ) {
2051        let doc = self.doc;
2052        let Some(pd) = as_dict(doc, pat) else { return };
2053        let ptype = get_int(doc, pd, b"PatternType").unwrap_or(2);
2054        let pmatrix = get(doc, pd, b"Matrix")
2055            .and_then(|o| nums(doc, o))
2056            .and_then(|v| Mat::from_slice(&v))
2057            .unwrap_or(Mat::IDENTITY);
2058        // Pattern space is the default space of the page (or form) the
2059        // pattern is a resource of: the base CTM recorded for this stream.
2060        let base = self.pattern_base(st);
2061        let m = pmatrix.then(base);
2062        if ptype == 2 {
2063            let Some(sh) = get(doc, pd, b"Shading") else {
2064                return;
2065            };
2066            let sh = sh.clone();
2067            self.paint_shading(&sh, m, st, Some((dev, rule)), st.eff_fill_alpha(), false);
2068            return;
2069        }
2070        // Tiling pattern.
2071        let Some(stream) = as_stream(doc, pat) else {
2072            return;
2073        };
2074        let Some(bbox) = get(doc, pd, b"BBox")
2075            .and_then(|o| nums(doc, o))
2076            .filter(|b| b.len() == 4)
2077        else {
2078            return;
2079        };
2080        let mut xstep = get_num(doc, pd, b"XStep")
2081            .unwrap_or(bbox[2] - bbox[0])
2082            .abs();
2083        let mut ystep = get_num(doc, pd, b"YStep")
2084            .unwrap_or(bbox[3] - bbox[1])
2085            .abs();
2086        if xstep < 1e-9 {
2087            xstep = (bbox[2] - bbox[0]).abs().max(1e-3);
2088        }
2089        if ystep < 1e-9 {
2090            ystep = (bbox[3] - bbox[1]).abs().max(1e-3);
2091        }
2092        let paint_type = get_int(doc, pd, b"PaintType").unwrap_or(1);
2093        let scale = m.max_scale().max(1e-6);
2094        let cell_w = (xstep * scale).ceil().clamp(1.0, 2048.0);
2095        let cell_h = (ystep * scale).ceil().clamp(1.0, 2048.0);
2096        let s_x = cell_w / xstep;
2097        let s_y = cell_h / ystep;
2098        let (x0, y0) = (bbox[0].min(bbox[2]), bbox[1].min(bbox[3]));
2099        // Pattern space → tile pixmap (y down).
2100        let to_tile = Mat::new(s_x, 0.0, 0.0, -s_y, -x0 * s_x, (y0 + ystep) * s_y);
2101        let Some(mut tile) = Pixmap::new(cell_w as u32, cell_h as u32) else {
2102            return;
2103        };
2104        tile.fill(tiny_skia::Color::TRANSPARENT);
2105        let Ok(content) = stream.decompressed_content() else {
2106            return;
2107        };
2108        let res = get_dict(doc, &stream.dict, b"Resources").or(resources);
2109        // Render the cell with a nested interpreter sharing the font cache.
2110        let mut inner = Interp {
2111            doc,
2112            canvas: tile,
2113            device: Box2::new(0.0, 0.0, cell_w, cell_h),
2114            shared: self.shared.clone(),
2115            images: HashMap::new(),
2116            rect_masks: HashMap::new(),
2117            shape_masks: HashMap::new(),
2118            ops: self.ops,
2119            warned_no_face: self.warned_no_face,
2120            type3_depth: self.type3_depth,
2121            base: to_tile,
2122            bitmap_hint: self.bitmap_hint,
2123        };
2124        let mut gst = inner.initial_state(to_tile);
2125        if paint_type == 2 {
2126            gst.fixed_color = true;
2127            gst.fill_rgb = st.fill_rgb;
2128            gst.stroke_rgb = st.fill_rgb;
2129        }
2130        inner.run(&content, res, gst, MAX_DEPTH - 2);
2131        self.ops = inner.ops;
2132        let tile = inner.canvas;
2133        // tile pixmap → pattern space → device.
2134        let Some(from_tile) = to_tile.invert() else {
2135            return;
2136        };
2137        let shader_m = from_tile.then(m);
2138        let shader = tiny_skia::Pattern::new(
2139            tile.as_ref(),
2140            SpreadMode::Repeat,
2141            FilterQuality::Bilinear,
2142            st.eff_fill_alpha() as f32,
2143            shader_m.to_ts(),
2144        );
2145        let paint = Paint {
2146            shader,
2147            blend_mode: st.eff_blend(),
2148            anti_alias: true,
2149            force_hq_pipeline: false,
2150            colorspace: tiny_skia::ColorSpace::Linear,
2151        };
2152        let mask = self.clip_mask_for(st, Some(dev.bounds()));
2153        self.canvas
2154            .fill_path(dev, &paint, rule, Transform::identity(), mask.as_deref());
2155    }
2156
2157    /// The base transform for pattern space: the page's (or the enclosing
2158    /// form's) default user space. Recorded on the interpreter per stream;
2159    /// here the page base is used for everything, which is exact for page
2160    /// content and the common case for forms.
2161    fn pattern_base(&self, _st: &GState) -> Mat {
2162        self.base
2163    }
2164}
2165
2166/// The coverage mask of a shape clip: `dev` (already in device space)
2167/// rasterized into a fresh mask, cut to `keep` (the new clip box) and
2168/// multiplied by the `parent` mask when the clip nests. Built by hand
2169/// rather than `Mask::intersect_path`: that rasterizes into a canvas-sized
2170/// temporary and multiplies the *whole* canvas, after a full-canvas
2171/// rectangle fill seeded the box clip — three or four passes over 4 MB
2172/// per clip, and a designer's page sets a few hundred clips. Here the only
2173/// full-canvas cost is the allocation; every other pass covers the shape's
2174/// bounding box.
2175fn shape_mask(
2176    w: u32,
2177    h: u32,
2178    dev: &Path,
2179    rule: FillRule,
2180    keep: Box2,
2181    parent: Option<&Mask>,
2182) -> Option<Mask> {
2183    let mut m = Mask::new(w, h)?;
2184    m.fill_path(dev, rule, true, Transform::identity());
2185    let bb = dev.bounds();
2186    let (w, h) = (w as usize, h as usize);
2187    // The rows and columns the shape may have touched.
2188    let bx0 = (bb.left().floor().max(0.0) as usize).min(w);
2189    let by0 = (bb.top().floor().max(0.0) as usize).min(h);
2190    let bx1 = ((bb.right().ceil().max(0.0) as usize) + 1).min(w);
2191    let by1 = ((bb.bottom().ceil().max(0.0) as usize) + 1).min(h);
2192    // The pixels that stay: the shape's box ∩ the clip box. A pixel a box
2193    // edge cuts through keeps the covered fraction (what the anti-aliased
2194    // rectangle mask this replaces gave it).
2195    let kx0 = (keep.x0.floor().max(0.0) as usize).clamp(bx0, bx1);
2196    let ky0 = (keep.y0.floor().max(0.0) as usize).clamp(by0, by1);
2197    let kx1 = (keep.x1.ceil().max(0.0) as usize).clamp(kx0, bx1);
2198    let ky1 = (keep.y1.ceil().max(0.0) as usize).clamp(ky0, by1);
2199    // Coverage of an edge pixel along one axis: the part of [i, i + 1)
2200    // inside [lo, hi).
2201    let edge = |i: usize, lo: f64, hi: f64| -> f64 {
2202        let (a, b) = (i as f64, i as f64 + 1.0);
2203        (b.min(hi) - a.max(lo)).clamp(0.0, 1.0)
2204    };
2205    let fx: Vec<f64> = (kx0..kx1).map(|x| edge(x, keep.x0, keep.x1)).collect();
2206    let plain_x = fx.iter().all(|&f| f >= 1.0);
2207    let data = m.data_mut();
2208    for y in by0..by1 {
2209        let row = &mut data[y * w..(y + 1) * w];
2210        if y < ky0 || y >= ky1 {
2211            row[bx0..bx1].fill(0);
2212            continue;
2213        }
2214        row[bx0..kx0].fill(0);
2215        row[kx1..bx1].fill(0);
2216        let fy = edge(y, keep.y0, keep.y1);
2217        let prow = parent.map(|p| &p.data()[y * w..(y + 1) * w]);
2218        if prow.is_none() && plain_x && fy >= 1.0 {
2219            continue;
2220        }
2221        for x in kx0..kx1 {
2222            let mut c = f64::from(row[x]) * fy * fx[x - kx0];
2223            if let Some(prow) = prow {
2224                c = c * f64::from(prow[x]) / 255.0;
2225            }
2226            row[x] = c.round().clamp(0.0, 255.0) as u8;
2227        }
2228    }
2229    Some(m)
2230}
2231
2232/// A hash of a device path's geometry (and the box it is clipped into).
2233fn path_hash(p: &Path, clip_box: Box2) -> u64 {
2234    use std::hash::{Hash, Hasher};
2235    let mut h = std::collections::hash_map::DefaultHasher::new();
2236    for pt in p.points() {
2237        pt.x.to_bits().hash(&mut h);
2238        pt.y.to_bits().hash(&mut h);
2239    }
2240    for v in p.verbs() {
2241        (*v as u8).hash(&mut h);
2242    }
2243    for v in [clip_box.x0, clip_box.y0, clip_box.x1, clip_box.y1] {
2244        v.to_bits().hash(&mut h);
2245    }
2246    h.finish()
2247}
2248
2249/// One closed sub-path of lines whose every vertex lies on a corner of its
2250/// bounding box — an axis-aligned rectangle (`get_axis_aligned_clip_rect`).
2251fn device_path_is_rect(p: &Path) -> bool {
2252    let b = p.bounds();
2253    if b.width() <= 1e-3 || b.height() <= 1e-3 {
2254        return false;
2255    }
2256    let mut moves = 0;
2257    let mut points = 0;
2258    for seg in p.segments() {
2259        match seg {
2260            tiny_skia::PathSegment::MoveTo(pt) => {
2261                moves += 1;
2262                if moves > 1 || !on_corner(pt, &b) {
2263                    return false;
2264                }
2265                points += 1;
2266            }
2267            tiny_skia::PathSegment::LineTo(pt) => {
2268                if !on_corner(pt, &b) {
2269                    return false;
2270                }
2271                points += 1;
2272            }
2273            tiny_skia::PathSegment::Close => {}
2274            _ => return false,
2275        }
2276    }
2277    (4..=5).contains(&points)
2278}
2279
2280fn on_corner(pt: Point, b: &tiny_skia::Rect) -> bool {
2281    let eps = 1e-3;
2282    let on_x = (pt.x - b.left()).abs() <= eps || (pt.x - b.right()).abs() <= eps;
2283    let on_y = (pt.y - b.top()).abs() <= eps || (pt.y - b.bottom()).abs() <= eps;
2284    on_x && on_y
2285}
2286
2287/// The Type 3 glyph name for a code: through the encoding's `/Differences`.
2288fn font_type3_name(font: &LoadedFont, code: u32) -> Option<String> {
2289    font.type3_glyph_name(code)
2290}
2291
2292fn mean3(c: &[[f64; 3]; 3]) -> [f64; 3] {
2293    [
2294        (c[0][0] + c[1][0] + c[2][0]) / 3.0,
2295        (c[0][1] + c[1][1] + c[2][1]) / 3.0,
2296        (c[0][2] + c[1][2] + c[2][2]) / 3.0,
2297    ]
2298}
2299
2300fn mean4(c: &[[f64; 3]]) -> [f64; 3] {
2301    let n = c.len().max(1) as f64;
2302    let mut out = [0.0; 3];
2303    for col in c {
2304        for k in 0..3 {
2305            out[k] += col[k] / n;
2306        }
2307    }
2308    out
2309}
2310
2311/// Sample a shading function into gradient stops over `[t0, t1]`; a
2312/// non-extended end gets a transparent guard stop just past it, as
2313/// docling-parse does (Blend2D's pad mode is the only one that keeps the
2314/// interior ramp intact).
2315fn sample_stops(
2316    f: &Function,
2317    cs: &ColorSpace,
2318    domain: &[f64],
2319    alpha: f64,
2320    e0: bool,
2321    e1: bool,
2322) -> Vec<GradientStop> {
2323    let (t0, t1) = (
2324        domain.first().copied().unwrap_or(0.0),
2325        domain.get(1).copied().unwrap_or(1.0),
2326    );
2327    const N: usize = 64;
2328    let mut stops = Vec::with_capacity(N + 3);
2329    let a = to_u8(alpha);
2330    let guard = 1.0 / 1024.0;
2331    for i in 0..=N {
2332        let u = i as f64 / N as f64;
2333        let t = t0 + (t1 - t0) * u;
2334        let out = f.eval(&[t]);
2335        let rgb = cs.to_rgb(&out).unwrap_or([0.0, 0.0, 0.0]);
2336        let color = tiny_skia::Color::from_rgba8(to_u8(rgb[0]), to_u8(rgb[1]), to_u8(rgb[2]), a);
2337        let pos = if !e0 && i == 0 {
2338            guard
2339        } else if !e1 && i == N {
2340            1.0 - guard
2341        } else {
2342            u
2343        };
2344        stops.push(GradientStop::new(pos as f32, color));
2345    }
2346    if !e0 {
2347        stops.insert(0, GradientStop::new(0.0, tiny_skia::Color::TRANSPARENT));
2348    }
2349    if !e1 {
2350        stops.push(GradientStop::new(1.0, tiny_skia::Color::TRANSPARENT));
2351    }
2352    stops
2353}
2354
2355struct BitReader<'a> {
2356    data: &'a [u8],
2357    pos: usize,
2358}
2359
2360impl<'a> BitReader<'a> {
2361    fn new(data: &'a [u8]) -> BitReader<'a> {
2362        BitReader { data, pos: 0 }
2363    }
2364
2365    fn read(&mut self, bits: u32) -> Option<u32> {
2366        if self.pos + bits as usize > self.data.len() * 8 {
2367            return None;
2368        }
2369        let mut v: u64 = 0;
2370        for _ in 0..bits {
2371            let byte = self.data[self.pos / 8];
2372            let bit = (byte >> (7 - self.pos % 8)) & 1;
2373            v = (v << 1) | u64::from(bit);
2374            self.pos += 1;
2375        }
2376        Some(v as u32)
2377    }
2378
2379    fn align(&mut self) {
2380        self.pos = self.pos.div_ceil(8) * 8;
2381    }
2382}