Skip to main content

rustyfi_backend/
graphics.rs

1//! The drawing data model — paths, colors, and `graphics` elements; the
2//! analog of upstream's `GraphicBase`/`PrePath`/`GraphicD`. Everything here is
3//! already-resolved coordinates/data: no lang-side closure or deferred
4//! computation crosses into this module.
5
6use crate::hbox::PureHorzBox;
7use crate::length::Length;
8
9/// A point in graphics space (upstream `point`; matches the runtime
10/// `Value::Tuple([Length, Length])` representation). Graphics space is
11/// y-**up** (PDF-native); the PDF writer's `place_graphics` flips
12/// page-layout's y-down convention when placing a graphics box on a line.
13pub type Point = (Length, Length);
14
15/// A dash pattern (`dashed-stroke`'s 2nd argument; upstream `graphicD.ml`'s
16/// `type dash = length * length * length`, `(d1, d2, d0)` = on-length,
17/// off-length, phase).
18pub type Dash = (Length, Length, Length);
19
20/// `color.satyh`'s `Gray`/`RGB`/`CMYK` after extraction by `as_color`
21/// (mirrors `evalUtil.ml`'s `get_color` → `DeviceGray`/`DeviceRGB`/
22/// `DeviceCMYK`).
23#[derive(Clone, Copy, Debug, PartialEq)]
24pub enum Color {
25    Gray(f64),
26    Rgb(f64, f64, f64),
27    Cmyk(f64, f64, f64, f64),
28}
29
30/// One path element: a control-point-free straight segment, or a cubic
31/// Bézier (2 control points + destination) — `graphicBase.ml`'s
32/// `point path_element`.
33#[derive(Clone, Copy, Debug, PartialEq)]
34pub enum PathSeg {
35    Line(Point),
36    Bezier(Point, Point, Point),
37}
38
39/// How a subpath closes (`graphicBase.ml`'s `path`'s `cycleopt`): left open,
40/// closed with a straight segment back to the start (`close-with-line`), or
41/// closed with a cubic (`close-with-bezier` — the destination is always the
42/// subpath's own `start`, so only the two control points are stored).
43#[derive(Clone, Copy, Debug, PartialEq)]
44pub enum Closing {
45    Open,
46    Line,
47    Bezier(Point, Point),
48}
49
50/// One `GraphicBase.GeneralPath(start, elems, closing)`.
51#[derive(Clone, Debug, PartialEq)]
52pub struct Subpath {
53    pub start: Point,
54    pub segs: Vec<PathSeg>,
55    pub closing: Closing,
56}
57
58/// The `path` value = upstream `path list` (`unite-path` appends subpath
59/// lists).
60#[derive(Clone, Debug, PartialEq)]
61pub struct Path {
62    pub subpaths: Vec<Subpath>,
63}
64
65/// The `pre-path` value (`PrePath.t`): a start point plus forward-accumulated
66/// segments, before a `terminate-path`/`close-with-line` fixes a closing.
67/// Upstream accumulates in reverse and flips at close time; this port pushes
68/// forward directly, which is unobservable.
69#[derive(Clone, Debug, PartialEq)]
70pub struct PrePath {
71    pub start: Point,
72    pub segs: Vec<PathSeg>,
73}
74
75/// One `graphics` element (`GraphicD.element`). `place_graphics`
76/// (rustyfi-pdf) matches this exhaustively, without a wildcard arm.
77#[derive(Clone, Debug, PartialEq)]
78pub enum GraphicsElem {
79    /// Filled region, even-odd rule (upstream's `op_f'`).
80    Fill(Color, Path),
81    /// Stroked outline at the given line width.
82    Stroke(Length, Color, Path),
83    /// Dashed stroked outline (`dashed-stroke`), rendered with a PDF `d`
84    /// dash-array op alongside the same stroke ops as `Stroke`.
85    DashedStroke(Length, Dash, Color, Path),
86    /// `draw-text`: a text run anchored at `pt` (box-local, y-up; the run's
87    /// leftmost baseline point). `contents` is the run laid out at NATURAL
88    /// width (upstream `LineBreak.natural` = `determine_widths None`,
89    /// `widperfil = 0`; here `fit_cell(boxes, natural_width)`), each box with
90    /// its x offset from `pt`. `width`/`height`/`depth` are the run's
91    /// `natural_metrics`, stored at construction so `graphics_bbox` needs no
92    /// re-measure. Rendered by each PDF writer re-entering its own per-box
93    /// emission at `pt + dx` INSIDE `place_graphics`'s box-local `cm` frame.
94    Text {
95        pt: Point,
96        contents: Vec<(Length, PureHorzBox)>,
97        width: Length,
98        height: Length,
99        depth: Length,
100        /// The accumulated 2×2 linear transform (`linear-transform-graphics`,
101        /// row-major `(a, b, c, d)` — same convention as
102        /// `linear_transform_point`) applied to the run about its local
103        /// origin BEFORE the `pt` translation. `None` means identity: the run
104        /// is drawn upright at `pt`. `Some` appears once
105        /// `rotate-graphics`/`scale-graphics` is composed onto a `draw-text`;
106        /// the writer then emits the run under a `cm` carrying this matrix
107        /// (upstream's lazy `LinearTrans` render-time `cm`).
108        transform: Option<(f64, f64, f64, f64)>,
109    },
110    /// 0.1 collection node (`GraphicD.concat`, dev-0-1-0 `graphicD.ml:23`):
111    /// `unite-graphics`' payload. No 0.0.6-visible primitive builds one, so it
112    /// is unreachable from 0.0.6 rendering by construction.
113    Group(Vec<GraphicsElem>),
114    /// 0.1 clip node (`GraphicD.make_clip`, `graphicD.ml:97-98`): render
115    /// `contents` clipped to `clip` (even-odd, `Op_W'` — `graphicD.ml:331`).
116    /// The port's `Path` already carries N subpaths, standing in for
117    /// upstream's `path list`. Never constructed by any 0.0.6 path, as `Group`.
118    Clip(Path, Vec<GraphicsElem>),
119}
120
121// `shift-path`/`shift-graphics`/`linear-transform-path`/
122// `linear-transform-graphics` are all EAGER point remaps — no lazy
123// `LinearTrans`-wrapper element: every point is rewritten up front, mirroring
124// `graphicBase.ml`'s `shift_path`/`linear_transform_path` (`(x, y) ->
125// (x*a + y*b, x*c + y*d)` for the 2x2 matrix `((a, b), (c, d))`).
126
127/// `shift_path v pt` (`graphicBase.ml`'s `(+@%)`).
128fn shift_point(v: Point, pt: Point) -> Point {
129    (pt.0 + v.0, pt.1 + v.1)
130}
131
132/// `graphicBase.ml`'s `linear_transform_point`: `(x, y) |-> (x*a + y*b, x*c +
133/// y*d)` for matrix `mat = (a, b, c, d)`.
134fn linear_transform_point(mat: (f64, f64, f64, f64), pt: Point) -> Point {
135    let (a, b, c, d) = mat;
136    (pt.0 * a + pt.1 * b, pt.0 * c + pt.1 * d)
137}
138
139/// Map `f` over every point of `path` (subpath starts, every segment's
140/// points — including Bézier control points — and any closing control
141/// points), preserving structure.
142fn map_path(path: &Path, f: impl Fn(Point) -> Point) -> Path {
143    Path {
144        subpaths: path
145            .subpaths
146            .iter()
147            .map(|sub| Subpath {
148                start: f(sub.start),
149                segs: sub
150                    .segs
151                    .iter()
152                    .map(|seg| match *seg {
153                        PathSeg::Line(p) => PathSeg::Line(f(p)),
154                        PathSeg::Bezier(c1, c2, p) => PathSeg::Bezier(f(c1), f(c2), f(p)),
155                    })
156                    .collect(),
157                closing: match sub.closing {
158                    Closing::Open => Closing::Open,
159                    Closing::Line => Closing::Line,
160                    Closing::Bezier(c1, c2) => Closing::Bezier(f(c1), f(c2)),
161                },
162            })
163            .collect(),
164    }
165}
166
167/// `shift-path : point -> path -> path` (vminst.ml:663) — translate every
168/// point of `path` by `v`.
169pub fn shift_path(v: Point, path: &Path) -> Path {
170    map_path(path, |p| shift_point(v, p))
171}
172
173/// `linear-transform-path : float -> float -> float -> float -> path ->
174/// path` (vminst.ml:678) — apply the 2x2 matrix `mat` to every point.
175pub fn linear_transform_path(mat: (f64, f64, f64, f64), path: &Path) -> Path {
176    map_path(path, |p| linear_transform_point(mat, p))
177}
178
179/// `shift-graphics : point -> graphics -> graphics` (vminst.ml:2451) —
180/// `graphicD.ml`'s `shift_element`.
181pub fn shift_graphics(v: Point, elem: &GraphicsElem) -> GraphicsElem {
182    match elem {
183        GraphicsElem::Fill(c, p) => GraphicsElem::Fill(*c, shift_path(v, p)),
184        GraphicsElem::Stroke(w, c, p) => GraphicsElem::Stroke(*w, *c, shift_path(v, p)),
185        GraphicsElem::DashedStroke(w, d, c, p) => {
186            GraphicsElem::DashedStroke(*w, *d, *c, shift_path(v, p))
187        }
188        GraphicsElem::Text { pt, contents, width, height, depth, transform } => {
189            GraphicsElem::Text {
190                pt: shift_point(v, *pt),
191                contents: contents.clone(),
192                width: *width,
193                height: *height,
194                depth: *depth,
195                // A pure translation leaves the run's own 2×2 transform intact
196                // (only `pt` moves) — the affine is `transform·l + pt`.
197                transform: *transform,
198            }
199        }
200        // `graphicD.ml:38`: `Group` maps every child; `Clip` shifts its own
201        // clip path AND recurses into its contents.
202        GraphicsElem::Group(gs) => {
203            GraphicsElem::Group(gs.iter().map(|g| shift_graphics(v, g)).collect())
204        }
205        GraphicsElem::Clip(path, gs) => GraphicsElem::Clip(
206            shift_path(v, path),
207            gs.iter().map(|g| shift_graphics(v, g)).collect(),
208        ),
209    }
210}
211
212/// `linear-transform-graphics : float -> float -> float -> float ->
213/// graphics -> graphics` (vminst.ml:2432) — `graphicD.ml`'s
214/// `make_linear_trans`, applied eagerly.
215pub fn linear_transform_graphics(mat: (f64, f64, f64, f64), elem: &GraphicsElem) -> GraphicsElem {
216    match elem {
217        GraphicsElem::Fill(c, p) => GraphicsElem::Fill(*c, linear_transform_path(mat, p)),
218        GraphicsElem::Stroke(w, c, p) => GraphicsElem::Stroke(*w, *c, linear_transform_path(mat, p)),
219        GraphicsElem::DashedStroke(w, d, c, p) => {
220            GraphicsElem::DashedStroke(*w, *d, *c, linear_transform_path(mat, p))
221        }
222        // A `draw-text` run carries the composed 2×2 matrix so the writer can
223        // rotate/scale the glyphs/image at render time (upstream's lazy
224        // `LinearTrans` `cm`). The affine is `transform·l + pt`; pre-composing
225        // `mat` gives `mat·(transform·l + pt) = (mat·transform)·l + mat·pt`, so
226        // `transform ↦ mat·transform` and `pt ↦ mat·pt`. Matrices are row-major
227        // `(a, b, c, d)` = `[[a, b], [c, d]]` (the `linear_transform_point`
228        // convention), so the product below is the standard 2×2 multiply.
229        GraphicsElem::Text { pt, contents, width, height, depth, transform } => {
230            let (ma, mb, mc, md) = mat;
231            let (ta, tb, tc, td) = transform.unwrap_or((1.0, 0.0, 0.0, 1.0));
232            let composed = (
233                ma * ta + mb * tc,
234                ma * tb + mb * td,
235                mc * ta + md * tc,
236                mc * tb + md * td,
237            );
238            GraphicsElem::Text {
239                pt: linear_transform_point(mat, *pt),
240                contents: contents.clone(),
241                width: *width,
242                height: *height,
243                depth: *depth,
244                transform: Some(composed),
245            }
246        }
247        GraphicsElem::Group(gs) => GraphicsElem::Group(
248            gs.iter().map(|g| linear_transform_graphics(mat, g)).collect(),
249        ),
250        GraphicsElem::Clip(path, gs) => GraphicsElem::Clip(
251            linear_transform_path(mat, path),
252            gs.iter().map(|g| linear_transform_graphics(mat, g)).collect(),
253        ),
254    }
255}
256
257/// One axis (x or y) of a cubic Bézier's EXACT extrema (`graphicBase.ml:88`
258/// `bezier_bbox`'s per-axis `aux`): for the cubic from `r0` (current point)
259/// through controls `r1`, `r2` to `r3`, the derivative's roots give the
260/// interior extrema; candidates are `{r0, r3, B(t+), B(t-)}` with `t` clamped
261/// to `[0, 1]` (`bezier_point`'s convention: `t < 0` snaps to `r0`, `t > 1`
262/// snaps to `r3`). Returns `(min, max)` over that candidate set.
263fn bezier_axis_extent(r0: f64, r1: f64, r2: f64, r3: f64) -> (f64, f64) {
264    // B(t) = (1-t)^3 r0 + 3(1-t)^2 t r1 + 3(1-t) t^2 r2 + t^3 r3
265    // B'(t)/3 = a t^2 + b t + c, with:
266    let a = -r0 + 3.0 * (r1 - r2) + r3;
267    let b = 2.0 * (r0 - 2.0 * r1 + r2);
268    let c = r1 - r0;
269    let bezier_point = |t: f64| -> f64 {
270        if t < 0.0 {
271            r0
272        } else if t > 1.0 {
273            r3
274        } else {
275            let u = 1.0 - t;
276            u * u * u * r0 + 3.0 * u * u * t * r1 + 3.0 * u * t * t * r2 + t * t * t * r3
277        }
278    };
279    let mut candidates = vec![r0, r3];
280    if a.abs() < 1e-12 {
281        // Linear derivative (or degenerate): at most one root, `-c/b`.
282        if b.abs() > 1e-12 {
283            candidates.push(bezier_point(-c / b));
284        }
285    } else {
286        let disc = b * b - 4.0 * a * c;
287        if disc >= 0.0 {
288            let sq = disc.sqrt();
289            candidates.push(bezier_point((-b + sq) / (2.0 * a)));
290            candidates.push(bezier_point((-b - sq) / (2.0 * a)));
291        }
292    }
293    let min = candidates.iter().cloned().fold(f64::INFINITY, f64::min);
294    let max = candidates.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
295    (min, max)
296}
297
298/// `get_path_bbox`/`bezier_bbox` (`graphicBase.ml:88-127,148-171`) — the
299/// EXACT bounding box of `path`: walks each subpath tracking the current
300/// point (`start`; each `Line` contributes its endpoint; each
301/// `Bezier(c1,c2,p)` contributes the cubic extrema of `(cur, c1, c2, p)`; a
302/// `Closing::Bezier(c1,c2)` contributes the extrema of `(cur, c1, c2,
303/// start)`), taking each axis's true curve extent via
304/// `bezier_axis_extent` rather than the (looser) control-point hull.
305pub fn path_bbox(path: &Path) -> (Point, Point) {
306    fn include(bounds: &mut (f64, f64, f64, f64), p: Point) {
307        bounds.0 = bounds.0.min(p.0 .0);
308        bounds.1 = bounds.1.max(p.0 .0);
309        bounds.2 = bounds.2.min(p.1 .0);
310        bounds.3 = bounds.3.max(p.1 .0);
311    }
312    fn include_axis_extents(bounds: &mut (f64, f64, f64, f64), ex: (f64, f64), ey: (f64, f64)) {
313        bounds.0 = bounds.0.min(ex.0);
314        bounds.1 = bounds.1.max(ex.1);
315        bounds.2 = bounds.2.min(ey.0);
316        bounds.3 = bounds.3.max(ey.1);
317    }
318    // (min_x, max_x, min_y, max_y).
319    let mut bounds = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY);
320    for sub in &path.subpaths {
321        include(&mut bounds, sub.start);
322        let mut cur = sub.start;
323        for seg in &sub.segs {
324            match *seg {
325                PathSeg::Line(p) => {
326                    include(&mut bounds, p);
327                    cur = p;
328                }
329                PathSeg::Bezier(c1, c2, p) => {
330                    let ex = bezier_axis_extent(cur.0 .0, c1.0 .0, c2.0 .0, p.0 .0);
331                    let ey = bezier_axis_extent(cur.1 .0, c1.1 .0, c2.1 .0, p.1 .0);
332                    include_axis_extents(&mut bounds, ex, ey);
333                    cur = p;
334                }
335            }
336        }
337        if let Closing::Bezier(c1, c2) = sub.closing {
338            let ex = bezier_axis_extent(cur.0 .0, c1.0 .0, c2.0 .0, sub.start.0 .0);
339            let ey = bezier_axis_extent(cur.1 .0, c1.1 .0, c2.1 .0, sub.start.1 .0);
340            include_axis_extents(&mut bounds, ex, ey);
341        }
342    }
343    let (min_x, max_x, min_y, max_y) = bounds;
344    if min_x.is_infinite() {
345        return ((Length::ZERO, Length::ZERO), (Length::ZERO, Length::ZERO));
346    }
347    (
348        (Length(min_x), Length(min_y)),
349        (Length(max_x), Length(max_y)),
350    )
351}
352
353fn union_bbox((amin, amax): (Point, Point), (bmin, bmax): (Point, Point)) -> (Point, Point) {
354    (
355        (
356            Length(amin.0 .0.min(bmin.0 .0)),
357            Length(amin.1 .0.min(bmin.1 .0)),
358        ),
359        (
360            Length(amax.0 .0.max(bmax.0 .0)),
361            Length(amax.1 .0.max(bmax.1 .0)),
362        ),
363    )
364}
365
366/// `get-graphics-bbox : graphics -> point * point` (v0.0.6 vminst.ml:2466) /
367/// `graphics -> option (point * point)` (dev-0-1-0 vminst.ml:2301, the
368/// "version-blind fix") — `graphicD.ml`'s `get_bbox`/`get_element_bbox`,
369/// ignoring stroke thickness (upstream's own documented simplification).
370/// `Clip(paths, _)` returns the CLIP PATHS' own bbox, ignoring `contents`
371/// (upstream `graphicD.ml:50-52` — deliberate: the clip boundary, not what is
372/// inside it, bounds the visible ink). `Group` union-folds its children
373/// (`graphicD.ml:61-74`); `None` for an empty `Group` or an empty top-level
374/// list, which v0.0.6 could never produce.
375pub fn graphics_bbox(elem: &GraphicsElem) -> Option<(Point, Point)> {
376    match elem {
377        GraphicsElem::Fill(_, p)
378        | GraphicsElem::Stroke(_, _, p)
379        | GraphicsElem::DashedStroke(_, _, _, p) => Some(path_bbox(p)),
380        GraphicsElem::Text { pt, width, height, depth, transform, .. } => {
381            match transform {
382                // Upright run: the axis-aligned `[0,width]×[-depth, height]`
383                // extent translated to `pt`.
384                None => Some(((pt.0, pt.1 - *depth), (pt.0 + *width, pt.1 + *height))),
385                // Rotated/scaled run: transform the four local corners, translate
386                // by `pt`, take the axis-aligned hull — so a `rotate`d figbox
387                // reserves the correct (rotated) inline size.
388                Some(mat) => {
389                    let corners = [
390                        (Length::ZERO, -*depth),
391                        (*width, -*depth),
392                        (*width, *height),
393                        (Length::ZERO, *height),
394                    ];
395                    let mut min = (f64::INFINITY, f64::INFINITY);
396                    let mut max = (f64::NEG_INFINITY, f64::NEG_INFINITY);
397                    for c in corners {
398                        let t = linear_transform_point(*mat, c);
399                        let (x, y) = (t.0 .0 + pt.0 .0, t.1 .0 + pt.1 .0);
400                        min = (min.0.min(x), min.1.min(y));
401                        max = (max.0.max(x), max.1.max(y));
402                    }
403                    Some((
404                        (Length(min.0), Length(min.1)),
405                        (Length(max.0), Length(max.1)),
406                    ))
407                }
408            }
409        }
410        GraphicsElem::Clip(path, _) => Some(path_bbox(path)),
411        GraphicsElem::Group(gs) => gs
412            .iter()
413            .filter_map(graphics_bbox)
414            .reduce(union_bbox),
415    }
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421
422    fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> Path {
423        Path {
424            subpaths: vec![Subpath {
425                start: (Length(x0), Length(y0)),
426                segs: vec![
427                    PathSeg::Line((Length(x1), Length(y0))),
428                    PathSeg::Line((Length(x1), Length(y1))),
429                    PathSeg::Line((Length(x0), Length(y1))),
430                ],
431                closing: Closing::Line,
432            }],
433        }
434    }
435
436    /// Over a `Clip`/`Group` both move the clip path AND the contents
437    /// (the `graphicD.ml:38` recursing-arm contract).
438    #[test]
439    fn shift_and_transform_recurse_into_clip_and_group() {
440        let fill = GraphicsElem::Fill(Color::Gray(0.0), rect(0.0, 0.0, 1.0, 1.0));
441        let group = GraphicsElem::Group(vec![fill.clone(), fill.clone()]);
442        let shifted_group = shift_graphics((Length(2.0), Length(3.0)), &group);
443        match &shifted_group {
444            GraphicsElem::Group(gs) => {
445                assert_eq!(gs.len(), 2);
446                for g in gs {
447                    assert_eq!(
448                        graphics_bbox(g),
449                        Some(((Length(2.0), Length(3.0)), (Length(3.0), Length(4.0))))
450                    );
451                }
452            }
453            other => panic!("expected Group, got {other:?}"),
454        }
455
456        let clip = GraphicsElem::Clip(rect(0.0, 0.0, 5.0, 5.0), vec![fill.clone()]);
457        let shifted_clip = shift_graphics((Length(1.0), Length(1.0)), &clip);
458        match &shifted_clip {
459            GraphicsElem::Clip(path, inner) => {
460                assert_eq!(
461                    path_bbox(path),
462                    ((Length(1.0), Length(1.0)), (Length(6.0), Length(6.0)))
463                );
464                assert_eq!(
465                    graphics_bbox(&inner[0]),
466                    Some(((Length(1.0), Length(1.0)), (Length(2.0), Length(2.0))))
467                );
468            }
469            other => panic!("expected Clip, got {other:?}"),
470        }
471
472        // `linear-transform-graphics` (scale by 2 on both axes) also
473        // recurses into both the clip path AND the contents.
474        let scaled_clip = linear_transform_graphics((2.0, 0.0, 0.0, 2.0), &clip);
475        match &scaled_clip {
476            GraphicsElem::Clip(path, inner) => {
477                assert_eq!(
478                    path_bbox(path),
479                    ((Length(0.0), Length(0.0)), (Length(10.0), Length(10.0)))
480                );
481                assert_eq!(
482                    graphics_bbox(&inner[0]),
483                    Some(((Length(0.0), Length(0.0)), (Length(2.0), Length(2.0))))
484                );
485            }
486            other => panic!("expected Clip, got {other:?}"),
487        }
488    }
489
490    /// `get-graphics-bbox` `Option` semantics: an empty `Group` has no
491    /// ink and returns `None`; a `Group` of two fills union-folds; a `Clip`
492    /// returns the CLIP PATH's own bbox, ignoring `contents`.
493    #[test]
494    fn bbox_option_semantics() {
495        assert_eq!(graphics_bbox(&GraphicsElem::Group(vec![])), None);
496
497        let a = GraphicsElem::Fill(Color::Gray(0.0), rect(0.0, 0.0, 1.0, 1.0));
498        let b = GraphicsElem::Fill(Color::Gray(0.0), rect(2.0, 2.0, 3.0, 3.0));
499        let group = GraphicsElem::Group(vec![a.clone(), b.clone()]);
500        assert_eq!(
501            graphics_bbox(&group),
502            Some(((Length(0.0), Length(0.0)), (Length(3.0), Length(3.0))))
503        );
504
505        let clip = GraphicsElem::Clip(rect(10.0, 10.0, 20.0, 20.0), vec![a]);
506        assert_eq!(
507            graphics_bbox(&clip),
508            Some(((Length(10.0), Length(10.0)), (Length(20.0), Length(20.0))))
509        );
510    }
511}