Skip to main content

laminapdf_model/
graphics.rs

1//! The graphics values that building and reading share: [`Matrix`] (ISO 32000-2 §8.3.3),
2//! [`FillRule`] (§8.5.3.3), [`Dash`] (§8.4.3.6) and [`BlendMode`] (§11.3.5). They hold numbers in whatever space they
3//! are used in: page space when building, user space when reading content.
4
5/// An affine transformation `[a b c d e f]` (§8.3.3): a point `(x, y)` maps to
6/// `(a·x + c·y + e, b·x + d·y + f)`.
7///
8/// Composition has two names, one per order: `p.then(&q)` applies `p` first, `q.after(&p)`
9/// is the same matrix. `cm` sets `CTM′ = M × CTM` (§8.4.4), which is `m.then(&ctm)`.
10///
11/// ```
12/// use laminapdf_model::Matrix;
13///
14/// let scale = Matrix::scale(2.0, 2.0);
15/// let shift = Matrix::translate(10.0, 0.0);
16/// assert_eq!(scale.then(&shift).apply(1.0, 1.0), (12.0, 2.0));
17/// assert_eq!(shift.after(&scale), scale.then(&shift));
18/// ```
19///
20/// Added in 0.2.0.
21#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct Matrix {
23    /// `a`.
24    pub a: f64,
25    /// `b`.
26    pub b: f64,
27    /// `c`.
28    pub c: f64,
29    /// `d`.
30    pub d: f64,
31    /// `e`, the x translation.
32    pub e: f64,
33    /// `f`, the y translation.
34    pub f: f64,
35}
36
37impl Default for Matrix {
38    fn default() -> Self {
39        Self::IDENTITY
40    }
41}
42
43impl Matrix {
44    /// The identity.
45    ///
46    /// Added in 0.2.0.
47    pub const IDENTITY: Self = Self::new([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
48
49    /// The matrix `[a b c d e f]`.
50    ///
51    /// Added in 0.2.0.
52    #[must_use]
53    #[expect(clippy::many_single_char_names, reason = "a–f are the matrix entries of §8.3.3")]
54    pub const fn new([a, b, c, d, e, f]: [f64; 6]) -> Self {
55        Self { a, b, c, d, e, f }
56    }
57
58    /// `[a b c d e f]`.
59    ///
60    /// Added in 0.2.0.
61    #[must_use]
62    pub const fn to_array(self) -> [f64; 6] {
63        [self.a, self.b, self.c, self.d, self.e, self.f]
64    }
65
66    /// A translation by `(x, y)`.
67    ///
68    /// Added in 0.2.0.
69    #[must_use]
70    pub const fn translate(x: f64, y: f64) -> Self {
71        Self::new([1.0, 0.0, 0.0, 1.0, x, y])
72    }
73
74    /// A scaling by `sx` horizontally and `sy` vertically.
75    ///
76    /// Added in 0.2.0.
77    #[must_use]
78    pub const fn scale(sx: f64, sy: f64) -> Self {
79        Self::new([sx, 0.0, 0.0, sy, 0.0, 0.0])
80    }
81
82    /// A rotation by `degrees` about the origin, from the x axis towards the y axis: clockwise
83    /// as displayed in page space (y down), counter-clockwise in user space (y up).
84    ///
85    /// Added in 0.2.0.
86    #[must_use]
87    pub fn rotate(degrees: f64) -> Self {
88        let (s, c) = degrees.to_radians().sin_cos();
89        Self::new([c, s, -s, c, 0.0, 0.0])
90    }
91
92    /// `self` first, then `next`: the matrix that maps `p` to `next(self(p))`, the product
93    /// `self × next` of §8.3.4.
94    ///
95    /// Added in 0.2.0.
96    #[must_use]
97    pub fn then(&self, next: &Self) -> Self {
98        Self::new([
99            self.a * next.a + self.b * next.c,
100            self.a * next.b + self.b * next.d,
101            self.c * next.a + self.d * next.c,
102            self.c * next.b + self.d * next.d,
103            self.e * next.a + self.f * next.c + next.e,
104            self.e * next.b + self.f * next.d + next.f,
105        ])
106    }
107
108    /// `self` after `first`: the matrix that maps `p` to `self(first(p))`, the same as
109    /// `first.then(self)`.
110    ///
111    /// Added in 0.2.0.
112    #[must_use]
113    pub fn after(&self, first: &Self) -> Self {
114        first.then(self)
115    }
116
117    /// The inverse, `None` for a singular matrix.
118    ///
119    /// Added in 0.2.0.
120    #[must_use]
121    pub fn invert(&self) -> Option<Self> {
122        let det = self.a * self.d - self.b * self.c;
123        if det == 0.0 || !det.is_finite() {
124            return None;
125        }
126        let (a, b, c, d) = (self.d / det, -self.b / det, -self.c / det, self.a / det);
127        Some(Self::new([
128            a,
129            b,
130            c,
131            d,
132            -(a * self.e + c * self.f),
133            -(b * self.e + d * self.f),
134        ]))
135    }
136
137    /// The image of the point `(x, y)`.
138    ///
139    /// Added in 0.2.0.
140    #[must_use]
141    pub fn apply(&self, x: f64, y: f64) -> (f64, f64) {
142        (self.a * x + self.c * y + self.e, self.b * x + self.d * y + self.f)
143    }
144
145    /// The matrix from six numbers (`None` unless there are exactly six).
146    ///
147    /// Added in 0.2.0.
148    #[must_use]
149    pub fn from_slice(values: &[f64]) -> Option<Self> {
150        <[f64; 6]>::try_from(values).ok().map(Self::new)
151    }
152}
153
154/// How a fill or clip decides what is inside a path (§8.5.3.3).
155///
156/// Added in 0.2.0.
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
158pub enum FillRule {
159    /// Non-zero winding number (`f`, `W`).
160    #[default]
161    NonZero,
162    /// Even-odd (`f*`, `W*`).
163    EvenOdd,
164}
165
166impl FillRule {
167    /// Every fill rule, in declaration order.
168    ///
169    /// Added in 0.2.0.
170    pub const ALL: [Self; 2] = [Self::NonZero, Self::EvenOdd];
171}
172
173/// A line dash pattern (§8.4.3.6): alternating dash and gap lengths, and how far into the
174/// pattern the line starts. Lengths are in the space the line is drawn in: points when
175/// building (page space), user-space units when reading content.
176///
177/// Added in 0.2.0.
178#[derive(Debug, Clone, PartialEq, Default)]
179#[non_exhaustive]
180pub struct Dash {
181    /// Dash and gap lengths; an empty list draws a solid line.
182    pub array: Vec<f64>,
183    /// Where in the pattern the line starts.
184    pub phase: f64,
185}
186
187impl Dash {
188    /// A pattern of `array` lengths starting `phase` into it.
189    ///
190    /// Added in 0.2.0.
191    #[must_use]
192    pub const fn new(array: Vec<f64>, phase: f64) -> Self {
193        Self { array, phase }
194    }
195}
196
197/// A blend mode (§11.3.5, Tables 134 and 135).
198///
199/// Added in 0.2.0.
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
201#[non_exhaustive]
202pub enum BlendMode {
203    /// `Normal`.
204    #[default]
205    Normal,
206    /// `Multiply`.
207    Multiply,
208    /// `Screen`.
209    Screen,
210    /// `Overlay`.
211    Overlay,
212    /// `Darken`.
213    Darken,
214    /// `Lighten`.
215    Lighten,
216    /// `ColorDodge`.
217    ColorDodge,
218    /// `ColorBurn`.
219    ColorBurn,
220    /// `HardLight`.
221    HardLight,
222    /// `SoftLight`.
223    SoftLight,
224    /// `Difference`.
225    Difference,
226    /// `Exclusion`.
227    Exclusion,
228    /// `Hue`.
229    Hue,
230    /// `Saturation`.
231    Saturation,
232    /// `Color`.
233    Color,
234    /// `Luminosity`.
235    Luminosity,
236}
237
238impl BlendMode {
239    /// Every blend mode, in declaration order.
240    ///
241    /// Added in 0.2.0.
242    pub const ALL: [Self; 16] = [
243        Self::Normal,
244        Self::Multiply,
245        Self::Screen,
246        Self::Overlay,
247        Self::Darken,
248        Self::Lighten,
249        Self::ColorDodge,
250        Self::ColorBurn,
251        Self::HardLight,
252        Self::SoftLight,
253        Self::Difference,
254        Self::Exclusion,
255        Self::Hue,
256        Self::Saturation,
257        Self::Color,
258        Self::Luminosity,
259    ];
260
261    /// The PDF name (`/BM`).
262    ///
263    /// Added in 0.2.0.
264    #[must_use]
265    pub const fn pdf_name(self) -> &'static str {
266        match self {
267            Self::Normal => "Normal",
268            Self::Multiply => "Multiply",
269            Self::Screen => "Screen",
270            Self::Overlay => "Overlay",
271            Self::Darken => "Darken",
272            Self::Lighten => "Lighten",
273            Self::ColorDodge => "ColorDodge",
274            Self::ColorBurn => "ColorBurn",
275            Self::HardLight => "HardLight",
276            Self::SoftLight => "SoftLight",
277            Self::Difference => "Difference",
278            Self::Exclusion => "Exclusion",
279            Self::Hue => "Hue",
280            Self::Saturation => "Saturation",
281            Self::Color => "Color",
282            Self::Luminosity => "Luminosity",
283        }
284    }
285    /// The mode a `/BM` name names, `Compatible` read as `Normal` (§11.3.5), or `None` for a
286    /// name §11.3.5 doesn't define.
287    ///
288    /// Added in 0.2.0.
289    #[must_use]
290    pub fn from_pdf_name(name: &[u8]) -> Option<Self> {
291        if name == b"Compatible" {
292            return Some(Self::Normal);
293        }
294        Self::ALL.into_iter().find(|mode| mode.pdf_name().as_bytes() == name)
295    }
296}
297
298#[cfg(test)]
299mod tests {
300    use super::{BlendMode, FillRule, Matrix};
301
302    const SCALE: Matrix = Matrix::scale(2.0, 3.0);
303    const SHIFT: Matrix = Matrix::translate(10.0, 20.0);
304
305    #[test]
306    fn then_should_apply_the_receiver_first() {
307        // Scale (1, 1) to (2, 3), then shift it to (12, 23).
308        assert_eq!(SCALE.then(&SHIFT).apply(1.0, 1.0), (12.0, 23.0));
309        // Shift (1, 1) to (11, 21), then scale it to (22, 63).
310        assert_eq!(SHIFT.then(&SCALE).apply(1.0, 1.0), (22.0, 63.0));
311    }
312
313    #[test]
314    fn after_should_apply_its_argument_first() {
315        assert_eq!(SHIFT.after(&SCALE).apply(1.0, 1.0), (12.0, 23.0));
316        assert_eq!(SHIFT.after(&SCALE), SCALE.then(&SHIFT));
317    }
318
319    #[test]
320    fn then_should_be_the_spec_product_cm_uses() {
321        // §8.4.4: `cm` sets CTM′ = M × CTM; with CTM a translation, M's scale applies first.
322        let m = Matrix::new([2.0, 0.0, 0.0, 2.0, 0.0, 0.0]);
323        let ctm = Matrix::new([1.0, 0.0, 0.0, 1.0, 5.0, 7.0]);
324        assert_eq!(m.then(&ctm).to_array(), [2.0, 0.0, 0.0, 2.0, 5.0, 7.0]);
325    }
326
327    #[test]
328    fn invert_should_undo_the_matrix_and_refuse_a_singular_one() {
329        let m = Matrix::rotate(30.0).then(&SCALE).then(&SHIFT);
330        let back = m.invert().map(|i| {
331            let (x, y) = m.apply(4.0, -2.0);
332            i.apply(x, y)
333        });
334        let Some((x, y)) = back else {
335            panic!("a rotation, scale and shift is invertible");
336        };
337        assert!((x - 4.0).abs() < 1e-9 && (y + 2.0).abs() < 1e-9);
338        assert_eq!(Matrix::scale(0.0, 1.0).invert(), None);
339    }
340
341    #[test]
342    fn rotate_should_turn_the_x_axis_towards_the_y_axis() {
343        let (x, y) = Matrix::rotate(90.0).apply(1.0, 0.0);
344        assert!(x.abs() < 1e-12 && (y - 1.0).abs() < 1e-12);
345    }
346
347    #[test]
348    fn from_slice_should_take_exactly_six_numbers() {
349        assert_eq!(
350            Matrix::from_slice(&[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]),
351            Some(Matrix::IDENTITY)
352        );
353        assert_eq!(Matrix::from_slice(&[1.0; 5]), None);
354        assert_eq!(Matrix::from_slice(&[1.0; 7]), None);
355    }
356
357    /// The match is exhaustive, so a new variant fails to build here first: give it the next
358    /// index and add it to `ALL` there, which this test then checks.
359    #[test]
360    fn all_should_list_every_fill_rule_once_in_declaration_order() {
361        let index = |v: FillRule| match v {
362            FillRule::NonZero => 0,
363            FillRule::EvenOdd => 1,
364        };
365        assert!(FillRule::ALL.iter().enumerate().all(|(i, v)| index(*v) == i));
366    }
367
368    /// The match is exhaustive, so a new variant fails to build here first: give it the next
369    /// index and add it to `ALL` there, which this test then checks.
370    #[test]
371    fn all_should_list_every_blend_mode_once_in_declaration_order() {
372        let index = |v: BlendMode| match v {
373            BlendMode::Normal => 0,
374            BlendMode::Multiply => 1,
375            BlendMode::Screen => 2,
376            BlendMode::Overlay => 3,
377            BlendMode::Darken => 4,
378            BlendMode::Lighten => 5,
379            BlendMode::ColorDodge => 6,
380            BlendMode::ColorBurn => 7,
381            BlendMode::HardLight => 8,
382            BlendMode::SoftLight => 9,
383            BlendMode::Difference => 10,
384            BlendMode::Exclusion => 11,
385            BlendMode::Hue => 12,
386            BlendMode::Saturation => 13,
387            BlendMode::Color => 14,
388            BlendMode::Luminosity => 15,
389        };
390        assert_eq!(
391            BlendMode::ALL.map(index),
392            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
393        );
394    }
395
396    #[test]
397    fn from_pdf_name_should_read_every_mode_and_compatible_as_normal() {
398        let read = BlendMode::ALL.map(|m| BlendMode::from_pdf_name(m.pdf_name().as_bytes()));
399        assert_eq!(read, BlendMode::ALL.map(Some));
400        assert_eq!(BlendMode::from_pdf_name(b"Compatible"), Some(BlendMode::Normal));
401        assert_eq!(BlendMode::from_pdf_name(b"Sparkle"), None);
402    }
403}