Skip to main content

pdf/read/render/
mod.rs

1// Drawing pages (ISO 32000-1, 8 to 11): Document::render gives the page as pixels (sRGB).  The
2// content stream runs through a graphics state (q / Q, cm, the line style, colours in every
3// colour space with ICC profiles, the Default* spaces and the output intent (color.rs), the
4// rendering intent of ri and RI, ExtGState with alpha, blend mode and soft mask), paths are
5// filled with the non-zero or
6// even-odd rule and stroked with caps, joins, miter limit and dashes in user space (also under
7// a non-uniform matrix), clipping paths and text clipping are masks.  Text through the glyph
8// outlines of the embedded fonts (Type 1, CFF, TrueType, OpenType, Type 3) or substitutes
9// (FontSource); every text render mode.  Images with every bit depth and colour space, Decode,
10// stencil masks, colour-key masks, soft masks, the JPEG filter (through img_jpeg) and
11// CCITTFax; shadings of every type (sh and as patterns), tiling patterns coloured and
12// uncoloured; form XObjects, transparency groups and soft masks (luminosity and alpha, with
13// backdrop and transfer function); the annotations' appearances, and for a form field without
14// one (or under NeedAppearances) the appearance edit::form makes from its value; optional content (the
15// default configuration, membership dictionaries); JPXDecode images through img_jp2, JBIG2Decode
16// images through img_jbig2.  Not here: knockout and non-isolated groups (drawn as isolated ones),
17// overprint, halftones, transfer functions outside soft masks.
18//
19//   let doc = read::Document::open(bytes)?;
20//   let page: gfx::Surface = doc.render(0, &RenderOptions { dpi: 150.0, ..Default::default() })?;
21//
22// Untrusted input: the work of a page is bounded (the operators, the pixels painted, forms,
23// patterns, Type 3 glyphs and soft masks inside each other, the pixels of images and layers),
24// a page that needs more gives Error::Limit.
25
26mod canvas;
27mod color;
28mod fax;
29mod fonts;
30mod image;
31mod shade;
32mod type1;
33
34use super::content::Ops;
35use super::object::{Dict, Object, Ref, Stream};
36use super::{Document, Error, Page};
37use alloc::collections::{BTreeMap, BTreeSet};
38use alloc::rc::Rc;
39use alloc::string::String;
40use alloc::vec;
41use alloc::vec::Vec;
42use canvas::{Blend, Clip, Layer, Mask, Put, Rect, Src};
43use color::Cs;
44use core::cell::{OnceCell, RefCell};
45use gfx::dash::{dash_stroke, DStyle};
46use gfx::path::Path;
47use gfx::raster::Raster;
48use gfx::{RULE_EVENODD, RULE_NONZERO};
49
50/// how to draw a page
51#[derive(Clone)]
52pub struct RenderOptions {
53    /// pixels per inch: 72 draws a point as a pixel
54    pub dpi: f64,
55    /// the part of the page image to draw, in pixels: x, y, width, height (None: all of it)
56    pub region: Option<[u32; 4]>,
57    /// the colour under the page, straight 0xAARRGGBB (None: transparent)
58    pub background: Option<u32>,
59    /// draw the annotations' appearances (form fields, stamps, comments)
60    pub annotations: bool,
61    /// fonts for the fonts a document does not embed (None: the system's, text::fontdb)
62    pub fonts: Option<Rc<dyn FontSource>>,
63    /// the largest image to draw, in pixels
64    pub max_pixels: u64,
65}
66
67impl Default for RenderOptions {
68    fn default() -> RenderOptions {
69        RenderOptions { dpi: 72.0, region: None, background: Some(0xFFFF_FFFF), annotations: true, fonts: None, max_pixels: 1 << 28 }
70    }
71}
72
73/// a font a page uses but does not embed
74#[derive(Clone, Debug)]
75pub struct FontQuery<'a> {
76    /// its PostScript name without a subset tag (Helvetica-Bold, ArialMT, ...)
77    pub name: &'a str,
78    pub family: Option<&'a str>,
79    pub bold: bool,
80    pub italic: bool,
81    /// serifs, a fixed pitch, a symbol font (by the descriptor's flags)
82    pub serif: bool,
83    pub fixed: bool,
84    pub symbolic: bool,
85    /// a simple font (one byte per code), not a composite one
86    pub text: bool,
87    /// a composite font of one of Adobe's CJK collections: the language of its text (zh-Hans,
88    /// zh-Hant, ja, ko), so a substitute has its characters (in its forms)
89    pub lang: Option<&'a str>,
90}
91
92/// where substitutes for fonts that are not embedded come from: a TrueType, OpenType or Type 1
93/// file and the face in it
94pub trait FontSource {
95    fn find(&self, q: &FontQuery) -> Option<(Vec<u8>, u32)>;
96}
97
98/// the system's fonts (text::fontdb), searched once: for the 14 standard fonts their
99/// metric-compatible families (URW's Nimbus, Liberation, the Windows fonts), others by name and
100/// flags; a font with a language (`FontQuery::lang`) by its own name, else the system's serif or
101/// sans-serif font for the language (text::fontconf: fontconfig's rules on Linux, Noto Sans CJK
102/// JP for ja, say; the built-in ones elsewhere)
103pub struct SystemFonts {
104    db: RefCell<Option<text::fontdb::FontDb>>,
105    conf: RefCell<Option<text::fontconf::FontConf>>,
106}
107
108impl Default for SystemFonts {
109    fn default() -> SystemFonts {
110        SystemFonts { db: RefCell::new(None), conf: RefCell::new(None) }
111    }
112}
113
114impl SystemFonts {
115    pub fn new() -> SystemFonts {
116        SystemFonts::default()
117    }
118}
119
120/// the families to try for a font, best first
121fn families(q: &FontQuery) -> Vec<&'static str> {
122    let n = q.name.to_ascii_lowercase();
123    let has = |s: &str| n.contains(s);
124    let sans = ["Nimbus Sans", "Liberation Sans", "Arial", "Helvetica", "DejaVu Sans", "Noto Sans"];
125    let serif = ["Nimbus Roman", "Liberation Serif", "Times New Roman", "Times", "DejaVu Serif", "Noto Serif"];
126    let mono = ["Nimbus Mono PS", "Liberation Mono", "Courier New", "Courier", "DejaVu Sans Mono", "Noto Sans Mono"];
127    if has("symbol") {
128        return vec!["Standard Symbols PS", "Symbol", "OpenSymbol", "DejaVu Sans"];
129    }
130    if has("dingbats") {
131        return vec!["D050000L", "Dingbats", "DejaVu Sans"];
132    }
133    if has("courier") || has("mono") || q.fixed {
134        return mono.to_vec();
135    }
136    if has("times") || has("roman") || has("georgia") || has("garamond") || has("serif") && !has("sans") || has("cambria") || has("minion") || has("book") {
137        return serif.to_vec();
138    }
139    if has("helvetica") || has("arial") || has("sans") || has("verdana") || has("calibri") || has("tahoma") || has("frutiger") || has("myriad") {
140        return sans.to_vec();
141    }
142    if q.serif { serif.to_vec() } else { sans.to_vec() }
143}
144
145/// the families for a CJK font's language, best first: Noto CJK and Source Han (any system), then
146/// those of Windows, macOS and Linux; a serif font tries the serif ones (Mincho, Song, Ming,
147/// Batang) first
148fn cjk_families(lang: &str, serif: bool) -> Vec<&'static str> {
149    let (sans, ser): (&[&str], &[&str]) = match lang {
150        "ja" => (
151            &["Noto Sans CJK JP", "Source Han Sans JP", "Yu Gothic", "Meiryo", "MS Gothic", "Hiragino Sans", "Hiragino Kaku Gothic ProN", "IPAexGothic", "IPAGothic", "TakaoGothic", "VL Gothic"],
152            &["Noto Serif CJK JP", "Source Han Serif JP", "Yu Mincho", "MS Mincho", "Hiragino Mincho ProN", "IPAexMincho", "IPAMincho", "TakaoMincho"],
153        ),
154        "zh-Hans" => (
155            &["Noto Sans CJK SC", "Source Han Sans SC", "Microsoft YaHei", "DengXian", "SimHei", "PingFang SC", "Hiragino Sans GB", "Heiti SC", "WenQuanYi Micro Hei", "WenQuanYi Zen Hei"],
156            &["Noto Serif CJK SC", "Source Han Serif SC", "SimSun", "NSimSun", "STSong", "Songti SC", "AR PL UMing CN", "AR PL SungtiL GB"],
157        ),
158        "zh-Hant" => (
159            &["Noto Sans CJK TC", "Source Han Sans TC", "Microsoft JhengHei", "PingFang TC", "Heiti TC", "WenQuanYi Micro Hei", "WenQuanYi Zen Hei"],
160            &["Noto Serif CJK TC", "Source Han Serif TC", "PMingLiU", "MingLiU", "LiSong Pro", "Songti TC", "AR PL UMing TW", "AR PL New Sung"],
161        ),
162        "ko" => (
163            &["Noto Sans CJK KR", "Source Han Sans KR", "Malgun Gothic", "Gulim", "Dotum", "Apple SD Gothic Neo", "NanumGothic", "UnDotum", "Baekmuk Gulim"],
164            &["Noto Serif CJK KR", "Source Han Serif KR", "Batang", "AppleMyungjo", "NanumMyeongjo", "UnBatang", "Baekmuk Batang"],
165        ),
166        _ => (&[], &[]),
167    };
168    if serif { ser.iter().chain(sans).copied().collect() } else { sans.iter().chain(ser).copied().collect() }
169}
170
171impl FontSource for SystemFonts {
172    fn find(&self, q: &FontQuery) -> Option<(Vec<u8>, u32)> {
173        let mut db = self.db.borrow_mut();
174        let db = db.get_or_insert_with(|| {
175            let mut d = text::fontdb::FontDb::new();
176            d.scan(0);
177            d
178        });
179        let weight = if q.bold { 700 } else { 400 };
180        let mut tries: Vec<String> = Vec::new();
181        // the font's own family first (Arial for ArialMT, Calibri, ...)
182        let own = q.name.split(['-', ',']).next().unwrap_or(q.name).trim_end_matches("MT").trim_end_matches("PS");
183        if !own.is_empty() && !q.name.to_ascii_lowercase().contains("helvetica") && !q.name.to_ascii_lowercase().starts_with("times") {
184            tries.push(own.into());
185        }
186        // a CJK font: the usual fonts of its language (a Latin family lacks its characters), then
187        // what fontconfig's rules put first for the language, then its serif or sans-serif choice
188        if let Some(lang) = q.lang {
189            tries.extend(cjk_families(lang, q.serif).into_iter().map(String::from));
190            let mut conf = self.conf.borrow_mut();
191            let conf = conf.get_or_insert_with(text::fontconf::FontConf::system);
192            tries.extend(conf.lang_families(lang));
193            if let Some((_, _, fam)) = db.resolve(conf, if q.serif { "serif" } else { "sans-serif" }, lang, weight, q.italic) {
194                tries.push(fam);
195            }
196        } else {
197            tries.extend(families(q).into_iter().map(String::from));
198        }
199        for fam in &tries {
200            if let Some((i, _)) = db.find(fam, weight, q.italic) {
201                let face = db.face(i)?;
202                if !face.family.eq_ignore_ascii_case(fam) && !face.tfamily.eq_ignore_ascii_case(fam) {
203                    continue;
204                }
205                if let Some(data) = plat::read_file(&face.path) {
206                    return Some((data, face.face));
207                }
208            }
209        }
210        None
211    }
212}
213
214/// what drawing keeps across the pages of a document: the fonts, the default font source
215#[derive(Default)]
216pub(crate) struct Cache {
217    fonts: RefCell<BTreeMap<Ref, Rc<fonts::GFont>>>,
218    /// glyphs drawn: (font, code, the glyph's device matrix, its quarter-pixel phase)
219    glyphs: RefCell<BTreeMap<(usize, u32, [u64; 4], u8), (Rc<fonts::GFont>, Option<Rc<canvas::Cover>>)>>,
220    glyph_bytes: core::cell::Cell<usize>,
221    subst: RefCell<BTreeMap<(String, bool, bool, bool, Option<String>), Option<Rc<fonts::Prog>>>>,
222    /// the font programs by where they are: an embedded one by its stream (and kind), a
223    /// substitute by its size, face and a fingerprint of its bytes (many names find one file);
224    /// the bytes of all programs held stay within PROG_CACHE
225    progs: RefCell<BTreeMap<(usize, usize, u64), Option<Rc<fonts::Prog>>>>,
226    prog_bytes: core::cell::Cell<usize>,
227    system: OnceCell<Rc<dyn FontSource>>,
228    /// ICC profiles by their stream (color::Icc::of), and the ColorGrids the document may
229    /// still build
230    icc: RefCell<BTreeMap<Ref, Option<Rc<color::Icc>>>>,
231    icc_grids: OnceCell<Rc<core::cell::Cell<usize>>>,
232    /// the last key given to resources with Default* spaces (Res::key)
233    res_keys: core::cell::Cell<u64>,
234    /// the codes of the fonts of fields whose appearances drawing makes (edit::widget_ap)
235    pub(crate) field_codes: crate::edit::CodeCache,
236}
237
238impl Cache {
239    fn res_key(&self) -> u64 {
240        let k = self.res_keys.get().wrapping_add(1).max(1);
241        self.res_keys.set(k);
242        k
243    }
244
245    fn icc_grids(&self) -> Rc<core::cell::Cell<usize>> {
246        self.icc_grids.get_or_init(|| Rc::new(core::cell::Cell::new(color::ICC_GRIDS))).clone()
247    }
248
249    /// keep a program of `len` bytes; past PROG_CACHE everything that holds programs is let go
250    /// first (4096 font dictionaries on one FontFile2 of 50 MB held 4096 copies of it)
251    fn keep_prog(&self, key: (usize, usize, u64), p: Option<Rc<fonts::Prog>>, len: usize) {
252        if self.prog_bytes.get() + len > PROG_CACHE {
253            self.progs.borrow_mut().clear();
254            self.subst.borrow_mut().clear();
255            self.fonts.borrow_mut().clear();
256            self.glyphs.borrow_mut().clear();
257            self.glyph_bytes.set(0);
258            self.prog_bytes.set(0);
259        }
260        self.prog_bytes.set(self.prog_bytes.get() + len);
261        self.progs.borrow_mut().insert(key, p);
262    }
263}
264
265/// a fingerprint of a font file: its length and FNV-1a of its first and last 4 KB
266fn fingerprint(d: &[u8]) -> u64 {
267    let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ d.len() as u64;
268    for &c in d.iter().take(4096).chain(d.iter().skip(d.len().saturating_sub(4096))) {
269        h = (h ^ c as u64).wrapping_mul(0x0100_0000_01b3);
270    }
271    h
272}
273
274pub(super) type M = [f64; 6];
275const ID: M = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
276
277/// a × b (a first, then b)
278pub(super) fn mul(a: &M, b: &M) -> M {
279    [
280        a[0] * b[0] + a[1] * b[2],
281        a[0] * b[1] + a[1] * b[3],
282        a[2] * b[0] + a[3] * b[2],
283        a[2] * b[1] + a[3] * b[3],
284        a[4] * b[0] + a[5] * b[2] + b[4],
285        a[4] * b[1] + a[5] * b[3] + b[5],
286    ]
287}
288
289pub(super) fn inv(m: &M) -> Option<M> {
290    let det = m[0] * m[3] - m[1] * m[2];
291    if !det.is_finite() || det.abs() < 1e-300 {
292        return None;
293    }
294    let (a, b, c, d) = (m[3] / det, -m[1] / det, -m[2] / det, m[0] / det);
295    Some([a, b, c, d, -(m[4] * a + m[5] * c), -(m[4] * b + m[5] * d)])
296}
297
298#[inline]
299pub(super) fn apply(m: &M, x: f64, y: f64) -> (f64, f64) {
300    (m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5])
301}
302
303fn finite(m: M) -> M {
304    if m.iter().all(|v| v.is_finite() && v.abs() < 1e12) { m } else { ID }
305}
306
307fn nums(ops: &[Object]) -> Vec<f64> {
308    ops.iter().map(|o| o.as_f64().filter(|v| v.is_finite()).unwrap_or(0.0)).collect()
309}
310
311fn m6(n: &[f64]) -> Option<M> {
312    (n.len() >= 6).then(|| [n[0], n[1], n[2], n[3], n[4], n[5]])
313}
314
315pub(super) fn to8(v: f64) -> u8 {
316    (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
317}
318
319/// forms, patterns, Type 3 glyphs and soft masks inside each other
320const MAX_DEPTH: usize = 12;
321const MAX_STACK: usize = 256;
322/// the operators of a page, forms counted each time they are drawn
323const MAX_OPS: u64 = 1 << 23;
324/// the bytes of glyph coverage kept for a document
325const GLYPH_CACHE: usize = 16 << 20;
326/// the pixels painted for a page: this many per pixel of the page, at least MIN_WORK
327const WORK_PER_PX: u64 = 1024;
328const MIN_WORK: u64 = 1 << 27;
329/// a content stream costs an operator for this many of its bytes each time it is run (a form of
330/// a megabyte of white space drawn a million times has no operators), as does decoding a form,
331/// a CharProc or a font program
332const BYTES_PER_OP: usize = 64;
333/// the masks a page makes (clips that are no rectangle, soft masks), in bytes: this many per
334/// pixel of the page, at least MIN_MASKS (each q may hold one)
335const MASK_PER_PX: u64 = 64;
336const MIN_MASKS: u64 = 1 << 28;
337/// the decoded CharProcs of Type 3 glyphs kept for a page, in bytes
338const T3_CACHE: usize = 32 << 20;
339/// the decoded images kept for a page, in bytes
340const IMAGE_CACHE: usize = 256 << 20;
341/// the font programs kept for a document, in bytes
342const PROG_CACHE: usize = 256 << 20;
343/// the patterns kept for a page (by reference and the matrix of their space)
344const PATTERN_CACHE: usize = 256;
345
346/// a colour of the graphics state: its space, components, RGB (under intent), or a pattern
347#[derive(Clone)]
348struct Paint {
349    cs: Rc<Cs>,
350    comps: Vec<f64>,
351    rgb: [u8; 3],
352    pat: Option<Rc<shade::Pattern>>,
353    intent: u8,
354}
355
356impl Paint {
357    fn new(cs: Rc<Cs>, intent: u8) -> Paint {
358        let comps = cs.initial();
359        let c = cs.rgb_i(&comps, intent, false);
360        Paint { cs, comps, rgb: [to8(c[0]), to8(c[1]), to8(c[2])], pat: None, intent }
361    }
362
363    fn set(&mut self, comps: &[f64]) {
364        let n = self.cs.n();
365        self.comps = comps.iter().take(n).copied().collect();
366        self.comps.resize(n, 0.0);
367        let c = self.cs.rgb_i(&self.comps, self.intent, false);
368        self.rgb = [to8(c[0]), to8(c[1]), to8(c[2])];
369    }
370
371    /// the colour under another rendering intent
372    fn reintent(&mut self, intent: u8) {
373        if self.intent == intent {
374            return;
375        }
376        self.intent = intent;
377        let c = match &*self.cs {
378            Cs::Pattern { under: Some(u) } => u.rgb_i(&self.comps, intent, false),
379            Cs::Pattern { under: None } => return,
380            cs => cs.rgb_i(&self.comps, intent, false),
381        };
382        self.rgb = [to8(c[0]), to8(c[1]), to8(c[2])];
383    }
384}
385
386#[derive(Clone)]
387struct Gs {
388    ctm: M,
389    clip: Clip,
390    fill: Paint,
391    stroke: Paint,
392    lw: f64,
393    cap: u32,
394    join: u32,
395    miter: f64,
396    dash: Rc<Vec<f64>>,
397    phase: f64,
398    fill_alpha: f64,
399    stroke_alpha: f64,
400    blend: Blend,
401    smask: Option<Rc<Mask>>,
402    font: Option<Rc<fonts::GFont>>,
403    size: f64,
404    tc: f64,
405    tw: f64,
406    th: f64,
407    tl: f64,
408    rise: f64,
409    mode: i64,
410    /// the rendering intent (ri, RI; 8.6.5.8)
411    intent: u8,
412}
413
414impl Gs {
415    /// the state a page begins with (and an annotation's appearance, as for a page of its own)
416    fn fresh(ctm: M, rect: Rect) -> Gs {
417        let gray = Rc::new(Cs::Gray);
418        Gs {
419            ctm,
420            clip: Clip { rect, mask: None },
421            fill: Paint::new(gray.clone(), color::RI_RELATIVE),
422            stroke: Paint::new(gray, color::RI_RELATIVE),
423            lw: 1.0,
424            cap: 0,
425            join: 0,
426            miter: 10.0,
427            dash: Rc::new(Vec::new()),
428            phase: 0.0,
429            fill_alpha: 1.0,
430            stroke_alpha: 1.0,
431            blend: Blend::Normal,
432            smask: None,
433            font: None,
434            size: 0.0,
435            tc: 0.0,
436            tw: 0.0,
437            th: 1.0,
438            tl: 0.0,
439            rise: 0.0,
440            mode: 0,
441            intent: color::RI_RELATIVE,
442        }
443    }
444}
445
446#[derive(Clone, Copy)]
447enum Seg {
448    M(f64, f64),
449    L(f64, f64),
450    C([f64; 6]),
451    Z,
452}
453
454/// the resources of a content stream, resolved once
455struct Res {
456    all: Dict,
457    fonts: Dict,
458    xobjects: Dict,
459    ext: Dict,
460    patterns: Dict,
461    shadings: Dict,
462    props: Dict,
463    /// what DeviceGray, DeviceRGB and DeviceCMYK are under these resources (Cs::device)
464    dev: OnceCell<[Rc<Cs>; 3]>,
465    /// 0, or for resources with Default* spaces a key of their own: what is resolved under them
466    /// (colour spaces, shadings, images) is cached under it
467    key: u64,
468}
469
470impl Res {
471    fn of(doc: &Document, res: &Dict) -> Res {
472        let get = |k: &str| res.get(k).map(|o| doc.dict(o)).unwrap_or_default();
473        let cs = get("ColorSpace");
474        let key = if ["DefaultGray", "DefaultRGB", "DefaultCMYK"].iter().any(|k| cs.get(k).is_some()) { doc.render_cache().res_key() } else { 0 };
475        Res {
476            key,
477            all: res.clone(),
478            fonts: get("Font"),
479            xobjects: get("XObject"),
480            ext: get("ExtGState"),
481            patterns: get("Pattern"),
482            shadings: get("Shading"),
483            props: get("Properties"),
484            dev: OnceCell::new(),
485        }
486    }
487}
488
489/// a form XObject, decoded once per page
490struct Form {
491    data: Vec<u8>,
492    res: Option<Rc<Res>>,
493    matrix: M,
494    bbox: Option<[f64; 4]>,
495    /// a transparency group
496    group: bool,
497    oc: Option<Object>,
498}
499
500/// what an annotation or a pattern cell draws with: content, resources and the matrix of its
501/// space
502struct Run<'d> {
503    doc: &'d Document,
504    opt: &'d RenderOptions,
505    layers: Vec<Layer>,
506    ras: Raster,
507    gs: Gs,
508    path: Vec<Seg>,
509    cur: (f64, f64),
510    start: (f64, f64),
511    /// the matrix of the current content stream's default space (patterns are relative to it)
512    base: M,
513    depth: usize,
514    forms: Vec<Ref>,
515    form_cache: BTreeMap<Ref, Option<Rc<Form>>>,
516    /// images by reference, the rendering intent and the resources' key
517    images: BTreeMap<(Ref, u8, u64), Option<Rc<image::Img>>>,
518    image_bytes: usize,
519    /// colour spaces by reference and the resources' key (Default* resolves inside them)
520    cs_cache: BTreeMap<(Ref, u64), Option<Rc<Cs>>>,
521    /// shadings by reference and rendering intent
522    shadings: BTreeMap<(Ref, u8, u64), Option<Rc<shade::Shading>>>,
523    /// patterns by reference and the matrix of their space (each scn parsed and drew it anew)
524    patterns: BTreeMap<(Ref, [u64; 6], u8), Option<Rc<shade::Pattern>>>,
525    /// Type 3 CharProcs decoded, by where their data is
526    t3_procs: BTreeMap<(usize, usize), Option<Rc<Vec<u8>>>>,
527    t3_bytes: usize,
528    ops: u64,
529    work: u64,
530    budget: u64,
531    /// the bytes of the masks made so far, and the most for the page
532    mask_bytes: u64,
533    mask_cap: u64,
534    /// the OCGs off in the default configuration, the marked content open (true: hidden)
535    oc_off: BTreeSet<Ref>,
536    mc: Vec<bool>,
537    hidden: usize,
538    /// Type 3 glyphs of d1 and uncoloured patterns: colours are not set by the content
539    uncolored: bool,
540    text_clip: Option<Path>,
541    /// a Type 3 glyph was shown in a clipping mode (it does not clip, as in Poppler)
542    t3_clip: bool,
543    codes: Vec<(u32, u8)>,
544    error: Option<Error>,
545    /// the page's output intents (color::output_intents)
546    oi: color::Oi,
547}
548
549impl Document {
550    /// the size of a page drawn at dpi: width and height in pixels (the crop box after /Rotate)
551    pub fn page_pixels(&self, page: usize, dpi: f64) -> Result<(u32, u32), Error> {
552        let p = self.page(page)?;
553        let (w, h) = p.size();
554        let s = dpi / 72.0;
555        let px = |v: f64| -> u32 { color::ceil(v * s - 1e-6).clamp(1.0, 65_535.0) as u32 };
556        Ok((px(w), px(h)))
557    }
558
559    /// draw a page into a new surface (premultiplied ARGB, gfx::FMT_PARGB)
560    pub fn render(&self, page: usize, opt: &RenderOptions) -> Result<gfx::Surface, Error> {
561        let p = self.page(page)?.clone();
562        let (w, h) = self.page_pixels(page, opt.dpi)?;
563        let [rx, ry, rw, rh] = opt.region.unwrap_or([0, 0, w, h]);
564        let (rw, rh) = (rw.min(w.saturating_sub(rx)), rh.min(h.saturating_sub(ry)));
565        if rw == 0 || rh == 0 {
566            return Err(Error::Limit("the region is outside the page"));
567        }
568        if (rw as u64) * (rh as u64) > opt.max_pixels.min(1 << 30) {
569            return Err(Error::Limit("pixels"));
570        }
571        // the page is drawn onto nothing (its blend modes see a transparent backdrop, 11.4.7),
572        // then onto the paper
573        let rect: Rect = [0, 0, rw as i32, rh as i32];
574        let layer = Layer::new(rect).ok_or(Error::Limit("memory"))?;
575        let dev = device_matrix(&p, opt.dpi, rx as f64, ry as f64);
576        let pixels = (rw as u64) * (rh as u64);
577        let mut run = Run::new(self, opt, layer, dev, pixels);
578        run.oc_off = self.oc_off();
579        run.oi = color::output_intents(self, &p.dict);
580        let res = Rc::new(Res::of(self, &p.resources));
581        let content = self.contents(page)?;
582        // the page is clipped to its crop box
583        run.clip_rect_user(&p.crop_box);
584        run.run(&content, &res);
585        if opt.annotations {
586            run.annotations(&p);
587        }
588        if let Some(e) = run.error.take() {
589            return Err(e);
590        }
591        let layer = run.layers.pop().ok_or(Error::Limit("layers"))?;
592        let mut sf = gfx::Surface::try_new(rw as i32, rh as i32, gfx::FMT_PARGB).ok_or(Error::Limit("memory"))?;
593        let stride = sf.stride as usize;
594        let paper = opt.background.map(|bg| {
595            let a = bg >> 24;
596            let pm = |v: u32| canvas::mul255(v & 0xFF, a);
597            [pm(bg >> 16), pm(bg >> 8), pm(bg), a]
598        });
599        let rowb = rw as usize * 4;
600        for (src, dst) in layer.px.chunks_exact(rowb).zip(sf.px.chunks_mut(stride)) {
601            for (s, d) in src.chunks_exact(4).zip(dst[..rowb].chunks_exact_mut(4)) {
602                match (paper, s[3]) {
603                    (Some(p), a) if a < 255 => {
604                        let ia = 255 - a as u32;
605                        d[0] = (s[2] as u32 + canvas::mul255(p[2], ia)) as u8;
606                        d[1] = (s[1] as u32 + canvas::mul255(p[1], ia)) as u8;
607                        d[2] = (s[0] as u32 + canvas::mul255(p[0], ia)) as u8;
608                        d[3] = (a as u32 + canvas::mul255(p[3], ia)) as u8;
609                    }
610                    _ => {
611                        d[0] = s[2];
612                        d[1] = s[1];
613                        d[2] = s[0];
614                        d[3] = s[3];
615                    }
616                }
617            }
618        }
619        Ok(sf)
620    }
621
622    /// the OCGs that are off in the default configuration of the document's optional content
623    fn oc_off(&self) -> BTreeSet<Ref> {
624        let mut off = BTreeSet::new();
625        let props = self.dict(&self.catalog().get("OCProperties").cloned().unwrap_or_default());
626        let d = self.dict(&props.get("D").cloned().unwrap_or_default());
627        let refs = |o: Option<&Object>| -> Vec<Ref> {
628            match o.map(|o| self.resolve(o)) {
629                Some(Object::Array(a)) => a.iter().filter_map(Object::as_ref).take(1 << 16).collect(),
630                _ => Vec::new(),
631            }
632        };
633        if d.name("BaseState") == Some(b"OFF") {
634            for r in refs(props.get("OCGs")) {
635                off.insert(r);
636            }
637            for r in refs(d.get("ON")) {
638                off.remove(&r);
639            }
640        }
641        for r in refs(d.get("OFF")) {
642            off.insert(r);
643        }
644        off
645    }
646
647    pub(crate) fn render_cache(&self) -> &Cache {
648        &self.render
649    }
650}
651
652/// default user space -> device pixels: the crop box's corner at the origin, y down, /Rotate,
653/// UserUnit and dpi, the region's corner at the origin
654fn device_matrix(p: &Page, dpi: f64, rx: f64, ry: f64) -> M {
655    let s = dpi / 72.0 * p.user_unit;
656    let [x0, y0, x1, y1] = p.crop_box;
657    let m = match p.rotate {
658        90 => [0.0, s, s, 0.0, -y0 * s, -x0 * s],
659        180 => [-s, 0.0, 0.0, s, x1 * s, -y0 * s],
660        270 => [0.0, -s, -s, 0.0, y1 * s, x1 * s],
661        _ => [s, 0.0, 0.0, -s, -x0 * s, y1 * s],
662    };
663    mul(&m, &[1.0, 0.0, 0.0, 1.0, -rx, -ry])
664}
665
666impl<'d> Run<'d> {
667    fn new(doc: &'d Document, opt: &'d RenderOptions, layer: Layer, dev: M, pixels: u64) -> Run<'d> {
668        let rect = layer.rect;
669        let gs = Gs::fresh(dev, rect);
670        Run {
671            doc,
672            opt,
673            layers: vec![layer],
674            ras: Raster::default(),
675            gs,
676            path: Vec::new(),
677            cur: (0.0, 0.0),
678            start: (0.0, 0.0),
679            base: dev,
680            depth: 0,
681            forms: Vec::new(),
682            form_cache: BTreeMap::new(),
683            images: BTreeMap::new(),
684            image_bytes: 0,
685            cs_cache: BTreeMap::new(),
686            shadings: BTreeMap::new(),
687            patterns: BTreeMap::new(),
688            t3_procs: BTreeMap::new(),
689            t3_bytes: 0,
690            ops: 0,
691            work: 0,
692            budget: pixels.saturating_mul(WORK_PER_PX).max(MIN_WORK),
693            mask_bytes: 0,
694            mask_cap: pixels.saturating_mul(MASK_PER_PX).max(MIN_MASKS),
695            oc_off: BTreeSet::new(),
696            mc: Vec::new(),
697            hidden: 0,
698            uncolored: false,
699            text_clip: None,
700            t3_clip: false,
701            codes: Vec::new(),
702            oi: color::Oi::default(),
703            error: None,
704        }
705    }
706
707    /// count painted pixels; false when the page has used up its work
708    fn spend(&mut self, n: u64) -> bool {
709        self.work = self.work.saturating_add(n);
710        if self.work > self.budget {
711            self.error.get_or_insert(Error::Limit("the work of a page"));
712            return false;
713        }
714        true
715    }
716
717    fn stopped(&self) -> bool {
718        self.error.is_some()
719    }
720
721    /// count operators (bytes read and decoded, glyphs shown); false when the page has used them up
722    fn charge(&mut self, ops: u64) -> bool {
723        self.ops = self.ops.saturating_add(ops);
724        if self.ops > MAX_OPS {
725            self.error.get_or_insert(Error::Limit("the operators of a page"));
726            return false;
727        }
728        true
729    }
730
731    /// a mask of `px` bytes is kept: what the masks of a page come to together (each q may hold
732    /// one: 256 of them on each of 12 levels were tens of GB)
733    fn mask_kept(&mut self, px: u64) -> bool {
734        self.mask_bytes = self.mask_bytes.saturating_add(px);
735        if self.mask_bytes > self.mask_cap {
736            self.error.get_or_insert(Error::Limit("memory"));
737            return false;
738        }
739        true
740    }
741
742    /// the clip and the area of the rasterizer's lines (a mask of their pixels when that is no
743    /// rectangle); the pixels count as work
744    fn clip_ras(&mut self, rule: u32) {
745        let px = self.gs.clip.path_area(&self.ras);
746        if !self.spend(px) {
747            return;
748        }
749        match self.gs.clip.and_path(&mut self.ras, rule) {
750            Some(c) => {
751                if let Some(m) = &c.mask {
752                    if !self.mask_kept(m.a.len() as u64) {
753                        return;
754                    }
755                }
756                self.gs.clip = c;
757            }
758            None => {
759                self.error.get_or_insert(Error::Limit("memory"));
760            }
761        }
762    }
763
764    fn layer_rect(&self) -> Rect {
765        self.layers.last().map_or([0, 0, 0, 0], |l| l.rect)
766    }
767
768    // ------------------------------------------------------------ paths
769
770    /// the current path into the rasterizer's lines in device space (through m)
771    fn lines(&mut self, segs: &[Seg], m: &M) {
772        let mut p = Path::default();
773        for s in segs {
774            match *s {
775                Seg::M(x, y) => {
776                    let (a, b) = apply(m, x, y);
777                    p.move_f(a as f32, b as f32);
778                }
779                Seg::L(x, y) => {
780                    let (a, b) = apply(m, x, y);
781                    p.line_f(a as f32, b as f32);
782                }
783                Seg::C(c) => {
784                    let (a, b) = apply(m, c[0], c[1]);
785                    let (e, f) = apply(m, c[2], c[3]);
786                    let (g, h) = apply(m, c[4], c[5]);
787                    p.cubic_f((a as f32, b as f32), (e as f32, f as f32), (g as f32, h as f32));
788                }
789                Seg::Z => p.close(),
790            }
791        }
792        p.fill_lines(&mut self.ras);
793    }
794
795    /// the outline of the stroke of segs (user space, line style of gs) into the rasterizer
796    fn stroke_lines(&mut self, segs: &[Seg], ctm: &M) -> bool {
797        if self.adjusted_stroke(segs, ctm) {
798            return true;
799        }
800        let gs = &self.gs;
801        let det = (ctm[0] * ctm[3] - ctm[1] * ctm[2]).abs();
802        let mut k = color::sqrt(det);
803        if !(k > 1e-9) {
804            k = ctm[0].abs().max(ctm[1].abs()).max(ctm[2].abs()).max(ctm[3].abs());
805            if !(k > 1e-9) {
806                return false;
807            }
808        }
809        // the stroke in user space scaled by k (a unit there is about a pixel), then M / k
810        let mut p = Path::default();
811        for s in segs {
812            match *s {
813                Seg::M(x, y) => p.move_f((x * k) as f32, (y * k) as f32),
814                Seg::L(x, y) => p.line_f((x * k) as f32, (y * k) as f32),
815                Seg::C(c) => p.cubic_f(((c[0] * k) as f32, (c[1] * k) as f32), ((c[2] * k) as f32, (c[3] * k) as f32), ((c[4] * k) as f32, (c[5] * k) as f32)),
816                Seg::Z => p.close(),
817            }
818        }
819        let (width, unit) = if gs.lw * k < 1e-6 { (1.0, 1.0 / k) } else { (gs.lw * k, gs.lw) };
820        let mut pat: Vec<f64> = gs.dash.iter().map(|d| d / unit).collect();
821        if pat.iter().all(|&d| d <= 0.0) || pat.iter().any(|&d| d < 0.0 || !d.is_finite()) {
822            pat.clear();
823        }
824        pat.truncate(gfx::dash::DASH_MAXPAT);
825        let st = DStyle { width, pat: &pat, join: gs.join, cap0: gs.cap, cap1: gs.cap, dcap: gs.cap, offset: gs.phase / unit, miter: gs.miter.max(1.0) };
826        if dash_stroke(&mut p, &st) != 0 {
827            return false;
828        }
829        let m = [ctm[0] / k, ctm[1] / k, ctm[2] / k, ctm[3] / k, ctm[4], ctm[5]];
830        for pt in p.pts_mut() {
831            let (x, y) = apply(&m, pt.0 as f64, pt.1 as f64);
832            *pt = (x as f32, y as f32);
833        }
834        p.fill_lines(&mut self.ras);
835        true
836    }
837
838    /// stroke adjustment (as Poppler does it): a solid stroke of lines that are all horizontal or
839    /// vertical on the device becomes rectangles whose edges are rounded to whole pixels, at
840    /// least one pixel wide, so that thin rules and frames stay sharp and equally thick
841    fn adjusted_stroke(&mut self, segs: &[Seg], ctm: &M) -> bool {
842        let gs = &self.gs;
843        let axis = ctm[1].abs() < 1e-9 && ctm[2].abs() < 1e-9;
844        let swap = ctm[0].abs() < 1e-9 && ctm[3].abs() < 1e-9;
845        if !gs.dash.is_empty() || !(axis || swap) || segs.iter().any(|s| matches!(s, Seg::C(_))) || segs.len() > 4096 {
846            return false;
847        }
848        // half the thickness of horizontal and of vertical lines on the device
849        let (sy, sx) = if axis { (ctm[3].abs(), ctm[0].abs()) } else { (ctm[1].abs(), ctm[2].abs()) };
850        let hh = if gs.lw * sy < 1.0 { 0.5 } else { gs.lw * sy / 2.0 };
851        let hv = if gs.lw * sx < 1.0 { 0.5 } else { gs.lw * sx / 2.0 };
852        // round caps and joins other than miter only where they cannot be seen
853        if (gs.cap == 1 || gs.join != 0) && (hh > 1.0 || hv > 1.0) {
854            return false;
855        }
856        let cap = if gs.cap == 0 { 0.0 } else { 1.0 };
857        // the subpaths as device points, closed or not
858        let mut subs: Vec<(Vec<(f64, f64)>, bool)> = Vec::new();
859        for s in segs {
860            match *s {
861                Seg::M(x, y) => subs.push((vec![apply(ctm, x, y)], false)),
862                Seg::L(x, y) => match subs.last_mut() {
863                    Some(sp) => sp.0.push(apply(ctm, x, y)),
864                    None => return false,
865                },
866                Seg::Z => {
867                    if let Some(sp) = subs.last_mut() {
868                        sp.1 = true;
869                    }
870                }
871                Seg::C(_) => return false,
872            }
873        }
874        let mut rects: Vec<[f64; 4]> = Vec::new();
875        for (pts, closed) in &subs {
876            let mut p: Vec<(f64, f64)> = Vec::with_capacity(pts.len());
877            for &q in pts {
878                if p.last().is_none_or(|l: &(f64, f64)| (l.0 - q.0).abs() > 1e-6 || (l.1 - q.1).abs() > 1e-6) {
879                    p.push(q);
880                }
881            }
882            let closed = *closed || p.len() > 2 && (p[0].0 - p[p.len() - 1].0).abs() < 1e-6 && (p[0].1 - p[p.len() - 1].1).abs() < 1e-6;
883            if closed && p.len() > 1 && (p[0].0 - p[p.len() - 1].0).abs() < 1e-6 && (p[0].1 - p[p.len() - 1].1).abs() < 1e-6 {
884                p.pop();
885            }
886            let n = p.len();
887            if n < 2 {
888                continue;
889            }
890            let nseg = if closed { n } else { n - 1 };
891            for i in 0..nseg {
892                let (a, b) = (p[i], p[(i + 1) % n]);
893                let horiz = (a.1 - b.1).abs() < 1e-6;
894                let vert = (a.0 - b.0).abs() < 1e-6;
895                if !horiz && !vert {
896                    return false;
897                }
898                // a join or a cap at each end: miter and square reach half the width further
899                let ext0 = if closed || i > 0 { 1.0 } else { cap };
900                let ext1 = if closed || i + 1 < nseg { 1.0 } else { cap };
901                if horiz {
902                    let (x0, x1) = if a.0 <= b.0 { (a.0 - hv * ext0, b.0 + hv * ext1) } else { (b.0 - hv * ext1, a.0 + hv * ext0) };
903                    rects.push([x0, a.1 - hh, x1, a.1 + hh]);
904                } else {
905                    let (y0, y1) = if a.1 <= b.1 { (a.1 - hh * ext0, b.1 + hh * ext1) } else { (b.1 - hh * ext1, a.1 + hh * ext0) };
906                    rects.push([a.0 - hv, y0, a.0 + hv, y1]);
907                }
908            }
909        }
910        let round = |v: f64| color::floor(v + 0.5);
911        self.ras.lines_begin();
912        for r in rects {
913            let (x0, mut x1) = (round(r[0]), round(r[2]));
914            let (y0, mut y1) = (round(r[1]), round(r[3]));
915            if x1 <= x0 {
916                x1 = x0 + 1.0;
917            }
918            if y1 <= y0 {
919                y1 = y0 + 1.0;
920            }
921            let (x0, x1, y0, y1) = (x0 as f32, x1 as f32, y0 as f32, y1 as f32);
922            self.ras.emit_line(x0, y0, x1, y0);
923            self.ras.emit_line(x1, y0, x1, y1);
924            self.ras.emit_line(x1, y1, x0, y1);
925            self.ras.emit_line(x0, y1, x0, y0);
926        }
927        true
928    }
929
930    /// a clipping path that is one rectangle along the device's axes: its edges rounded to whole
931    /// pixels (as Poppler clips to rectangles), no mask
932    fn clip_rect_fast(&mut self, segs: &[Seg], ctm: &M) -> bool {
933        let mut pts: Vec<(f64, f64)> = Vec::with_capacity(5);
934        for (i, s) in segs.iter().enumerate() {
935            match *s {
936                Seg::M(x, y) if i == 0 => pts.push(apply(ctm, x, y)),
937                Seg::L(x, y) => pts.push(apply(ctm, x, y)),
938                Seg::Z if i + 1 == segs.len() => {}
939                _ => return false,
940            }
941        }
942        if pts.len() == 5 && (pts[0].0 - pts[4].0).abs() < 1e-6 && (pts[0].1 - pts[4].1).abs() < 1e-6 {
943            pts.pop();
944        }
945        if pts.len() != 4 {
946            return false;
947        }
948        let near = |a: f64, b: f64| (a - b).abs() < 1e-6;
949        let along = (0..4).all(|i| {
950            let (a, b) = (pts[i], pts[(i + 1) % 4]);
951            near(a.0, b.0) != near(a.1, b.1)
952        });
953        if !along {
954            return false;
955        }
956        let xs = pts.iter().map(|p| p.0);
957        let ys = pts.iter().map(|p| p.1);
958        let (x0, x1) = (xs.clone().fold(f64::MAX, f64::min), xs.fold(f64::MIN, f64::max));
959        let (y0, y1) = (ys.clone().fold(f64::MAX, f64::min), ys.fold(f64::MIN, f64::max));
960        let r = |v: f64| color::floor(v + 0.5).clamp(-1.0e8, 1.0e8) as i32;
961        let rect = canvas::intersect(self.gs.clip.rect, [r(x0), r(y0), r(x1), r(y1)]);
962        self.gs.clip = Clip { rect, mask: if canvas::is_empty(rect) { None } else { self.gs.clip.mask.clone() } };
963        true
964    }
965
966    fn clip_rect_user(&mut self, b: &[f64; 4]) {
967        let segs = [Seg::M(b[0], b[1]), Seg::L(b[2], b[1]), Seg::L(b[2], b[3]), Seg::L(b[0], b[3]), Seg::Z];
968        let ctm = self.gs.ctm;
969        if self.clip_rect_fast(&segs, &ctm) {
970            return;
971        }
972        self.lines(&segs, &ctm);
973        self.clip_ras(RULE_NONZERO);
974    }
975
976    /// the source of a paint for the pixels of a fill
977    fn paint(&mut self, stroke: bool, f: &mut dyn FnMut(&mut Run, &Src, u8)) {
978        let p = if stroke { self.gs.stroke.clone() } else { self.gs.fill.clone() };
979        let alpha = to8(if stroke { self.gs.stroke_alpha } else { self.gs.fill_alpha });
980        if p.cs.paints_nothing() {
981            return;
982        }
983        match &p.pat {
984            None => f(self, &Src::Solid(p.rgb), alpha),
985            Some(pat) => {
986                let area = canvas::intersect(self.gs.clip.rect, self.layer_rect());
987                let lb = self.ras.lbox();
988                let area = canvas::intersect(area, [canvas::floor(lb[0]), canvas::floor(lb[1]), canvas::ceil(lb[2]) + 1, canvas::ceil(lb[3]) + 1]);
989                if canvas::is_empty(area) {
990                    return;
991                }
992                // the rasterizer's lines are kept while the pattern is prepared (it draws too)
993                let saved = core::mem::take(&mut self.ras);
994                let shader = shade::shader(self, pat, &p, area);
995                self.ras = saved;
996                if let Some(s) = shader {
997                    f(self, &Src::Shade(&*s), alpha);
998                }
999            }
1000        }
1001    }
1002
1003    /// fill the rasterizer's lines with the fill or stroke paint
1004    fn fill_ras(&mut self, rule: u32, stroke: bool) {
1005        if self.hidden > 0 || self.stopped() {
1006            return;
1007        }
1008        self.paint(stroke, &mut |run, src, alpha| {
1009            let Run { layers, ras, gs, .. } = run;
1010            let Some(layer) = layers.last_mut() else { return };
1011            let put = Put { clip: &gs.clip, alpha, blend: gs.blend, smask: gs.smask.as_deref() };
1012            let n = canvas::fill(layer, ras, rule, src, &put);
1013            run.spend(n);
1014        });
1015    }
1016
1017    fn paint_path(&mut self, fill: Option<u32>, stroke: bool, close: bool) {
1018        if close {
1019            self.path.push(Seg::Z);
1020        }
1021        let segs = core::mem::take(&mut self.path);
1022        let ctm = self.gs.ctm;
1023        if let Some(rule) = fill {
1024            self.lines(&segs, &ctm);
1025            self.fill_ras(rule, false);
1026        }
1027        if stroke && self.stroke_lines(&segs, &ctm) {
1028            self.fill_ras(RULE_NONZERO, true);
1029        }
1030        self.path = segs;
1031    }
1032
1033    fn end_path(&mut self, clip: Option<u32>) {
1034        if let Some(rule) = clip {
1035            let segs = core::mem::take(&mut self.path);
1036            let ctm = self.gs.ctm;
1037            if self.clip_rect_fast(&segs, &ctm) {
1038                self.path.clear();
1039                return;
1040            }
1041            self.lines(&segs, &ctm);
1042            self.clip_ras(rule);
1043        }
1044        self.path.clear();
1045    }
1046
1047    // ------------------------------------------------------------ colours
1048
1049    fn colorspace(&mut self, o: &Object, res: &Res) -> Option<Rc<Cs>> {
1050        // a named space of the resources by its reference, parsed once
1051        if let Object::Name(n) = o {
1052            if let Some(r) = res.all.get("ColorSpace").map(|c| self.doc.dict(c)).and_then(|d| d.get_bytes(&n.0).and_then(Object::as_ref)) {
1053                if let Some(c) = self.cs_cache.get(&(r, res.key)) {
1054                    return c.clone();
1055                }
1056                let c = Cs::parse(self.doc, &Object::Ref(r), &res.all, &self.oi);
1057                self.cs_cache.insert((r, res.key), c.clone());
1058                return c;
1059            }
1060        }
1061        Cs::parse(self.doc, o, &res.all, &self.oi)
1062    }
1063
1064    /// DeviceGray (0), DeviceRGB (1), DeviceCMYK (2) under the resources res
1065    fn device_cs(&self, k: usize, res: &Res) -> Rc<Cs> {
1066        let d = res.dev.get_or_init(|| [0, 1, 2].map(|k| Cs::device(self.doc, &res.all, &self.oi, k)));
1067        d[k.min(2)].clone()
1068    }
1069
1070    /// the rendering intent of the graphics state, and the colours set under it
1071    fn set_intent(&mut self, intent: u8) {
1072        self.gs.intent = intent;
1073        self.gs.fill.reintent(intent);
1074        self.gs.stroke.reintent(intent);
1075    }
1076
1077    fn set_color(&mut self, stroke: bool, a: &[Object], res: &Res) {
1078        if self.uncolored {
1079            return;
1080        }
1081        let p = if stroke { &mut self.gs.stroke } else { &mut self.gs.fill };
1082        // a pattern: its name last, the underlying space's components before it
1083        if let Some(Object::Name(n)) = a.last() {
1084            if matches!(&*p.cs, Cs::Pattern { .. }) {
1085                let comps = nums(&a[..a.len() - 1]);
1086                let under = match &*p.cs {
1087                    Cs::Pattern { under: Some(u) } => Some(u.clone()),
1088                    _ => None,
1089                };
1090                let pat = res.patterns.get_bytes(&n.0).cloned();
1091                let base = self.base;
1092                let doc = self.doc;
1093                // a pattern by its reference and the matrix of its space, parsed and its tile
1094                // drawn once (each scn did it again: many /P0 scn ... f put a page over its work)
1095                let key = pat.as_ref().and_then(Object::as_ref).map(|r| (r, base.map(f64::to_bits), self.gs.intent));
1096                let pat = match key.and_then(|k| self.patterns.get(&k).cloned()) {
1097                    Some(p) => p,
1098                    None => {
1099                        let p = pat.and_then(|o| shade::Pattern::parse(doc, &o, &base, self));
1100                        if let Some(k) = key {
1101                            if self.patterns.len() < PATTERN_CACHE {
1102                                self.patterns.insert(k, p.clone());
1103                            }
1104                        }
1105                        p
1106                    }
1107                };
1108                let p = if stroke { &mut self.gs.stroke } else { &mut self.gs.fill };
1109                p.pat = pat;
1110                if let Some(u) = under {
1111                    let c = u.rgb_i(&comps, p.intent, false);
1112                    p.rgb = [to8(c[0]), to8(c[1]), to8(c[2])];
1113                    p.comps = comps;
1114                }
1115                return;
1116            }
1117        }
1118        p.pat = None;
1119        p.set(&nums(a));
1120    }
1121
1122    fn set_space(&mut self, stroke: bool, cs: Rc<Cs>) {
1123        if self.uncolored {
1124            return;
1125        }
1126        let p = Paint::new(cs, self.gs.intent);
1127        if stroke {
1128            self.gs.stroke = p;
1129        } else {
1130            self.gs.fill = p;
1131        }
1132    }
1133
1134    // ------------------------------------------------------------ graphics state
1135
1136    fn ext_gstate(&mut self, d: &Dict, res: &Res) {
1137        let doc = self.doc;
1138        if let Some(v) = doc.key(d, "LW").as_f64() {
1139            self.gs.lw = v.abs();
1140        }
1141        if let Some(v) = doc.key(d, "LC").as_int() {
1142            self.gs.cap = v.clamp(0, 2) as u32;
1143        }
1144        if let Some(v) = doc.key(d, "LJ").as_int() {
1145            self.gs.join = v.clamp(0, 2) as u32;
1146        }
1147        if let Some(v) = doc.key(d, "ML").as_f64() {
1148            self.gs.miter = v;
1149        }
1150        if let Object::Array(a) = doc.key(d, "D") {
1151            if let Some(Object::Array(p)) = a.first().map(|o| doc.resolve(o)) {
1152                self.gs.dash = Rc::new(p.iter().filter_map(|v| doc.resolve(v).as_f64()).take(64).collect());
1153                self.gs.phase = a.get(1).and_then(|v| doc.resolve(v).as_f64()).unwrap_or(0.0);
1154            }
1155        }
1156        if let Object::Name(n) = doc.key(d, "RI") {
1157            self.set_intent(color::intent_of(&n.0));
1158        }
1159        if let Some(v) = doc.key(d, "CA").as_f64() {
1160            self.gs.stroke_alpha = v.clamp(0.0, 1.0);
1161        }
1162        if let Some(v) = doc.key(d, "ca").as_f64() {
1163            self.gs.fill_alpha = v.clamp(0.0, 1.0);
1164        }
1165        match doc.key(d, "BM") {
1166            Object::Name(n) => self.gs.blend = Blend::from_name(&n.0).unwrap_or(Blend::Normal),
1167            Object::Array(a) => {
1168                self.gs.blend = a.iter().find_map(|v| doc.resolve(v).as_name().and_then(Blend::from_name)).unwrap_or(Blend::Normal);
1169            }
1170            _ => {}
1171        }
1172        if let Object::Array(a) = doc.key(d, "Font") {
1173            if let (Some(f), Some(sz)) = (a.first(), a.get(1).and_then(|v| doc.resolve(v).as_f64())) {
1174                self.gs.font = self.font_of(f);
1175                self.gs.size = sz;
1176            }
1177        }
1178        match doc.key(d, "SMask") {
1179            Object::Name(n) if n.0 == b"None" => self.gs.smask = None,
1180            Object::Dict(sm) => self.gs.smask = self.soft_mask(&sm, res),
1181            _ => {}
1182        }
1183    }
1184
1185    /// a soft mask: its group drawn now, with the CTM of now (11.6.5.2)
1186    fn soft_mask(&mut self, sm: &Dict, _res: &Res) -> Option<Rc<Mask>> {
1187        if self.depth >= MAX_DEPTH {
1188            return None;
1189        }
1190        let doc = self.doc;
1191        let luminosity = sm.name("S") != Some(b"Alpha");
1192        let g = sm.get("G")?;
1193        let r = g.as_ref();
1194        let form = self.form(g)?;
1195        let gd = match doc.resolve(g) {
1196            Object::Stream(s) => s.dict.clone(),
1197            _ => return None,
1198        };
1199        // the group's colour space under its own resources (their Default*)
1200        let gres = form.res.as_ref().map_or_else(|| _res.all.clone(), |r| r.all.clone());
1201        let group_cs = doc.dict(&gd.get("Group").cloned().unwrap_or_default()).get("CS").cloned().and_then(|c| Cs::parse(doc, &c, &gres, &self.oi));
1202        let ctm = finite(mul(&form.matrix, &self.gs.ctm));
1203        // where the group can paint: its bbox on the device, within the page
1204        let page = self.layers[0].rect;
1205        let rect = match form.bbox {
1206            Some(b) => canvas::intersect(page, bbox_rect(&b, &ctm)),
1207            None => page,
1208        };
1209        let bc: Vec<f64> = match doc.key(sm, "BC") {
1210            Object::Array(a) => a.iter().filter_map(|v| doc.resolve(v).as_f64()).collect(),
1211            _ => Vec::new(),
1212        };
1213        let back = if luminosity {
1214            let cs = group_cs.clone().unwrap_or_else(|| Rc::new(Cs::Rgb));
1215            let c = if bc.is_empty() { [0.0; 3] } else { cs.rgb_i(&bc, self.gs.intent, false) };
1216            [to8(c[0]), to8(c[1]), to8(c[2]), 255]
1217        } else {
1218            [0, 0, 0, 0]
1219        };
1220        let tr = match doc.key(sm, "TR") {
1221            Object::Name(_) | Object::Null => None,
1222            o => color::Func::parse(doc, &o),
1223        };
1224        let lum = |c: [u8; 4]| -> u8 { ((c[0] as u32 * 77 + c[1] as u32 * 151 + c[2] as u32 * 28 + 128) >> 8) as u8 };
1225        let lut: Vec<u8> = (0..256u32)
1226            .map(|v| match &tr {
1227                Some(f) => {
1228                    let mut out = Vec::new();
1229                    f.eval(&[v as f64 / 255.0], &mut out);
1230                    to8(out.first().copied().unwrap_or(v as f64 / 255.0))
1231                }
1232                None => v as u8,
1233            })
1234            .collect();
1235        let outside = lut[if luminosity { lum(back) } else { 0 } as usize];
1236        if canvas::is_empty(rect) {
1237            return Some(Rc::new(Mask { rect, a: Vec::new(), outside }));
1238        }
1239        // the group's layer is filled, drawn and read: its pixels count as work, the mask as
1240        // memory (a page-size soft mask a million times, each held by a q)
1241        let px = (rect[2] - rect[0]) as u64 * (rect[3] - rect[1]) as u64;
1242        if !self.spend(px.saturating_mul(4)) || !self.mask_kept(px) {
1243            return None;
1244        }
1245        let mut layer = Layer::new(rect)?;
1246        layer.fill(back);
1247        let saved_gs = self.gs.clone();
1248        self.layers.push(layer);
1249        self.gs.ctm = ctm;
1250        self.gs.clip = Clip { rect, mask: None };
1251        self.gs.fill_alpha = 1.0;
1252        self.gs.stroke_alpha = 1.0;
1253        self.gs.blend = Blend::Normal;
1254        self.gs.smask = None;
1255        let res = form.res.clone().unwrap_or_else(|| Rc::new(Res::of(doc, &Dict::new())));
1256        self.depth += 1;
1257        self.forms.push(r.unwrap_or(Ref { num: u32::MAX, generation: 0 }));
1258        let saved_base = self.base;
1259        self.base = ctm;
1260        if let Some(b) = form.bbox {
1261            self.clip_rect_user(&b);
1262        }
1263        self.run(&form.data, &res);
1264        self.base = saved_base;
1265        self.forms.pop();
1266        self.depth -= 1;
1267        let layer = self.layers.pop()?;
1268        self.gs = saved_gs;
1269        let a: Vec<u8> = layer
1270            .px
1271            .chunks_exact(4)
1272            .map(|p| {
1273                let v = if luminosity { lum([p[0], p[1], p[2], p[3]]) } else { p[3] };
1274                lut[v as usize]
1275            })
1276            .collect();
1277        Some(Rc::new(Mask { rect, a, outside }))
1278    }
1279
1280    // ------------------------------------------------------------ fonts and text
1281
1282    fn font_of(&mut self, o: &Object) -> Option<Rc<fonts::GFont>> {
1283        let doc = self.doc;
1284        let cache = doc.render_cache();
1285        let r = o.as_ref();
1286        if let Some(f) = r.and_then(|r| cache.fonts.borrow().get(&r).cloned()) {
1287            return Some(f);
1288        }
1289        let d = doc.dict(o);
1290        if d.is_empty() {
1291            return None;
1292        }
1293        let source = self.opt.fonts.clone().unwrap_or_else(|| cache.system.get_or_init(|| Rc::new(SystemFonts::new())).clone());
1294        // the bytes read and decoded for programs count as operators
1295        let read = core::cell::Cell::new(0usize);
1296        let mut embedded = |s: &Stream, kind: u8| -> Option<Rc<fonts::Prog>> {
1297            let key = (s.start, s.end, kind as u64);
1298            if let Some(p) = cache.progs.borrow().get(&key) {
1299                return p.clone();
1300            }
1301            let data = doc.decode(s).ok()?;
1302            read.set(read.get() + s.raw_len() + data.len());
1303            let len = data.len();
1304            let p = fonts::Prog::open(data, 0, kind).map(Rc::new);
1305            cache.keep_prog(key, p.clone(), len);
1306            p
1307        };
1308        let mut subst = |q: &FontQuery| -> Option<Rc<fonts::Prog>> {
1309            let key = (String::from(q.name), q.bold, q.italic, q.fixed, q.lang.map(String::from));
1310            if let Some(p) = cache.subst.borrow().get(&key) {
1311                return p.clone();
1312            }
1313            let p = source.find(q).and_then(|(data, face)| {
1314                read.set(read.get() + data.len());
1315                // another name that found the same file shares its program
1316                let fkey = (usize::MAX, face as usize, fingerprint(&data));
1317                if let Some(p) = cache.progs.borrow().get(&fkey) {
1318                    return p.clone();
1319                }
1320                let len = data.len();
1321                let p = fonts::Prog::open(data, face, 2).map(Rc::new);
1322                cache.keep_prog(fkey, p.clone(), len);
1323                p
1324            });
1325            cache.subst.borrow_mut().insert(key, p.clone());
1326            p
1327        };
1328        let f = Rc::new(fonts::GFont::load(doc, &d, &mut embedded, &mut subst));
1329        if !self.charge((read.get() / BYTES_PER_OP) as u64) {
1330            return None;
1331        }
1332        if let Some(r) = r {
1333            let mut c = cache.fonts.borrow_mut();
1334            if c.len() < 4096 {
1335                c.insert(r, f.clone());
1336            }
1337        }
1338        Some(f)
1339    }
1340
1341    fn show(&mut self, tm: &mut M, s: &[u8], res: &Rc<Res>) {
1342        let Some(font) = self.gs.font.clone() else { return };
1343        let mut codes = core::mem::take(&mut self.codes);
1344        font.base.codes(s, &mut codes);
1345        // each glyph counts, an invisible one too (a Type 3 glyph runs its CharProc)
1346        if !self.charge(codes.len() as u64) {
1347            self.codes = codes;
1348            return;
1349        }
1350        for &(code, len) in &codes {
1351            if self.stopped() {
1352                break;
1353            }
1354            let gs = &self.gs;
1355            let w0 = font.base.width(code);
1356            let mut trm = mul(&[gs.size * gs.th, 0.0, 0.0, gs.size, 0.0, gs.rise], tm);
1357            if font.base.vertical {
1358                // the origin of a vertical glyph: half its width left, 0.88 up -- in glyph space,
1359                // which trm scales by the size (and the horizontal scaling) itself
1360                let hw = font.base.h_width(code);
1361                trm = mul(&[1.0, 0.0, 0.0, 1.0, -hw / 2.0, -0.88], &trm);
1362            }
1363            self.glyph(&font, code, &trm, res);
1364            let w0 = font.width(code).unwrap_or(w0);
1365            let gs = &self.gs;
1366            let space = if len == 1 && code == 32 { gs.tw } else { 0.0 };
1367            let (tx, ty) = if font.base.vertical { (0.0, w0 * gs.size + gs.tc + space) } else { ((w0 * gs.size + gs.tc + space) * gs.th, 0.0) };
1368            *tm = finite(mul(&[1.0, 0.0, 0.0, 1.0, tx, ty], tm));
1369        }
1370        self.codes = codes;
1371    }
1372
1373    /// one glyph: trm is glyph-independent text space -> user space (before the CTM)
1374    fn glyph(&mut self, font: &Rc<fonts::GFont>, code: u32, trm: &M, res: &Rc<Res>) {
1375        let mode = self.gs.mode;
1376        if let Some(t3) = &font.type3 {
1377            if mode >= 4 {
1378                self.t3_clip = true;
1379            }
1380            if mode != 3 && mode != 7 {
1381                self.type3(t3, code, &mul(trm, &self.gs.ctm), res);
1382            }
1383            return;
1384        }
1385        let Some(g) = font.glyph(code) else { return };
1386        let to_user = mul(&font.matrix, trm);
1387        let segs = outline_segs(&g);
1388        let ctm = self.gs.ctm;
1389        let mut dev = mul(&to_user, &ctm);
1390        // the origin as Poppler places glyphs: down to a whole pixel, across to a quarter (a
1391        // baseline stays on one row of pixels, a glyph looks the same wherever it is)
1392        let (ox, oy) = apply(&mul(trm, &ctm), 0.0, 0.0);
1393        let placed = ox.abs() < 1e7 && oy.abs() < 1e7;
1394        // the origin in quarter pixels across and whole pixels down
1395        let (qx, py) = if placed { (color::floor(ox * 4.0) as i64, color::floor(oy) as i64) } else { (0, 0) };
1396        if placed {
1397            dev[4] += qx as f64 / 4.0 - ox;
1398            dev[5] += py as f64 - oy;
1399        }
1400        let fill = matches!(mode, 0 | 2 | 4 | 6);
1401        let stroke = matches!(mode, 1 | 2 | 5 | 6);
1402        let clip = mode >= 4;
1403        // the glyph's box around its origin on the device: one far from its origin or larger
1404        // than the coverage cache takes is filled as a path (the cache draws it where every
1405        // coordinate is positive, a million pixels away if need be)
1406        let (mut mx, mut my, mut nx, mut ny) = (0f64, 0f64, 0f64, 0f64);
1407        for &(x, y) in &g.pts {
1408            let (a, b) = apply(&[dev[0], dev[1], dev[2], dev[3], 0.0, 0.0], x as f64, y as f64);
1409            mx = mx.min(a);
1410            my = my.min(b);
1411            nx = nx.max(a);
1412            ny = ny.max(b);
1413        }
1414        let side = (canvas::COVER_SIDE / 2) as f64;
1415        let small = mx > -side && my > -side && nx < side && ny < side && (nx - mx + 4.0) * (ny - my + 4.0) < (1u64 << 22) as f64;
1416        if fill && placed && small && self.hidden == 0 && !self.stopped() {
1417            // a glyph drawn once per font, code, size and quarter pixel, then placed
1418            let (gx, gy) = (qx.div_euclid(4), py);
1419            let phase = qx.rem_euclid(4) as u8;
1420            let key = (Rc::as_ptr(font) as usize, code, [dev[0].to_bits(), dev[1].to_bits(), dev[2].to_bits(), dev[3].to_bits()], phase);
1421            let cache = self.doc.render_cache();
1422            let hit = cache.glyphs.borrow().get(&key).map(|e| e.1.clone());
1423            let cover = match hit {
1424                Some(c) => c,
1425                None => {
1426                    // drawn where every coordinate is positive (the rasterizer's rows start there)
1427                    let (sx, sy) = (color::ceil(-mx).clamp(0.0, side) + 2.0, color::ceil(-my).clamp(0.0, side) + 2.0);
1428                    let local = [dev[0], dev[1], dev[2], dev[3], phase as f64 / 4.0 + sx, sy];
1429                    self.lines(&segs, &local);
1430                    let c = canvas::Cover::of(&mut self.ras, sx as i32, sy as i32).map(Rc::new);
1431                    let bytes = c.as_ref().map_or(0, |c| c.a.len() + 64);
1432                    if cache.glyph_bytes.get() + bytes > GLYPH_CACHE {
1433                        cache.glyphs.borrow_mut().clear();
1434                        cache.glyph_bytes.set(0);
1435                    }
1436                    cache.glyph_bytes.set(cache.glyph_bytes.get() + bytes);
1437                    // the font is kept with its glyphs: its address stays its own
1438                    cache.glyphs.borrow_mut().insert(key, (font.clone(), c.clone()));
1439                    c
1440                }
1441            };
1442            if let Some(c) = cover {
1443                {
1444                    let (ox, oy) = (gx as i32, gy as i32);
1445                    let saved = core::mem::take(&mut self.ras);
1446                    // a pattern paint needs the area: the glyph's box
1447                    self.ras.lines_begin();
1448                    let (x0, y0) = ((ox + c.x) as f32, (oy + c.y) as f32);
1449                    self.ras.emit_line(x0, y0, x0 + c.w as f32, y0 + c.h as f32);
1450                    self.paint(false, &mut |run, src, alpha| {
1451                        let Run { layers, gs, .. } = run;
1452                        let Some(layer) = layers.last_mut() else { return };
1453                        let put = Put { clip: &gs.clip, alpha, blend: gs.blend, smask: gs.smask.as_deref() };
1454                        let n = canvas::fill_cover(layer, &c, ox, oy, src, &put);
1455                        run.spend(n);
1456                    });
1457                    self.ras = saved;
1458                }
1459            }
1460        } else if fill {
1461            self.lines(&segs, &dev);
1462            self.fill_ras(RULE_NONZERO, false);
1463        }
1464        if stroke {
1465            let user: Vec<Seg> = segs
1466                .iter()
1467                .map(|s| match *s {
1468                    Seg::M(x, y) => {
1469                        let (a, b) = apply(&to_user, x, y);
1470                        Seg::M(a, b)
1471                    }
1472                    Seg::L(x, y) => {
1473                        let (a, b) = apply(&to_user, x, y);
1474                        Seg::L(a, b)
1475                    }
1476                    Seg::C(c) => {
1477                        let (a, b) = apply(&to_user, c[0], c[1]);
1478                        let (e, f) = apply(&to_user, c[2], c[3]);
1479                        let (g, h) = apply(&to_user, c[4], c[5]);
1480                        Seg::C([a, b, e, f, g, h])
1481                    }
1482                    Seg::Z => Seg::Z,
1483                })
1484                .collect();
1485            if self.stroke_lines(&user, &ctm) {
1486                self.fill_ras(RULE_NONZERO, true);
1487            }
1488        }
1489        if clip {
1490            let tc = self.text_clip.get_or_insert_with(Path::default);
1491            add_segs(tc, &segs, &dev);
1492        }
1493    }
1494
1495    fn type3(&mut self, t3: &fonts::Type3, code: u32, trm_dev: &M, res: &Rc<Res>) {
1496        let Some(Some(proc_)) = t3.procs.get(code as usize) else { return };
1497        if self.depth >= MAX_DEPTH {
1498            return;
1499        }
1500        // decoded once for the page (each glyph decoded its CharProc again), within T3_CACHE
1501        let key = (proc_.start, proc_.end);
1502        let data = match self.t3_procs.get(&key) {
1503            Some(d) => d.clone(),
1504            None => {
1505                let d = self.doc.decode(proc_).ok().map(Rc::new);
1506                let n = d.as_ref().map_or(0, |d| d.len());
1507                if !self.charge(((proc_.raw_len() + n) / BYTES_PER_OP) as u64) {
1508                    return;
1509                }
1510                if self.t3_bytes + n <= T3_CACHE {
1511                    self.t3_bytes += n;
1512                    self.t3_procs.insert(key, d.clone());
1513                }
1514                d
1515            }
1516        };
1517        let Some(data) = data else { return };
1518        let fres = match &t3.res {
1519            Some(r) => t3.run_res.get_or_init(|| Rc::new(Res::of(self.doc, r))).clone(),
1520            None => res.clone(),
1521        };
1522        let saved = self.gs.clone();
1523        let saved_path = core::mem::take(&mut self.path);
1524        let saved_unc = self.uncolored;
1525        let saved_base = self.base;
1526        let saved_tc = self.text_clip.take();
1527        self.gs.ctm = finite(mul(&t3.matrix, trm_dev));
1528        self.base = self.gs.ctm;
1529        self.depth += 1;
1530        self.run(&data, &fres);
1531        self.depth -= 1;
1532        self.gs = saved;
1533        self.path = saved_path;
1534        self.uncolored = saved_unc;
1535        self.base = saved_base;
1536        self.text_clip = saved_tc;
1537    }
1538
1539    // ------------------------------------------------------------ XObjects
1540
1541    fn form(&mut self, o: &Object) -> Option<Rc<Form>> {
1542        let r = o.as_ref();
1543        if let Some(f) = r.and_then(|r| self.form_cache.get(&r)) {
1544            return f.clone();
1545        }
1546        let doc = self.doc;
1547        let mut read = 0;
1548        let built = match doc.resolve(o) {
1549            Object::Stream(s) => doc.decode(&s).ok().map(|data| {
1550                read = s.raw_len() + data.len();
1551                let res = s.dict.get("Resources").map(|x| Rc::new(Res::of(doc, &doc.dict(x))));
1552                let matrix = m6(&color::nums(doc, &doc.key(&s.dict, "Matrix"))).map(finite).unwrap_or(ID);
1553                let bbox = doc.key(&s.dict, "BBox").as_rect();
1554                let group = doc.dict(&s.dict.get("Group").cloned().unwrap_or_default()).is("S", "Transparency");
1555                Rc::new(Form { data, res, matrix, bbox, group, oc: s.dict.get("OC").cloned() })
1556            }),
1557            _ => None,
1558        };
1559        if !self.charge((read / BYTES_PER_OP) as u64) {
1560            return None;
1561        }
1562        if let Some(r) = r {
1563            self.form_cache.insert(r, built.clone());
1564        }
1565        built
1566    }
1567
1568    fn draw_form(&mut self, o: &Object, res: &Rc<Res>, extra: Option<M>) {
1569        let r = o.as_ref();
1570        if self.depth >= MAX_DEPTH || r.is_some_and(|r| self.forms.contains(&r)) {
1571            return;
1572        }
1573        let Some(form) = self.form(o) else { return };
1574        self.draw_built(&form, r, res, extra);
1575    }
1576
1577    /// a form XObject loaded (or made: a field's appearance) drawn under the current state
1578    fn draw_built(&mut self, form: &Rc<Form>, r: Option<Ref>, res: &Rc<Res>, extra: Option<M>) {
1579        if self.depth >= MAX_DEPTH {
1580            return;
1581        }
1582        if let Some(oc) = &form.oc {
1583            if !self.oc_visible(oc) {
1584                return;
1585            }
1586        }
1587        let saved = self.gs.clone();
1588        let saved_path = core::mem::take(&mut self.path);
1589        let saved_base = self.base;
1590        let ctm0 = match extra {
1591            Some(m) => mul(&m, &self.gs.ctm),
1592            None => self.gs.ctm,
1593        };
1594        self.gs.ctm = finite(mul(&form.matrix, &ctm0));
1595        self.base = self.gs.ctm;
1596        if let Some(b) = form.bbox {
1597            self.clip_rect_user(&b);
1598        }
1599        let fres = form.res.clone().unwrap_or_else(|| res.clone());
1600        self.forms.push(r.unwrap_or(Ref { num: u32::MAX, generation: 0 }));
1601        self.depth += 1;
1602        let group = form.group && (saved.fill_alpha < 1.0 || saved.blend != Blend::Normal || saved.smask.is_some());
1603        if group {
1604            // a transparency group: drawn into a layer of its own, then composited as one
1605            let rect = canvas::intersect(self.gs.clip.rect, self.layer_rect());
1606            match Layer::new(rect) {
1607                Some(l) if !canvas::is_empty(rect) => {
1608                    self.layers.push(l);
1609                    self.gs.fill_alpha = 1.0;
1610                    self.gs.stroke_alpha = 1.0;
1611                    self.gs.blend = Blend::Normal;
1612                    self.gs.smask = None;
1613                    self.run(&form.data, &fres);
1614                    let l = self.layers.pop();
1615                    if let (Some(l), Some(dst)) = (l, self.layers.last_mut()) {
1616                        let put = Put { clip: &saved.clip, alpha: to8(saved.fill_alpha), blend: saved.blend, smask: saved.smask.as_deref() };
1617                        let n = canvas::composite(dst, &l, &put);
1618                        self.spend(n);
1619                    }
1620                }
1621                _ => {}
1622            }
1623        } else {
1624            self.run(&form.data, &fres);
1625        }
1626        self.depth -= 1;
1627        self.forms.pop();
1628        self.gs = saved;
1629        self.path = saved_path;
1630        self.base = saved_base;
1631    }
1632
1633    fn xobject(&mut self, name: &[u8], res: &Rc<Res>) {
1634        let Some(o) = res.xobjects.get_bytes(name).cloned() else { return };
1635        let sub = match self.doc.resolve(&o) {
1636            Object::Stream(s) => s.dict.name("Subtype").map(<[u8]>::to_vec),
1637            _ => None,
1638        };
1639        match sub.as_deref() {
1640            Some(b"Form") => self.draw_form(&o, res, None),
1641            Some(b"Image") => {
1642                if self.hidden > 0 {
1643                    return;
1644                }
1645                let img = match o.as_ref().map(|r| (r, self.gs.intent, res.key)) {
1646                    Some(r) => match self.images.get(&r) {
1647                        Some(i) => i.clone(),
1648                        None => {
1649                            let i = image::Img::load_xobject(self, &o, res);
1650                            // kept within IMAGE_CACHE bytes (256 images of a GB each before)
1651                            let n = i.as_ref().map_or(0, |i| i.px.len());
1652                            if self.images.len() < 256 && self.image_bytes + n <= IMAGE_CACHE {
1653                                self.image_bytes += n;
1654                                self.images.insert(r, i.clone());
1655                            }
1656                            i
1657                        }
1658                    },
1659                    None => image::Img::load_xobject(self, &o, res),
1660                };
1661                if let Some(img) = img {
1662                    if img.oc.as_ref().is_none_or(|oc| self.oc_visible(oc)) {
1663                        image::draw(self, &img);
1664                    }
1665                }
1666            }
1667            _ => {}
1668        }
1669    }
1670
1671    // ------------------------------------------------------------ optional content
1672
1673    fn oc_visible(&self, o: &Object) -> bool {
1674        let doc = self.doc;
1675        let r = o.as_ref();
1676        let d = doc.dict(o);
1677        if d.is("Type", "OCMD") {
1678            let refs: Vec<Ref> = match doc.key(&d, "OCGs") {
1679                Object::Array(a) => a.iter().filter_map(Object::as_ref).collect(),
1680                _ => d.get("OCGs").and_then(Object::as_ref).into_iter().collect(),
1681            };
1682            if refs.is_empty() {
1683                return true;
1684            }
1685            let on = |r: &Ref| !self.oc_off.contains(r);
1686            return match d.name("P") {
1687                Some(b"AllOn") => refs.iter().all(on),
1688                Some(b"AnyOff") => refs.iter().any(|r| !on(r)),
1689                Some(b"AllOff") => refs.iter().all(|r| !on(r)),
1690                _ => refs.iter().any(on),
1691            };
1692        }
1693        r.is_none_or(|r| !self.oc_off.contains(&r))
1694    }
1695
1696    // ------------------------------------------------------------ the content stream
1697
1698    fn run(&mut self, content: &[u8], res: &Rc<Res>) {
1699        if !self.charge((content.len() / BYTES_PER_OP) as u64) {
1700            return;
1701        }
1702        let mut stack: Vec<Gs> = Vec::new();
1703        let mut extra_q = 0usize;
1704        let (mut tm, mut tlm) = (ID, ID);
1705        let mc_base = self.mc.len();
1706        let mut clip: Option<u32> = None;
1707        for op in Ops::new(content) {
1708            self.ops += 1;
1709            if self.ops > MAX_OPS {
1710                self.error.get_or_insert(Error::Limit("the operators of a page"));
1711            }
1712            if self.stopped() {
1713                break;
1714            }
1715            let a = &op.operands;
1716            let n = |i: usize| a.get(i).and_then(Object::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0);
1717            match op.operator {
1718                b"q" => {
1719                    if stack.len() < MAX_STACK {
1720                        stack.push(self.gs.clone());
1721                    } else {
1722                        extra_q += 1;
1723                    }
1724                }
1725                b"Q" => {
1726                    if extra_q > 0 {
1727                        extra_q -= 1;
1728                    } else if let Some(g) = stack.pop() {
1729                        self.gs = g;
1730                    }
1731                }
1732                b"cm" if a.len() >= 6 => {
1733                    let v = nums(&a[a.len() - 6..]);
1734                    self.gs.ctm = finite(mul(&[v[0], v[1], v[2], v[3], v[4], v[5]], &self.gs.ctm));
1735                }
1736                b"w" => self.gs.lw = n(0).abs(),
1737                b"J" => self.gs.cap = n(0).clamp(0.0, 2.0) as u32,
1738                b"j" => self.gs.join = n(0).clamp(0.0, 2.0) as u32,
1739                b"M" => self.gs.miter = n(0),
1740                b"d" if a.len() >= 2 => {
1741                    if let Some(arr) = a[0].as_array() {
1742                        self.gs.dash = Rc::new(nums(arr).into_iter().take(64).collect());
1743                        self.gs.phase = n(1);
1744                    }
1745                }
1746                b"gs" => {
1747                    if let Some(d) = a.first().and_then(Object::as_name).and_then(|nm| res.ext.get_bytes(nm)).map(|o| self.doc.dict(o)) {
1748                        self.ext_gstate(&d, res);
1749                    }
1750                }
1751                // paths
1752                b"m" => {
1753                    self.cur = (n(0), n(1));
1754                    self.start = self.cur;
1755                    self.path.push(Seg::M(n(0), n(1)));
1756                }
1757                b"l" => {
1758                    self.cur = (n(0), n(1));
1759                    self.path.push(Seg::L(n(0), n(1)));
1760                }
1761                b"c" => {
1762                    self.path.push(Seg::C([n(0), n(1), n(2), n(3), n(4), n(5)]));
1763                    self.cur = (n(4), n(5));
1764                }
1765                b"v" => {
1766                    self.path.push(Seg::C([self.cur.0, self.cur.1, n(0), n(1), n(2), n(3)]));
1767                    self.cur = (n(2), n(3));
1768                }
1769                b"y" => {
1770                    self.path.push(Seg::C([n(0), n(1), n(2), n(3), n(2), n(3)]));
1771                    self.cur = (n(2), n(3));
1772                }
1773                b"h" => {
1774                    self.path.push(Seg::Z);
1775                    self.cur = self.start;
1776                }
1777                b"re" => {
1778                    let (x, y, w, h) = (n(0), n(1), n(2), n(3));
1779                    self.path.extend([Seg::M(x, y), Seg::L(x + w, y), Seg::L(x + w, y + h), Seg::L(x, y + h), Seg::Z]);
1780                    self.cur = (x, y);
1781                    self.start = (x, y);
1782                }
1783                b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"n" => {
1784                    if self.path.len() > 1 << 22 {
1785                        self.path.clear();
1786                    }
1787                    let o = op.operator;
1788                    let close = matches!(o, b"s" | b"b" | b"b*");
1789                    let fill = match o {
1790                        b"f" | b"F" | b"B" | b"b" => Some(RULE_NONZERO),
1791                        b"f*" | b"B*" | b"b*" => Some(RULE_EVENODD),
1792                        _ => None,
1793                    };
1794                    let stroke = matches!(o, b"S" | b"s" | b"B" | b"B*" | b"b" | b"b*");
1795                    if o != b"n" {
1796                        self.paint_path(fill, stroke, close);
1797                    }
1798                    self.end_path(clip.take());
1799                }
1800                b"W" => clip = Some(RULE_NONZERO),
1801                b"W*" => clip = Some(RULE_EVENODD),
1802                // colours
1803                b"CS" | b"cs" => {
1804                    if let Some(o) = a.first() {
1805                        let o = o.clone();
1806                        if let Some(c) = self.colorspace(&o, res) {
1807                            self.set_space(op.operator == b"CS", c);
1808                        }
1809                    }
1810                }
1811                b"ri" => {
1812                    if let Some(n) = a.first().and_then(Object::as_name) {
1813                        self.set_intent(color::intent_of(n));
1814                    }
1815                }
1816                b"SC" | b"SCN" => self.set_color(true, a, res),
1817                b"sc" | b"scn" => self.set_color(false, a, res),
1818                b"G" | b"g" | b"RG" | b"rg" | b"K" | b"k" => {
1819                    let stroke = op.operator[0].is_ascii_uppercase();
1820                    let cs = self.device_cs(
1821                        match op.operator {
1822                            b"G" | b"g" => 0,
1823                            b"RG" | b"rg" => 1,
1824                            _ => 2,
1825                        },
1826                        res,
1827                    );
1828                    if !self.uncolored {
1829                        self.set_space(stroke, cs);
1830                        let p = if stroke { &mut self.gs.stroke } else { &mut self.gs.fill };
1831                        p.set(&nums(a));
1832                    }
1833                }
1834                b"sh" => {
1835                    if let Some(o) = a.first().and_then(Object::as_name).and_then(|nm| res.shadings.get_bytes(nm)).cloned() {
1836                        if self.hidden == 0 {
1837                            shade::sh(self, &o, res);
1838                        }
1839                    }
1840                }
1841                // text
1842                b"BT" => {
1843                    tm = ID;
1844                    tlm = ID;
1845                    self.text_clip = None;
1846                    self.t3_clip = false;
1847                }
1848                b"ET" => {
1849                    if let Some(p) = self.text_clip.take() {
1850                        p.fill_lines(&mut self.ras);
1851                        self.clip_ras(RULE_NONZERO);
1852                    } else if self.gs.mode >= 4 && !self.t3_clip {
1853                        // clip text that drew nothing clips everything away
1854                        self.gs.clip = Clip { rect: [0, 0, 0, 0], mask: None };
1855                    }
1856                }
1857                b"Tf" if a.len() >= 2 => {
1858                    if let Some(nm) = a[a.len() - 2].as_name() {
1859                        let f = res.fonts.get_bytes(nm).cloned();
1860                        self.gs.font = f.and_then(|o| self.font_of(&o));
1861                    }
1862                    self.gs.size = n(a.len() - 1);
1863                }
1864                b"Tc" => self.gs.tc = n(0),
1865                b"Tw" => self.gs.tw = n(0),
1866                b"Tz" => self.gs.th = n(0) / 100.0,
1867                b"TL" => self.gs.tl = n(0),
1868                b"Ts" => self.gs.rise = n(0),
1869                b"Tr" => self.gs.mode = n(0).clamp(0.0, 7.0) as i64,
1870                b"Td" | b"TD" if a.len() >= 2 => {
1871                    if op.operator == b"TD" {
1872                        self.gs.tl = -n(1);
1873                    }
1874                    tlm = finite(mul(&[1.0, 0.0, 0.0, 1.0, n(0), n(1)], &tlm));
1875                    tm = tlm;
1876                }
1877                b"Tm" if a.len() >= 6 => {
1878                    let v = nums(&a[a.len() - 6..]);
1879                    tlm = finite([v[0], v[1], v[2], v[3], v[4], v[5]]);
1880                    tm = tlm;
1881                }
1882                b"T*" => {
1883                    tlm = finite(mul(&[1.0, 0.0, 0.0, 1.0, 0.0, -self.gs.tl], &tlm));
1884                    tm = tlm;
1885                }
1886                b"Tj" => {
1887                    if let Some(s) = a.last().and_then(Object::as_bytes) {
1888                        if self.hidden == 0 {
1889                            self.show(&mut tm, s, res);
1890                        }
1891                    }
1892                }
1893                b"'" | b"\"" => {
1894                    if op.operator == b"\"" && a.len() >= 3 {
1895                        self.gs.tw = n(0);
1896                        self.gs.tc = n(1);
1897                    }
1898                    tlm = finite(mul(&[1.0, 0.0, 0.0, 1.0, 0.0, -self.gs.tl], &tlm));
1899                    tm = tlm;
1900                    if let Some(s) = a.last().and_then(Object::as_bytes) {
1901                        if self.hidden == 0 {
1902                            self.show(&mut tm, s, res);
1903                        }
1904                    }
1905                }
1906                b"TJ" => {
1907                    let Some(arr) = a.last().and_then(Object::as_array) else { continue };
1908                    let vertical = self.gs.font.as_ref().is_some_and(|f| f.base.vertical);
1909                    for e in arr {
1910                        match e {
1911                            Object::String(s) => {
1912                                if self.hidden == 0 {
1913                                    self.show(&mut tm, s, res);
1914                                }
1915                            }
1916                            o => {
1917                                if let Some(v) = o.as_f64().filter(|v| v.is_finite()) {
1918                                    let adj = -v / 1000.0 * self.gs.size;
1919                                    let t = if vertical { [1.0, 0.0, 0.0, 1.0, 0.0, adj] } else { [1.0, 0.0, 0.0, 1.0, adj * self.gs.th, 0.0] };
1920                                    tm = finite(mul(&t, &tm));
1921                                }
1922                            }
1923                        }
1924                    }
1925                }
1926                b"d0" => {}
1927                b"d1" => self.uncolored = true,
1928                // XObjects and inline images
1929                b"Do" => {
1930                    if let Some(nm) = a.first().and_then(Object::as_name) {
1931                        let nm = nm.to_vec();
1932                        self.xobject(&nm, res);
1933                    }
1934                }
1935                b"BI" if a.len() >= 2 => {
1936                    if self.hidden == 0 {
1937                        if let (Object::Dict(d), Some(data)) = (&a[0], a[1].as_bytes()) {
1938                            if let Some(img) = image::Img::load_inline(self, d, data, res) {
1939                                image::draw(self, &img);
1940                            }
1941                        }
1942                    }
1943                }
1944                // marked content: optional content hides what it holds
1945                b"BDC" | b"BMC" => {
1946                    let mut hide = false;
1947                    if op.operator == b"BDC" && a.first().and_then(Object::as_name) == Some(b"OC") {
1948                        let p = match a.get(1) {
1949                            Some(Object::Name(nm)) => res.props.get_bytes(&nm.0).cloned(),
1950                            Some(o) => Some(o.clone()),
1951                            None => None,
1952                        };
1953                        if let Some(p) = p {
1954                            hide = !self.oc_visible(&p);
1955                        }
1956                    }
1957                    if self.mc.len() < 1 << 16 {
1958                        self.mc.push(hide);
1959                        if hide {
1960                            self.hidden += 1;
1961                        }
1962                    }
1963                }
1964                b"EMC" => {
1965                    if self.mc.len() > mc_base {
1966                        if self.mc.pop() == Some(true) {
1967                            self.hidden -= 1;
1968                        }
1969                    }
1970                }
1971                _ => {}
1972            }
1973        }
1974        // marked content left open by this stream ends with it
1975        while self.mc.len() > mc_base {
1976            if self.mc.pop() == Some(true) {
1977                self.hidden -= 1;
1978            }
1979        }
1980    }
1981
1982    // ------------------------------------------------------------ annotations
1983
1984    fn annotations(&mut self, page: &Page) {
1985        let doc = self.doc;
1986        let Object::Array(annots) = doc.key(&page.dict, "Annots") else { return };
1987        let dev = self.base;
1988        // fields whose appearance the viewer is to make (12.7.2)
1989        let need = doc.dict(&doc.catalog().get("AcroForm").cloned().unwrap_or_default()).get("NeedAppearances").map(|o| doc.resolve(o)).and_then(|o| o.as_bool()) == Some(true);
1990        for a in annots.iter().take(1 << 14) {
1991            if self.stopped() {
1992                break;
1993            }
1994            let d = doc.dict(a);
1995            let flags = doc.key(&d, "F").as_int().unwrap_or(0);
1996            if flags & (2 | 32) != 0 || d.is("Subtype", "Popup") {
1997                continue;
1998            }
1999            if let Some(oc) = d.get("OC") {
2000                if !self.oc_visible(oc) {
2001                    continue;
2002                }
2003            }
2004            let Some(rect) = doc.key(&d, "Rect").as_rect() else { continue };
2005            if d.is("Subtype", "Widget") {
2006                if let Some((ap, resd, work)) = crate::edit::widget_ap(doc, &d, a.as_ref(), need, &doc.render.field_codes) {
2007                    if !self.charge((ap.content.len() / BYTES_PER_OP) as u64 + 1 + work / 64) {
2008                        break;
2009                    }
2010                    let form = Rc::new(Form { data: ap.content, res: Some(Rc::new(Res::of(doc, &resd))), matrix: ap.matrix.unwrap_or(ID), bbox: Some(ap.bbox), group: false, oc: None });
2011                    let fit = fit_rect(&ap.bbox, &form.matrix, &rect);
2012                    let res = Rc::new(Res::of(doc, &page.resources));
2013                    // the state of a page's beginning, not where its content left it (Tr 3 ...)
2014                    let saved = core::mem::replace(&mut self.gs, Gs::fresh(dev, self.layers[0].rect));
2015                    self.draw_built(&form, None, &res, Some(fit));
2016                    self.gs = saved;
2017                    continue;
2018                }
2019            }
2020            let ap = doc.dict(&d.get("AP").cloned().unwrap_or_default());
2021            let Some(n) = ap.get("N").cloned() else { continue };
2022            let stream = match doc.resolve(&n) {
2023                Object::Stream(_) => n,
2024                Object::Dict(states) => {
2025                    let Some(st) = d.name("AS") else { continue };
2026                    match states.get_bytes(st) {
2027                        Some(o) => o.clone(),
2028                        None => continue,
2029                    }
2030                }
2031                _ => continue,
2032            };
2033            let Some(form) = self.form(&stream) else { continue };
2034            let Some(bbox) = form.bbox else { continue };
2035            let fit = fit_rect(&bbox, &form.matrix, &rect);
2036            let res = Rc::new(Res::of(doc, &page.resources));
2037            let saved = core::mem::replace(&mut self.gs, Gs::fresh(dev, self.layers[0].rect));
2038            self.draw_form(&stream, &res, Some(fit));
2039            self.gs = saved;
2040        }
2041    }
2042}
2043
2044/// Algorithm 8.1: a form's bbox through its matrix, fitted onto a rectangle
2045fn fit_rect(bbox: &[f64; 4], m: &M, rect: &[f64; 4]) -> M {
2046    let r = [rect[0].min(rect[2]), rect[1].min(rect[3]), rect[0].max(rect[2]), rect[1].max(rect[3])];
2047    let tb = transform_box(bbox, m);
2048    let (bw, bh) = (tb[2] - tb[0], tb[3] - tb[1]);
2049    let sx = if bw.abs() > 1e-9 { (r[2] - r[0]) / bw } else { 1.0 };
2050    let sy = if bh.abs() > 1e-9 { (r[3] - r[1]) / bh } else { 1.0 };
2051    [sx, 0.0, 0.0, sy, r[0] - tb[0] * sx, r[1] - tb[1] * sy]
2052}
2053
2054/// the corners of a box through m, as a box
2055fn transform_box(b: &[f64; 4], m: &M) -> [f64; 4] {
2056    let pts = [apply(m, b[0], b[1]), apply(m, b[2], b[1]), apply(m, b[2], b[3]), apply(m, b[0], b[3])];
2057    let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
2058    for (x, y) in pts {
2059        x0 = x0.min(x);
2060        y0 = y0.min(y);
2061        x1 = x1.max(x);
2062        y1 = y1.max(y);
2063    }
2064    [x0, y0, x1, y1]
2065}
2066
2067/// a box in user space through the CTM as a device rectangle (pixels touched)
2068pub(super) fn bbox_rect(b: &[f64; 4], m: &M) -> Rect {
2069    let t = transform_box(b, m);
2070    let c = |v: f64| v.clamp(-1.0e8, 1.0e8);
2071    [canvas::floor(c(t[0]) as f32), canvas::floor(c(t[1]) as f32), canvas::ceil(c(t[2]) as f32) + 1, canvas::ceil(c(t[3]) as f32) + 1]
2072}
2073
2074/// a glyph outline as path segments (TrueType's quadratic contours as cubics)
2075fn outline_segs(g: &fonts::Glyph) -> Vec<Seg> {
2076    use text::outline::{OLT_CUBIC, OLT_OFF};
2077    let mut out = Vec::new();
2078    let mut start = 0usize;
2079    for &e in &g.ends {
2080        let e = (e as usize).min(g.pts.len().saturating_sub(1));
2081        if e < start || start >= g.pts.len() {
2082            start = e + 1;
2083            continue;
2084        }
2085        let pts = &g.pts[start..=e];
2086        let tags = &g.tags[start..=e];
2087        let n = pts.len();
2088        let p = |i: usize| (pts[i % n].0 as f64, pts[i % n].1 as f64);
2089        let quad = tags.iter().any(|&t| t == OLT_OFF);
2090        if quad {
2091            // start at an on-curve point (or the middle of two off-curve ones)
2092            let first_on = tags.iter().position(|&t| t != OLT_OFF);
2093            let (s, origin) = match first_on {
2094                Some(i) => (i, p(i)),
2095                None => {
2096                    let (a, b) = (p(0), p(1));
2097                    (0, ((a.0 + b.0) / 2.0, (a.1 + b.1) / 2.0))
2098                }
2099            };
2100            out.push(Seg::M(origin.0, origin.1));
2101            let mut cur = origin;
2102            let mut ctrl: Option<(f64, f64)> = None;
2103            for k in 1..=n {
2104                let i = (s + k) % n;
2105                let q = p(i);
2106                let end = k == n;
2107                if tags[i] == OLT_OFF {
2108                    if let Some(c) = ctrl {
2109                        let mid = ((c.0 + q.0) / 2.0, (c.1 + q.1) / 2.0);
2110                        out.push(quad_seg(cur, c, mid));
2111                        cur = mid;
2112                    }
2113                    ctrl = Some(q);
2114                    if end {
2115                        out.push(quad_seg(cur, q, origin));
2116                    }
2117                } else {
2118                    let target = if end { origin } else { q };
2119                    match ctrl.take() {
2120                        Some(c) => out.push(quad_seg(cur, c, target)),
2121                        None => out.push(Seg::L(target.0, target.1)),
2122                    }
2123                    cur = target;
2124                }
2125            }
2126            out.push(Seg::Z);
2127        } else {
2128            out.push(Seg::M(p(0).0, p(0).1));
2129            let mut i = 1;
2130            while i < n {
2131                if tags[i] == OLT_CUBIC && i + 1 < n + 1 {
2132                    let c1 = p(i);
2133                    let c2 = p(i + 1);
2134                    let e2 = if i + 2 <= n { p((i + 2) % n) } else { p(0) };
2135                    out.push(Seg::C([c1.0, c1.1, c2.0, c2.1, e2.0, e2.1]));
2136                    i += 3;
2137                } else {
2138                    out.push(Seg::L(p(i).0, p(i).1));
2139                    i += 1;
2140                }
2141            }
2142            out.push(Seg::Z);
2143        }
2144        start = e + 1;
2145    }
2146    out
2147}
2148
2149fn quad_seg(p0: (f64, f64), c: (f64, f64), p1: (f64, f64)) -> Seg {
2150    let c1 = (p0.0 + 2.0 / 3.0 * (c.0 - p0.0), p0.1 + 2.0 / 3.0 * (c.1 - p0.1));
2151    let c2 = (p1.0 + 2.0 / 3.0 * (c.0 - p1.0), p1.1 + 2.0 / 3.0 * (c.1 - p1.1));
2152    Seg::C([c1.0, c1.1, c2.0, c2.1, p1.0, p1.1])
2153}
2154
2155fn add_segs(p: &mut Path, segs: &[Seg], m: &M) {
2156    for s in segs {
2157        match *s {
2158            Seg::M(x, y) => {
2159                let (a, b) = apply(m, x, y);
2160                p.move_f(a as f32, b as f32);
2161            }
2162            Seg::L(x, y) => {
2163                let (a, b) = apply(m, x, y);
2164                p.line_f(a as f32, b as f32);
2165            }
2166            Seg::C(c) => {
2167                let (a, b) = apply(m, c[0], c[1]);
2168                let (e, f) = apply(m, c[2], c[3]);
2169                let (g, h) = apply(m, c[4], c[5]);
2170                p.cubic_f((a as f32, b as f32), (e as f32, f as f32), (g as f32, h as f32));
2171            }
2172            Seg::Z => p.close(),
2173        }
2174    }
2175}
2176