Skip to main content

pdf/
canvas.rs

1// canvas -- drawing on one page: paths, paint, transforms, clipping, images, text, links
2//
3// The canvas writes the page's content stream.  Graphics state that only matters when
4// something is painted (colours, alpha, line width, caps, joins, miter limit, dash, text mode)
5// is kept as wanted and written just before the paint operator that needs it, so a run of
6// paths in the same style writes it once.  Transforms (`cm`) are written at once; a path
7// still open when the transform changes keeps where it was drawn.  Path construction is
8// buffered until it is painted, so no state operator ever lands inside a path object.
9
10use alloc::collections::BTreeSet;
11use alloc::string::String;
12use alloc::vec::Vec;
13
14use crate::geom::{FillRule, LineCap, LineJoin, Matrix, Path, Rgb, Seg, TextMode};
15use crate::obj::{self, num};
16use crate::shading::{self, Alpha, Hatch, Prepared, Shading};
17use crate::{Dest, Document, FontId, Glyph, ImageId, Link, LinkTarget, PageId};
18
19/// where a canvas puts (0, 0) and which way y grows
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
21pub enum Origin {
22    /// the top left corner of the page, y downwards (as gfx, the screen and page layout)
23    TopLeft,
24    /// the bottom left corner, y upwards (PDF's own page space)
25    BottomLeft,
26}
27
28/// alpha in thousandths
29pub(crate) fn alpha_key(a: f64) -> u16 {
30    if a.is_finite() { (a.clamp(0.0, 1.0) * 1000.0 + 0.5) as u16 } else { 1000 }
31}
32
33/// two alphas in thousandths multiplied
34fn alpha_mul(a: u16, b: u16) -> u16 {
35    ((a as u32 * b as u32 + 500) / 1000) as u16
36}
37
38#[derive(Clone, Debug, PartialEq)]
39struct Paint {
40    fill: Rgb,
41    stroke: Rgb,
42    fill_alpha: u16,
43    stroke_alpha: u16,
44    width: f64,
45    cap: LineCap,
46    join: LineJoin,
47    miter: f64,
48    dash: Vec<f64>,
49    phase: f64,
50    text_mode: TextMode,
51}
52
53impl Paint {
54    /// PDF's initial graphics state
55    fn initial() -> Paint {
56        Paint {
57            fill: Rgb::BLACK,
58            stroke: Rgb::BLACK,
59            fill_alpha: 1000,
60            stroke_alpha: 1000,
61            width: 1.0,
62            cap: LineCap::Butt,
63            join: LineJoin::Miter,
64            miter: 10.0,
65            dash: Vec::new(),
66            phase: 0.0,
67            text_mode: TextMode::Fill,
68        }
69    }
70}
71
72/// drawing on one page (Document::canvas).  Coordinates are points (1/72 inch) from the
73/// origin the canvas was made with; what it draws goes into the page when it is dropped, with
74/// every save it left open restored.  Several canvases on one page draw one after the other.
75pub struct Canvas<'a> {
76    doc: &'a mut Document,
77    page: usize,
78    out: Vec<u8>,
79    ctm: Matrix,
80    want: Paint,
81    have: Paint,
82    stack: Vec<(Matrix, Paint, Paint)>,
83    path: Path,
84}
85
86impl<'a> Canvas<'a> {
87    pub(crate) fn new(doc: &'a mut Document, page: usize, origin: Origin) -> Canvas<'a> {
88        let h = doc.pages[page].height;
89        let mut c = Canvas {
90            doc,
91            page,
92            out: Vec::new(),
93            ctm: Matrix::IDENTITY,
94            want: Paint::initial(),
95            have: Paint::initial(),
96            stack: Vec::new(),
97            path: Path::new(),
98        };
99        c.out.extend_from_slice(b"q\n");
100        if origin == Origin::TopLeft {
101            c.write_cm(&Matrix::new(1.0, 0.0, 0.0, -1.0, 0.0, h));
102            c.ctm = Matrix::new(1.0, 0.0, 0.0, -1.0, 0.0, h);
103        }
104        c
105    }
106
107    /// the page this canvas draws on
108    pub fn page(&self) -> PageId {
109        PageId(self.page as u32)
110    }
111
112    pub(crate) fn doc_mut(&mut self) -> &mut Document {
113        self.doc
114    }
115
116    /// width and height of the page in points
117    pub fn page_size(&self) -> (f64, f64) {
118        let p = &self.doc.pages[self.page];
119        (p.width, p.height)
120    }
121
122    /// the current transform from this canvas's coordinates to PDF page space (points from the
123    /// bottom left, y up)
124    pub fn ctm(&self) -> Matrix {
125        self.ctm
126    }
127
128    /// the document (fonts, metrics, shaping) while drawing
129    pub fn document(&self) -> &Document {
130        self.doc
131    }
132
133    // ------------------------------------------------------------------ state
134
135    /// saves the whole state (transform, clip, colours, alpha, stroke and text settings)
136    pub fn save(&mut self) {
137        self.out.extend_from_slice(b"q\n");
138        self.stack.push((self.ctm, self.want.clone(), self.have.clone()));
139    }
140
141    /// back to the state of the matching save (none open: nothing happens)
142    pub fn restore(&mut self) {
143        let Some((ctm, want, have)) = self.stack.pop() else { return };
144        self.out.extend_from_slice(b"Q\n");
145        self.move_path(&ctm);
146        self.ctm = ctm;
147        self.want = want;
148        self.have = have;
149    }
150
151    /// how many saves are open
152    pub fn depth(&self) -> usize {
153        self.stack.len()
154    }
155
156    /// m first, then the current transform (singular or not finite: ignored)
157    pub fn transform(&mut self, m: Matrix) {
158        if !m.is_finite() || m.invert().is_none() {
159            return;
160        }
161        let ctm = m.then(&self.ctm);
162        self.move_path(&ctm);
163        self.ctm = ctm;
164        self.write_cm(&m);
165    }
166
167    pub fn translate(&mut self, tx: f64, ty: f64) {
168        self.transform(Matrix::translate(tx, ty));
169    }
170
171    pub fn scale(&mut self, sx: f64, sy: f64) {
172        self.transform(Matrix::scale(sx, sy));
173    }
174
175    /// radians: counter-clockwise where y points up, clockwise where it points down
176    pub fn rotate(&mut self, angle: f64) {
177        self.transform(Matrix::rotate(angle));
178    }
179
180    /// an open path keeps its place on the page when the transform becomes `ctm`
181    fn move_path(&mut self, ctm: &Matrix) {
182        if self.path.is_empty() || *ctm == self.ctm {
183            return;
184        }
185        if let Some(inv) = ctm.invert() {
186            let m = self.ctm.then(&inv);
187            self.path.transform(&m);
188        }
189    }
190
191    fn write_cm(&mut self, m: &Matrix) {
192        let o = &mut self.out;
193        for v in [m.a, m.b, m.c, m.d, m.e, m.f] {
194            num(o, v);
195            o.push(b' ');
196        }
197        o.extend_from_slice(b"cm\n");
198    }
199
200    pub fn set_fill_color(&mut self, c: Rgb) {
201        self.want.fill = c.clamped();
202    }
203
204    pub fn set_stroke_color(&mut self, c: Rgb) {
205        self.want.stroke = c.clamped();
206    }
207
208    /// opacity of fills, text fills and images, 0 to 1 (kept in thousandths)
209    pub fn set_fill_alpha(&mut self, a: f64) {
210        self.want.fill_alpha = alpha_key(a);
211    }
212
213    /// opacity of strokes, 0 to 1 (kept in thousandths)
214    pub fn set_stroke_alpha(&mut self, a: f64) {
215        self.want.stroke_alpha = alpha_key(a);
216    }
217
218    /// in the coordinates at the time of the stroke (0: the thinnest line the device draws)
219    pub fn set_line_width(&mut self, w: f64) {
220        if w.is_finite() && w >= 0.0 {
221            self.want.width = w;
222        }
223    }
224
225    pub fn set_line_cap(&mut self, cap: LineCap) {
226        self.want.cap = cap;
227    }
228
229    pub fn set_line_join(&mut self, join: LineJoin) {
230        self.want.join = join;
231    }
232
233    /// the longest miter, as a multiple of the line width (at least 1)
234    pub fn set_miter_limit(&mut self, limit: f64) {
235        if limit.is_finite() && limit >= 1.0 {
236            self.want.miter = limit;
237        }
238    }
239
240    /// dashes: lengths on, off, on, ... from `phase` into the pattern; an empty list (or one
241    /// with a negative length or only zeros) draws solid lines
242    pub fn set_dash(&mut self, pattern: &[f64], phase: f64) {
243        let ok = pattern.iter().all(|v| v.is_finite() && *v >= 0.0) && pattern.iter().any(|v| *v > 0.0);
244        if ok && pattern.len() <= 64 {
245            self.want.dash = pattern.to_vec();
246            self.want.phase = if phase.is_finite() { phase } else { 0.0 };
247        } else {
248            self.want.dash.clear();
249            self.want.phase = 0.0;
250        }
251    }
252
253    pub fn set_text_mode(&mut self, mode: TextMode) {
254        self.want.text_mode = mode;
255    }
256
257    fn sync_alpha(&mut self) {
258        let (f, s) = (self.want.fill_alpha, self.want.stroke_alpha);
259        if (f, s) == (self.have.fill_alpha, self.have.stroke_alpha) {
260            return;
261        }
262        let next = self.doc.alphas.len();
263        let i = *self.doc.alpha_ids.entry((f, s)).or_insert(next);
264        if i == next {
265            self.doc.alphas.push((f, s));
266        }
267        let page = &mut self.doc.pages[self.page];
268        page.gstates.insert(i);
269        if f < 1000 || s < 1000 {
270            page.transparency = true;
271        }
272        let _ = core::fmt::Write::write_fmt(&mut obj::Fmt(&mut self.out), format_args!("/G{i} gs\n"));
273        self.have.fill_alpha = f;
274        self.have.stroke_alpha = s;
275    }
276
277    fn sync_fill(&mut self) {
278        if self.want.fill != self.have.fill {
279            let c = self.want.fill;
280            self.color(c, b"rg\n");
281            self.have.fill = c;
282        }
283        self.sync_alpha();
284    }
285
286    fn sync_stroke(&mut self) {
287        if self.want.stroke != self.have.stroke {
288            let c = self.want.stroke;
289            self.color(c, b"RG\n");
290            self.have.stroke = c;
291        }
292        let o = &mut self.out;
293        if self.want.width != self.have.width {
294            num(o, self.want.width);
295            o.extend_from_slice(b" w\n");
296            self.have.width = self.want.width;
297        }
298        if self.want.cap != self.have.cap {
299            o.extend_from_slice(match self.want.cap {
300                LineCap::Butt => b"0 J\n",
301                LineCap::Round => b"1 J\n",
302                LineCap::Square => b"2 J\n",
303            });
304            self.have.cap = self.want.cap;
305        }
306        if self.want.join != self.have.join {
307            o.extend_from_slice(match self.want.join {
308                LineJoin::Miter => b"0 j\n",
309                LineJoin::Round => b"1 j\n",
310                LineJoin::Bevel => b"2 j\n",
311            });
312            self.have.join = self.want.join;
313        }
314        if self.want.miter != self.have.miter {
315            num(o, self.want.miter);
316            o.extend_from_slice(b" M\n");
317            self.have.miter = self.want.miter;
318        }
319        if self.want.dash != self.have.dash || self.want.phase != self.have.phase {
320            obj::nums(o, &self.want.dash);
321            o.push(b' ');
322            num(o, self.want.phase);
323            o.extend_from_slice(b" d\n");
324            self.have.dash = self.want.dash.clone();
325            self.have.phase = self.want.phase;
326        }
327        self.sync_alpha();
328    }
329
330    fn color(&mut self, c: Rgb, op: &[u8]) {
331        let o = &mut self.out;
332        num(o, c.r);
333        o.push(b' ');
334        num(o, c.g);
335        o.push(b' ');
336        num(o, c.b);
337        o.push(b' ');
338        o.extend_from_slice(op);
339    }
340
341    // ------------------------------------------------------------------ paths
342
343    pub fn move_to(&mut self, x: f64, y: f64) {
344        self.path.move_to(x, y);
345    }
346
347    pub fn line_to(&mut self, x: f64, y: f64) {
348        self.path.line_to(x, y);
349    }
350
351    pub fn curve_to(&mut self, x1: f64, y1: f64, x2: f64, y2: f64, x: f64, y: f64) {
352        self.path.curve_to(x1, y1, x2, y2, x, y);
353    }
354
355    pub fn quad_to(&mut self, x1: f64, y1: f64, x: f64, y: f64) {
356        self.path.quad_to(x1, y1, x, y);
357    }
358
359    pub fn close(&mut self) {
360        self.path.close();
361    }
362
363    pub fn rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
364        self.path.rect(x, y, w, h);
365    }
366
367    pub fn rounded_rect(&mut self, x: f64, y: f64, w: f64, h: f64, r: f64) {
368        self.path.rounded_rect(x, y, w, h, r);
369    }
370
371    pub fn ellipse(&mut self, cx: f64, cy: f64, rx: f64, ry: f64) {
372        self.path.ellipse(cx, cy, rx, ry);
373    }
374
375    pub fn circle(&mut self, cx: f64, cy: f64, r: f64) {
376        self.path.circle(cx, cy, r);
377    }
378
379    /// Path::arc on the canvas's path
380    pub fn arc(&mut self, cx: f64, cy: f64, rx: f64, ry: f64, start: f64, sweep: f64) {
381        self.path.arc(cx, cy, rx, ry, start, sweep);
382    }
383
384    /// a prepared path's subpaths, in the current coordinates
385    pub fn append_path(&mut self, p: &Path) {
386        self.path.append(p);
387    }
388
389    fn write_path(&mut self) -> bool {
390        if self.path.is_empty() {
391            return false;
392        }
393        let o = &mut self.out;
394        for s in &self.path.segs {
395            match *s {
396                Seg::Move(x, y) => pts(o, &[x, y], b"m\n"),
397                Seg::Line(x, y) => pts(o, &[x, y], b"l\n"),
398                Seg::Cubic(a, b, c, d, e, f) => pts(o, &[a, b, c, d, e, f], b"c\n"),
399                Seg::Rect(x, y, w, h) => pts(o, &[x, y, w, h], b"re\n"),
400                Seg::Close => o.extend_from_slice(b"h\n"),
401            }
402        }
403        self.path.clear();
404        true
405    }
406
407    /// fills the path and starts a new one
408    pub fn fill(&mut self, rule: FillRule) {
409        if self.path.is_empty() {
410            return;
411        }
412        self.sync_fill();
413        self.write_path();
414        self.out.extend_from_slice(if rule == FillRule::EvenOdd { b"f*\n" } else { b"f\n" });
415    }
416
417    /// strokes the path and starts a new one
418    pub fn stroke(&mut self) {
419        if self.path.is_empty() {
420            return;
421        }
422        self.sync_stroke();
423        self.write_path();
424        self.out.extend_from_slice(b"S\n");
425    }
426
427    /// fills, then strokes the path, and starts a new one
428    pub fn fill_stroke(&mut self, rule: FillRule) {
429        if self.path.is_empty() {
430            return;
431        }
432        self.sync_fill();
433        self.sync_stroke();
434        self.write_path();
435        self.out.extend_from_slice(if rule == FillRule::EvenOdd { b"B*\n" } else { b"B\n" });
436    }
437
438    /// intersects the clip with the path (until the matching restore) and starts a new path
439    pub fn clip(&mut self, rule: FillRule) {
440        if self.write_path() {
441            self.out.extend_from_slice(if rule == FillRule::EvenOdd { b"W* n\n" } else { b"W n\n" });
442        }
443    }
444
445    /// drops the path without painting it
446    pub fn end_path(&mut self) {
447        self.path.clear();
448    }
449
450    pub fn fill_path(&mut self, p: &Path, rule: FillRule) {
451        self.path.clear();
452        self.path.append(p);
453        self.fill(rule);
454    }
455
456    pub fn stroke_path(&mut self, p: &Path) {
457        self.path.clear();
458        self.path.append(p);
459        self.stroke();
460    }
461
462    // ------------------------------------------------------------------ gradients and hatches
463
464    /// paints the gradient over the whole current clip (`sh`), its coordinates in the current user
465    /// space, times the canvas's fill alpha.  Degenerate geometry paints the last stop's colour
466    /// (axial from = to, radial with both radii 0: everywhere; two equal circles: that disk); no
467    /// stops, coordinates that are not finite or a negative radius: nothing.  The path being built
468    /// is kept.
469    pub fn shade(&mut self, s: &Shading) {
470        let prepared = shading::prepare(s);
471        if matches!(prepared, Prepared::Invalid) {
472            return;
473        }
474        let kept = core::mem::take(&mut self.path);
475        let (area, bb) = self.page_area();
476        self.scoped(|c| match prepared {
477            Prepared::Invalid => {}
478            Prepared::Solid(col, a) => {
479                c.path = area;
480                c.paint_solid(col, a, FillRule::NonZero);
481            }
482            Prepared::Disk(at, r, col, a) => {
483                c.path.circle(at[0], at[1], r);
484                c.paint_solid(col, a, FillRule::NonZero);
485            }
486            Prepared::Shade(dict, alpha) => c.paint_shading(dict, alpha, bb),
487        });
488        self.path = kept;
489    }
490
491    /// fills the path with the gradient (q, clip with `rule`, sh, Q) and starts a new path, as
492    /// fill() does; what shade() does with degenerate and invalid gradients, within the path (an
493    /// invalid one drops the path)
494    pub fn fill_shading(&mut self, rule: FillRule, s: &Shading) {
495        if self.path.is_empty() {
496            return;
497        }
498        let prepared = shading::prepare(s);
499        if matches!(prepared, Prepared::Invalid) {
500            self.path.clear();
501            return;
502        }
503        // the soft mask's group covers the path (with a margin against edge antialiasing)
504        let bb = match self.path_bbox() {
505            Some(b) => {
506                let m = (b[2] - b[0]).max(b[3] - b[1]) * 0.05 + 1.0;
507                [b[0] - m, b[1] - m, b[2] + m, b[3] + m]
508            }
509            None => self.page_area().1,
510        };
511        self.scoped(|c| match prepared {
512            Prepared::Invalid => c.path.clear(),
513            Prepared::Solid(col, a) => c.paint_solid(col, a, rule),
514            Prepared::Disk(at, r, col, a) => {
515                c.clip(rule);
516                c.path.circle(at[0], at[1], r);
517                c.paint_solid(col, a, FillRule::NonZero);
518            }
519            Prepared::Shade(dict, alpha) => {
520                c.clip(rule);
521                c.paint_shading(dict, alpha, bb);
522            }
523        });
524    }
525
526    /// fills the path with the hatch's lines (q, clip with `rule`, the lines stroked, Q) and starts
527    /// a new path, as fill() does.  Lines at least as wide as their spacing fill the path solid;
528    /// an angle, spacing, width or origin that is not finite (or a spacing or width <= 0), a path
529    /// with coordinates that are not finite or more than 100 000 lines: nothing, the path dropped
530    pub fn fill_hatch(&mut self, rule: FillRule, h: &Hatch) {
531        if self.path.is_empty() {
532            return;
533        }
534        let ok = h.angle.is_finite() && h.spacing.is_finite() && h.spacing > 0.0 && h.width.is_finite() && h.width > 0.0 && h.origin.iter().all(|v| v.is_finite());
535        let (true, Some(bb)) = (ok, self.path_bbox()) else {
536            self.path.clear();
537            return;
538        };
539        let color = h.color.clamped();
540        let a = alpha_key(h.alpha);
541        if h.width >= h.spacing {
542            self.scoped(|c| c.paint_solid(color, a, rule));
543            return;
544        }
545        let lines = match shading::hatch_lines(h, bb) {
546            Some(l) if !l.is_empty() => l,
547            _ => {
548                self.path.clear();
549                return;
550            }
551        };
552        self.scoped(|c| {
553            c.clip(rule);
554            c.want.stroke = color;
555            c.want.width = h.width;
556            c.want.cap = LineCap::Butt;
557            c.want.join = c.have.join;
558            c.want.miter = c.have.miter;
559            c.want.dash.clear();
560            c.want.phase = 0.0;
561            c.want.stroke_alpha = alpha_mul(c.want.fill_alpha, a);
562            c.sync_stroke();
563            for l in &lines {
564                pts(&mut c.out, &[l[0], l[1]], b"m\n");
565                pts(&mut c.out, &[l[2], l[3]], b"l\n");
566            }
567            c.out.extend_from_slice(b"S\n");
568        });
569    }
570
571    /// f between q and Q; the state the canvas knows is what it was before
572    fn scoped(&mut self, f: impl FnOnce(&mut Self)) {
573        let (want, have) = (self.want.clone(), self.have.clone());
574        self.out.extend_from_slice(b"q\n");
575        f(self);
576        self.out.extend_from_slice(b"Q\n");
577        self.want = want;
578        self.have = have;
579    }
580
581    /// fills the path in one colour, its alpha times the fill alpha
582    fn paint_solid(&mut self, col: Rgb, a: u16, rule: FillRule) {
583        self.want.fill = col;
584        self.want.fill_alpha = alpha_mul(self.want.fill_alpha, a);
585        self.fill(rule);
586    }
587
588    /// `sh` with its alpha: a constant (times the fill alpha) or a soft mask over `bb`
589    fn paint_shading(&mut self, dict: Vec<u8>, alpha: Alpha, bb: [f64; 4]) {
590        let i = self.doc.add_shading(dict);
591        match alpha {
592            Alpha::Const(a) => {
593                self.want.fill_alpha = alpha_mul(self.want.fill_alpha, a);
594                self.sync_alpha();
595            }
596            Alpha::Mask(gray) => {
597                self.sync_alpha();
598                let g = self.doc.add_shading(gray);
599                let m = self.doc.add_mask(g, bb);
600                let page = &mut self.doc.pages[self.page];
601                page.masks.insert(m);
602                page.transparency = true;
603                // the group's space is the user space at this gs, the same as the shading's below
604                let _ = core::fmt::Write::write_fmt(&mut obj::Fmt(&mut self.out), format_args!("/M{m} gs\n"));
605            }
606        }
607        self.doc.pages[self.page].shadings.insert(i);
608        let _ = core::fmt::Write::write_fmt(&mut obj::Fmt(&mut self.out), format_args!("/Sh{i} sh\n"));
609    }
610
611    /// the bounding box of the path's points and control points; None for an empty path or one
612    /// with coordinates that are not finite
613    fn path_bbox(&self) -> Option<[f64; 4]> {
614        let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
615        let mut finite = true;
616        let mut add = |x: f64, y: f64| {
617            finite &= x.is_finite() && y.is_finite();
618            b = [b[0].min(x), b[1].min(y), b[2].max(x), b[3].max(y)];
619        };
620        for s in &self.path.segs {
621            match *s {
622                Seg::Move(x, y) | Seg::Line(x, y) => add(x, y),
623                Seg::Cubic(x1, y1, x2, y2, x, y) => {
624                    add(x1, y1);
625                    add(x2, y2);
626                    add(x, y);
627                }
628                Seg::Rect(x, y, w, h) => {
629                    add(x, y);
630                    add(x + w, y + h);
631                }
632                Seg::Close => {}
633            }
634        }
635        (finite && b.iter().all(|v| v.is_finite())).then_some(b)
636    }
637
638    /// the page in the current user space: its outline and bounding box
639    fn page_area(&self) -> (Path, [f64; 4]) {
640        let (w, h) = self.page_size();
641        let inv = self.ctm.invert().unwrap_or(Matrix::IDENTITY);
642        let c = [inv.apply(0.0, 0.0), inv.apply(w, 0.0), inv.apply(w, h), inv.apply(0.0, h)];
643        let mut p = Path::new();
644        p.move_to(c[0].0, c[0].1);
645        for q in &c[1..] {
646            p.line_to(q.0, q.1);
647        }
648        p.close();
649        let mut b = [c[0].0, c[0].1, c[0].0, c[0].1];
650        for q in &c[1..] {
651            b = [b[0].min(q.0), b[1].min(q.1), b[2].max(q.0), b[3].max(q.1)];
652        }
653        (p, b)
654    }
655
656    // ------------------------------------------------------------------ images
657
658    /// the image upright (as it looks on the page) in the rectangle x, y, w, h of the current
659    /// coordinates
660    pub fn image(&mut self, img: ImageId, x: f64, y: f64, w: f64, h: f64) {
661        let m = if self.ctm.det() < 0.0 { Matrix::new(w, 0.0, 0.0, -h, x, y + h) } else { Matrix::new(w, 0.0, 0.0, h, x, y) };
662        self.image_transform(img, m);
663    }
664
665    /// the image's unit square (row 0 along y = 1, column 0 along x = 0) mapped by m into the
666    /// current coordinates
667    pub fn image_transform(&mut self, img: ImageId, m: Matrix) {
668        let i = img.0 as usize;
669        if i >= self.doc.images.len() || !m.is_finite() || m.invert().is_none() {
670            return;
671        }
672        self.sync_alpha();
673        let page = &mut self.doc.pages[self.page];
674        page.images.insert(i);
675        if self.doc.images[i].has_alpha() {
676            page.transparency = true;
677        }
678        self.out.extend_from_slice(b"q\n");
679        self.write_cm(&m);
680        let _ = core::fmt::Write::write_fmt(&mut obj::Fmt(&mut self.out), format_args!("/Im{i} Do\nQ\n"));
681    }
682
683    // ------------------------------------------------------------------ text
684
685    /// one line of text shaped with the font (kerning, ligatures, marks, bidi), its baseline
686    /// starting at (x, y), `size` the em in points; upright as it looks on the page.  Returns
687    /// the advance along the baseline (0 when nothing was drawn).
688    pub fn text(&mut self, font: FontId, size: f64, x: f64, y: f64, s: &str) -> f64 {
689        self.text_fallback(&[font], size, x, y, s)
690    }
691
692    /// the same with fallback fonts: a run of one script the first font cannot show comes from
693    /// the first of the others that can
694    pub fn text_fallback(&mut self, fonts: &[FontId], size: f64, x: f64, y: f64, s: &str) -> f64 {
695        let glyphs = self.doc.shape(fonts, s);
696        self.glyphs(fonts, size, x, y, &glyphs, s)
697    }
698
699    /// shaped glyphs (in visual order; `Glyph::font` indexes `fonts`) from the
700    /// pen at (x, y); `text` is the shaped string (each glyph's cluster is a byte range of it)
701    /// for search and copy.  Returns the advance.
702    pub fn glyphs(&mut self, fonts: &[FontId], size: f64, x: f64, y: f64, glyphs: &[Glyph], text: &str) -> f64 {
703        if !(size.is_finite() && size > 0.0 && x.is_finite() && y.is_finite()) || glyphs.is_empty() {
704            return 0.0;
705        }
706        let ids: Vec<usize> = fonts.iter().map(|f| f.0 as usize).collect();
707        if ids.is_empty() || ids.iter().any(|&i| i >= self.doc.fonts.len()) {
708            return 0.0;
709        }
710        match self.want.text_mode {
711            TextMode::Fill => self.sync_fill(),
712            TextMode::Stroke => self.sync_stroke(),
713            TextMode::FillStroke => {
714                self.sync_fill();
715                self.sync_stroke();
716            }
717            TextMode::Invisible => {}
718        }
719        let o = &mut self.out;
720        o.extend_from_slice(b"BT\n");
721        if self.want.text_mode != self.have.text_mode {
722            o.extend_from_slice(match self.want.text_mode {
723                TextMode::Fill => b"0 Tr\n",
724                TextMode::Stroke => b"1 Tr\n",
725                TextMode::FillStroke => b"2 Tr\n",
726                TextMode::Invisible => b"3 Tr\n",
727            });
728            self.have.text_mode = self.want.text_mode;
729        }
730        // text space: x along the baseline, y up as seen on the page
731        let flip = if self.ctm.det() < 0.0 { -1.0 } else { 1.0 };
732        pts(o, &[1.0, 0.0, 0.0, flip, x, y], b"Tm\n");
733        let mut run = TextRun { out: Vec::new(), open: false, in_str: false };
734        let mut cur_font = usize::MAX;
735        let (mut lx, mut ly) = (0.0f64, 0.0f64); // line start (Td)
736        let (mut tx, mut ty) = (0.0f64, 0.0f64); // where PDF's text position is
737        let mut pen = 0.0f64;
738        let mut seen: BTreeSet<(usize, usize)> = BTreeSet::new(); // clusters mapped in this call
739        let mut used_fonts: Vec<usize> = Vec::new();
740        for g in glyphs {
741            let Some(&fi) = ids.get(g.font) else { continue };
742            let f = &mut self.doc.fonts[fi];
743            let upem = f.upem as f64;
744            let scale = size / upem;
745            let gid = g.id;
746            let gx = pen + g.x as f64 * scale;
747            let gy = g.y as f64 * scale;
748            pen += g.advance as f64 * scale;
749            if gid >= f.glyphs as u32 {
750                continue;
751            }
752            if fi != cur_font {
753                run.flush(o);
754                let _ = core::fmt::Write::write_fmt(&mut obj::Fmt(o), format_args!("/F{fi} "));
755                num(o, size);
756                o.extend_from_slice(b" Tf\n");
757                cur_font = fi;
758                if !used_fonts.contains(&fi) {
759                    used_fonts.push(fi);
760                }
761            }
762            let dx = gx - tx;
763            if (gy - ty).abs() > 1e-9 || (!run.open && dx.abs() > 1e-9) {
764                run.flush(o);
765                pts(o, &[gx - lx, gy - ly], b"Td\n");
766                lx = gx;
767                ly = gy;
768                tx = gx;
769                ty = gy;
770            } else if dx.abs() > 1e-9 {
771                // TJ: a number moves left by number / 1000 em
772                run.adjust(-dx * 1000.0 / size);
773                tx = gx;
774            }
775            // ToUnicode: the first glyph of a cluster stands for its text
776            let cl = (g.cluster.min(text.len()), g.end.min(text.len()));
777            let unicode = if gid != 0 && cl.0 < cl.1 && text.is_char_boundary(cl.0) && text.is_char_boundary(cl.1) && seen.insert(cl) {
778                Some(String::from(&text[cl.0..cl.1]))
779            } else {
780                None
781            };
782            run.glyph(gid as u16);
783            tx += f.advance(gid as u16) as f64 * scale;
784            f.mark(gid as u16, unicode);
785        }
786        run.flush(o);
787        o.extend_from_slice(b"ET\n");
788        for fi in used_fonts {
789            self.doc.pages[self.page].fonts.insert(fi);
790        }
791        pen
792    }
793
794    // ------------------------------------------------------------------ links
795
796    /// a link on the rectangle x, y, w, h (its box on the page when turned) to a URI
797    pub fn link_uri(&mut self, x: f64, y: f64, w: f64, h: f64, uri: &str) {
798        let rect = self.page_box(x, y, w, h);
799        self.doc.pages[self.page].links.push(Link { rect, target: LinkTarget::Uri(String::from(uri)) });
800    }
801
802    /// a link on the rectangle x, y, w, h to a place in the document
803    pub fn link_dest(&mut self, x: f64, y: f64, w: f64, h: f64, dest: Dest) {
804        let rect = self.page_box(x, y, w, h);
805        self.doc.pages[self.page].links.push(Link { rect, target: LinkTarget::Dest(dest) });
806    }
807
808    /// a destination showing the point (x, y) of this canvas at the top left of the window,
809    /// the zoom unchanged
810    pub fn dest(&self, x: f64, y: f64) -> Dest {
811        let (px, py) = self.ctm.apply(x, y);
812        Dest::Xyz { page: self.page(), left: px, top: py, zoom: None }
813    }
814
815    pub(crate) fn page_box(&self, x: f64, y: f64, w: f64, h: f64) -> [f64; 4] {
816        let c = [self.ctm.apply(x, y), self.ctm.apply(x + w, y), self.ctm.apply(x + w, y + h), self.ctm.apply(x, y + h)];
817        let mut b = [c[0].0, c[0].1, c[0].0, c[0].1];
818        for p in &c[1..] {
819            b[0] = b[0].min(p.0);
820            b[1] = b[1].min(p.1);
821            b[2] = b[2].max(p.0);
822            b[3] = b[3].max(p.1);
823        }
824        b
825    }
826}
827
828impl Drop for Canvas<'_> {
829    fn drop(&mut self) {
830        for _ in 0..=self.stack.len() {
831            self.out.extend_from_slice(b"Q\n");
832        }
833        let out = core::mem::take(&mut self.out);
834        self.doc.pages[self.page].content.extend_from_slice(&out);
835    }
836}
837
838/// numbers separated by spaces, then the operator
839fn pts(o: &mut Vec<u8>, v: &[f64], op: &[u8]) {
840    for x in v {
841        num(o, *x);
842        o.push(b' ');
843    }
844    o.extend_from_slice(op);
845}
846
847/// the array of one TJ
848struct TextRun {
849    out: Vec<u8>,
850    open: bool,
851    in_str: bool,
852}
853
854impl TextRun {
855    fn glyph(&mut self, gid: u16) {
856        if !self.open {
857            self.out.push(b'[');
858            self.open = true;
859        }
860        if !self.in_str {
861            self.out.push(b'<');
862            self.in_str = true;
863        }
864        const H: &[u8; 16] = b"0123456789ABCDEF";
865        for b in gid.to_be_bytes() {
866            self.out.push(H[(b >> 4) as usize]);
867            self.out.push(H[(b & 15) as usize]);
868        }
869    }
870
871    fn adjust(&mut self, n: f64) {
872        if self.in_str {
873            self.out.push(b'>');
874            self.in_str = false;
875        }
876        self.out.push(b' ');
877        num(&mut self.out, n);
878        self.out.push(b' ');
879    }
880
881    fn flush(&mut self, o: &mut Vec<u8>) {
882        if !self.open {
883            return;
884        }
885        if self.in_str {
886            self.out.push(b'>');
887        }
888        self.out.extend_from_slice(b"] TJ\n");
889        o.extend_from_slice(&self.out);
890        self.out.clear();
891        self.open = false;
892        self.in_str = false;
893    }
894}