Skip to main content

day_geometry/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-geometry: plain `Copy` value types shared by layout, canvas, and the toolkit spec.
5//! Everything is in points (density-independent); backends convert to device pixels (§7.9).
6
7#[derive(Clone, Copy, Debug, Default, PartialEq)]
8pub struct Point {
9    pub x: f64,
10    pub y: f64,
11}
12
13impl Point {
14    pub const ZERO: Point = Point { x: 0.0, y: 0.0 };
15    #[inline]
16    pub const fn new(x: f64, y: f64) -> Self {
17        Point { x, y }
18    }
19    #[inline]
20    #[must_use]
21    pub fn offset(self, dx: f64, dy: f64) -> Self {
22        Point::new(self.x + dx, self.y + dy)
23    }
24}
25
26#[derive(Clone, Copy, Debug, Default, PartialEq)]
27pub struct Size {
28    pub width: f64,
29    pub height: f64,
30}
31
32impl Size {
33    pub const ZERO: Size = Size {
34        width: 0.0,
35        height: 0.0,
36    };
37    #[inline]
38    pub const fn new(width: f64, height: f64) -> Self {
39        Size { width, height }
40    }
41    #[inline]
42    #[must_use]
43    pub fn max(self, other: Size) -> Size {
44        Size::new(self.width.max(other.width), self.height.max(other.height))
45    }
46    /// Approximate equality on the half-pixel epsilon used by frame diffing (§7.9).
47    #[inline]
48    #[must_use]
49    pub fn approx_eq(self, other: Size, eps: f64) -> bool {
50        (self.width - other.width).abs() <= eps && (self.height - other.height).abs() <= eps
51    }
52}
53
54#[derive(Clone, Copy, Debug, Default, PartialEq)]
55pub struct Rect {
56    pub origin: Point,
57    pub size: Size,
58}
59
60impl Rect {
61    pub const ZERO: Rect = Rect {
62        origin: Point::ZERO,
63        size: Size::ZERO,
64    };
65    #[inline]
66    pub const fn new(x: f64, y: f64, width: f64, height: f64) -> Self {
67        Rect {
68            origin: Point::new(x, y),
69            size: Size::new(width, height),
70        }
71    }
72    #[inline]
73    pub fn from_size(size: Size) -> Self {
74        Rect {
75            origin: Point::ZERO,
76            size,
77        }
78    }
79    #[inline]
80    #[must_use]
81    pub fn min_x(&self) -> f64 {
82        self.origin.x
83    }
84    #[inline]
85    #[must_use]
86    pub fn min_y(&self) -> f64 {
87        self.origin.y
88    }
89    #[inline]
90    #[must_use]
91    pub fn max_x(&self) -> f64 {
92        self.origin.x + self.size.width
93    }
94    #[inline]
95    #[must_use]
96    pub fn max_y(&self) -> f64 {
97        self.origin.y + self.size.height
98    }
99    #[inline]
100    pub fn center(&self) -> Point {
101        Point::new(
102            self.origin.x + self.size.width / 2.0,
103            self.origin.y + self.size.height / 2.0,
104        )
105    }
106    #[inline]
107    #[must_use]
108    pub fn inset(&self, d: f64) -> Rect {
109        self.inset_by(Insets::all(d))
110    }
111    #[must_use]
112    pub fn inset_by(&self, i: Insets) -> Rect {
113        Rect::new(
114            self.origin.x + i.leading,
115            self.origin.y + i.top,
116            (self.size.width - i.leading - i.trailing).max(0.0),
117            (self.size.height - i.top - i.bottom).max(0.0),
118        )
119    }
120    #[must_use]
121    pub fn intersects(&self, other: &Rect) -> bool {
122        self.min_x() < other.max_x()
123            && other.min_x() < self.max_x()
124            && self.min_y() < other.max_y()
125            && other.min_y() < self.max_y()
126    }
127    /// Approximate equality on the half-pixel epsilon used by frame diffing (§7.9).
128    #[must_use]
129    pub fn approx_eq(&self, other: &Rect, eps: f64) -> bool {
130        (self.origin.x - other.origin.x).abs() <= eps
131            && (self.origin.y - other.origin.y).abs() <= eps
132            && self.size.approx_eq(other.size, eps)
133    }
134}
135
136/// A 2-D affine transform (CoreGraphics row-vector convention): a point `p` maps to
137/// `(a·p.x + c·p.y + tx, b·p.x + d·p.y + ty)`. Used by canvas transform ops for shape
138/// rotate/scale/offset; every native 2-D context concatenates it onto its CTM identically.
139#[derive(Clone, Copy, Debug, PartialEq)]
140pub struct Affine {
141    pub a: f64,
142    pub b: f64,
143    pub c: f64,
144    pub d: f64,
145    pub tx: f64,
146    pub ty: f64,
147}
148
149impl Affine {
150    pub const IDENTITY: Affine = Affine {
151        a: 1.0,
152        b: 0.0,
153        c: 0.0,
154        d: 1.0,
155        tx: 0.0,
156        ty: 0.0,
157    };
158
159    #[inline]
160    pub const fn translate(x: f64, y: f64) -> Affine {
161        Affine {
162            a: 1.0,
163            b: 0.0,
164            c: 0.0,
165            d: 1.0,
166            tx: x,
167            ty: y,
168        }
169    }
170    #[inline]
171    pub const fn scale(sx: f64, sy: f64) -> Affine {
172        Affine {
173            a: sx,
174            b: 0.0,
175            c: 0.0,
176            d: sy,
177            tx: 0.0,
178            ty: 0.0,
179        }
180    }
181    /// Rotation by `radians` (counter-clockwise in a y-up space; clockwise on y-down screens).
182    #[inline]
183    pub fn rotate(radians: f64) -> Affine {
184        let (s, cos) = radians.sin_cos();
185        Affine {
186            a: cos,
187            b: s,
188            c: -s,
189            d: cos,
190            tx: 0.0,
191            ty: 0.0,
192        }
193    }
194    /// `self` applied first, then `other` (row-vector product `self · other`).
195    #[inline]
196    #[must_use]
197    pub fn then(self, o: Affine) -> Affine {
198        Affine {
199            a: self.a * o.a + self.b * o.c,
200            b: self.a * o.b + self.b * o.d,
201            c: self.c * o.a + self.d * o.c,
202            d: self.c * o.b + self.d * o.d,
203            tx: self.tx * o.a + self.ty * o.c + o.tx,
204            ty: self.tx * o.b + self.ty * o.d + o.ty,
205        }
206    }
207    #[inline]
208    pub fn apply(&self, p: Point) -> Point {
209        Point::new(
210            self.a * p.x + self.c * p.y + self.tx,
211            self.b * p.x + self.d * p.y + self.ty,
212        )
213    }
214    /// Map a point back through the inverse (for hit-testing a transformed shape). None if singular.
215    #[must_use]
216    pub fn invert_apply(&self, p: Point) -> Option<Point> {
217        let det = self.a * self.d - self.b * self.c;
218        if det.abs() < 1e-12 {
219            return None;
220        }
221        let inv = 1.0 / det;
222        let x = p.x - self.tx;
223        let y = p.y - self.ty;
224        Some(Point::new(
225            (x * self.d - y * self.c) * inv,
226            (y * self.a - x * self.b) * inv,
227        ))
228    }
229    #[inline]
230    #[must_use]
231    pub fn is_identity(&self) -> bool {
232        *self == Affine::IDENTITY
233    }
234    #[inline]
235    #[must_use]
236    pub fn as_array(&self) -> [f64; 6] {
237        [self.a, self.b, self.c, self.d, self.tx, self.ty]
238    }
239    #[inline]
240    pub fn from_array(m: [f64; 6]) -> Affine {
241        Affine {
242            a: m[0],
243            b: m[1],
244            c: m[2],
245            d: m[3],
246            tx: m[4],
247            ty: m[5],
248        }
249    }
250}
251
252/// Logical insets: `leading`/`trailing` resolve against the layout direction at place time (§7.8).
253#[derive(Clone, Copy, Debug, Default, PartialEq)]
254pub struct Insets {
255    pub top: f64,
256    pub leading: f64,
257    pub bottom: f64,
258    pub trailing: f64,
259}
260
261impl Insets {
262    pub const ZERO: Insets = Insets {
263        top: 0.0,
264        leading: 0.0,
265        bottom: 0.0,
266        trailing: 0.0,
267    };
268    /// Four explicit edges, in the order they are named.
269    #[inline]
270    #[must_use]
271    pub const fn new(top: f64, leading: f64, bottom: f64, trailing: f64) -> Self {
272        Insets {
273            top,
274            leading,
275            bottom,
276            trailing,
277        }
278    }
279    #[inline]
280    #[must_use]
281    pub const fn all(d: f64) -> Self {
282        Insets {
283            top: d,
284            leading: d,
285            bottom: d,
286            trailing: d,
287        }
288    }
289    #[inline]
290    #[must_use]
291    pub const fn symmetric(horizontal: f64, vertical: f64) -> Self {
292        Insets {
293            top: vertical,
294            leading: horizontal,
295            bottom: vertical,
296            trailing: horizontal,
297        }
298    }
299    /// `d` on the leading and trailing edges, nothing above or below.
300    #[inline]
301    #[must_use]
302    pub const fn horizontal(d: f64) -> Self {
303        Insets::symmetric(d, 0.0)
304    }
305    /// `d` above and below, nothing on the sides.
306    #[inline]
307    #[must_use]
308    pub const fn vertical(d: f64) -> Self {
309        Insets::symmetric(0.0, d)
310    }
311    /// `d` above, nothing elsewhere.
312    #[inline]
313    #[must_use]
314    pub const fn top(d: f64) -> Self {
315        Insets {
316            top: d,
317            ..Insets::ZERO
318        }
319    }
320    /// `d` below, nothing elsewhere.
321    #[inline]
322    #[must_use]
323    pub const fn bottom(d: f64) -> Self {
324        Insets {
325            bottom: d,
326            ..Insets::ZERO
327        }
328    }
329    /// `d` on the leading edge, nothing elsewhere.
330    #[inline]
331    #[must_use]
332    pub const fn leading(d: f64) -> Self {
333        Insets {
334            leading: d,
335            ..Insets::ZERO
336        }
337    }
338    /// `d` on the trailing edge, nothing elsewhere.
339    #[inline]
340    #[must_use]
341    pub const fn trailing(d: f64) -> Self {
342        Insets {
343            trailing: d,
344            ..Insets::ZERO
345        }
346    }
347    /// The width the insets take: leading plus trailing.
348    #[inline]
349    #[must_use]
350    pub fn horizontal_total(&self) -> f64 {
351        self.leading + self.trailing
352    }
353    /// The height the insets take: top plus bottom.
354    #[inline]
355    #[must_use]
356    pub fn vertical_total(&self) -> f64 {
357        self.top + self.bottom
358    }
359}
360
361/// sRGB color, 0.0–1.0 components. Semantic theme tokens (§6.3) resolve to these in the backend.
362#[derive(Clone, Copy, Debug, PartialEq)]
363pub struct Color {
364    pub r: f64,
365    pub g: f64,
366    pub b: f64,
367    pub a: f64,
368}
369
370impl Color {
371    pub const fn rgba(r: f64, g: f64, b: f64, a: f64) -> Self {
372        Color { r, g, b, a }
373    }
374    pub const fn rgb(r: f64, g: f64, b: f64) -> Self {
375        Color::rgba(r, g, b, 1.0)
376    }
377    pub const BLACK: Color = Color::rgb(0.0, 0.0, 0.0);
378    pub const WHITE: Color = Color::rgb(1.0, 1.0, 1.0);
379    pub const CLEAR: Color = Color::rgba(0.0, 0.0, 0.0, 0.0);
380    /// 0xRRGGBB
381    pub const fn hex(v: u32) -> Self {
382        Color::rgb(
383            ((v >> 16) & 0xff) as f64 / 255.0,
384            ((v >> 8) & 0xff) as f64 / 255.0,
385            (v & 0xff) as f64 / 255.0,
386        )
387    }
388
389    /// From HSL: `h` in degrees (wraps mod 360), `s`/`l` in `0.0..=1.0`. `Color` is the one color
390    /// type every parameter accepts, so this makes HSL usable everywhere a color is.
391    pub fn hsl(h: f64, s: f64, l: f64) -> Self {
392        Color::hsla(h, s, l, 1.0)
393    }
394    pub fn hsla(h: f64, s: f64, l: f64, a: f64) -> Self {
395        let (s, l) = (s.clamp(0.0, 1.0), l.clamp(0.0, 1.0));
396        if s == 0.0 {
397            return Color::rgba(l, l, l, a);
398        }
399        let hk = h.rem_euclid(360.0) / 360.0;
400        let q = if l < 0.5 {
401            l * (1.0 + s)
402        } else {
403            l + s - l * s
404        };
405        let p = 2.0 * l - q;
406        Color::rgba(
407            hue2rgb(p, q, hk + 1.0 / 3.0),
408            hue2rgb(p, q, hk),
409            hue2rgb(p, q, hk - 1.0 / 3.0),
410            a,
411        )
412    }
413
414    /// From HSV/HSB: `h` degrees (wraps), `s`/`v` in `0.0..=1.0`.
415    pub fn hsv(h: f64, s: f64, v: f64) -> Self {
416        Color::hsva(h, s, v, 1.0)
417    }
418    pub fn hsva(h: f64, s: f64, v: f64, a: f64) -> Self {
419        let (s, v) = (s.clamp(0.0, 1.0), v.clamp(0.0, 1.0));
420        let hh = h.rem_euclid(360.0) / 60.0;
421        let c = v * s;
422        let x = c * (1.0 - (hh % 2.0 - 1.0).abs());
423        let m = v - c;
424        let (r, g, b) = match hh as i32 {
425            0 => (c, x, 0.0),
426            1 => (x, c, 0.0),
427            2 => (0.0, c, x),
428            3 => (0.0, x, c),
429            4 => (x, 0.0, c),
430            _ => (c, 0.0, x),
431        };
432        Color::rgba(r + m, g + m, b + m, a)
433    }
434
435    /// Decompose to `(hue°, saturation, lightness)` (HSL). Hue is `0.0` for grays.
436    #[must_use]
437    #[expect(
438        clippy::float_cmp,
439        reason = "`max` is a copy of one of the three channels, so equality is exact"
440    )]
441    pub fn to_hsl(&self) -> (f64, f64, f64) {
442        let (r, g, b) = (self.r, self.g, self.b);
443        let max = r.max(g).max(b);
444        let min = r.min(g).min(b);
445        let l = f64::midpoint(max, min);
446        let d = max - min;
447        if d.abs() < 1e-9 {
448            return (0.0, 0.0, l);
449        }
450        let s = d / (1.0 - (2.0 * l - 1.0).abs());
451        let h = if max == r {
452            60.0 * (((g - b) / d).rem_euclid(6.0))
453        } else if max == g {
454            60.0 * ((b - r) / d + 2.0)
455        } else {
456            60.0 * ((r - g) / d + 4.0)
457        };
458        (h.rem_euclid(360.0), s.clamp(0.0, 1.0), l)
459    }
460
461    /// Decompose to `(hue°, saturation, value)` (HSV/HSB), the model every native color picker's
462    /// spectrum tab is built on, so this is what a renderer seeds its sliders from. Hue is `0.0`
463    /// for grays. Inverse of [`Color::hsv`].
464    #[must_use]
465    #[expect(
466        clippy::float_cmp,
467        reason = "`max` is a copy of one of the three channels, so equality is exact"
468    )]
469    pub fn to_hsv(&self) -> (f64, f64, f64) {
470        let (r, g, b) = (self.r, self.g, self.b);
471        let max = r.max(g).max(b);
472        let min = r.min(g).min(b);
473        let d = max - min;
474        if d.abs() < 1e-9 {
475            return (0.0, 0.0, max);
476        }
477        let h = if max == r {
478            60.0 * (((g - b) / d).rem_euclid(6.0))
479        } else if max == g {
480            60.0 * ((b - r) / d + 2.0)
481        } else {
482            60.0 * ((r - g) / d + 4.0)
483        };
484        (h.rem_euclid(360.0), d / max, max)
485    }
486
487    /// The same color at a different opacity: what a picker's alpha slider produces, and what
488    /// tinting a surface down to a wash needs (`palette.with_alpha(0.14)`).
489    #[must_use]
490    pub fn with_alpha(self, a: f64) -> Color {
491        Color { a, ..self }
492    }
493
494    /// `#rrggbb`, or `#rrggbbaa` when the color is not fully opaque. The 8-bit form every
495    /// platform's own color field speaks, and what [`Color::parse`] round-trips.
496    #[must_use]
497    pub fn to_hex_string(&self) -> String {
498        let q = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
499        if self.a >= 1.0 {
500            format!("#{:02x}{:02x}{:02x}", q(self.r), q(self.g), q(self.b))
501        } else {
502            format!(
503                "#{:02x}{:02x}{:02x}{:02x}",
504                q(self.r),
505                q(self.g),
506                q(self.b),
507                q(self.a)
508            )
509        }
510    }
511
512    /// Parse a color from either interchange form:
513    ///
514    /// - **hex**: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa` (the leading `#` optional). What a
515    ///   person types, and what an 8-bit platform field (`<input type="color">`, `Windows.UI.Color`,
516    ///   `android.graphics.Color`) hands back.
517    /// - **components**: 3 or 4 space-separated floats in `0.0..=1.0`, `"r g b"` / `"r g b a"`.
518    ///   The lossless form, for the toolkits whose picker really is float-precision (`NSColor`,
519    ///   `GdkRGBA`, `QColor::getRgbF`).
520    ///
521    /// `None` on anything else. See [docs/color.md](https://daybrite.dev/docs/reference/color) for
522    /// why the currency stays sRGB for now and what a wider one would carry.
523    #[must_use]
524    pub fn parse(s: &str) -> Option<Color> {
525        let s = s.trim();
526        let hex = s.strip_prefix('#').unwrap_or(s);
527        if !hex.is_empty() && hex.bytes().all(|b| b.is_ascii_hexdigit()) {
528            let nib = |i: usize| u8::from_str_radix(&hex[i..=i], 16).ok().map(f64::from);
529            let byte = |i: usize| {
530                u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16)
531                    .ok()
532                    .map(f64::from)
533            };
534            return match hex.len() {
535                3 | 4 => Some(Color::rgba(
536                    nib(0)? / 15.0,
537                    nib(1)? / 15.0,
538                    nib(2)? / 15.0,
539                    if hex.len() == 4 { nib(3)? / 15.0 } else { 1.0 },
540                )),
541                6 | 8 => Some(Color::rgba(
542                    byte(0)? / 255.0,
543                    byte(1)? / 255.0,
544                    byte(2)? / 255.0,
545                    if hex.len() == 8 {
546                        byte(3)? / 255.0
547                    } else {
548                        1.0
549                    },
550                )),
551                _ => None,
552            };
553        }
554        let mut it = s.split_whitespace();
555        let (r, g, b) = (
556            it.next()?.parse::<f64>().ok()?,
557            it.next()?.parse::<f64>().ok()?,
558            it.next()?.parse::<f64>().ok()?,
559        );
560        let a = match it.next() {
561            Some(a) => a.parse::<f64>().ok()?,
562            None => 1.0,
563        };
564        if it.next().is_some() {
565            return None;
566        }
567        Some(Color::rgba(
568            r.clamp(0.0, 1.0),
569            g.clamp(0.0, 1.0),
570            b.clamp(0.0, 1.0),
571            a.clamp(0.0, 1.0),
572        ))
573    }
574
575    /// Interpolate toward `to` in HSL space, taking the shortest hue arc (`t` in `0.0..=1.0`). A
576    /// hue-space blend (red→green sweeps through yellow) rather than the muddy RGB straight line,
577    /// used by the canvas / self-driven animation path (native widget color animation interpolates
578    /// in the toolkit's own space).
579    #[must_use]
580    pub fn lerp_hsl(self, to: Color, t: f64) -> Color {
581        let (h0, s0, l0) = self.to_hsl();
582        let (h1, s1, l1) = to.to_hsl();
583        let mut dh = (h1 - h0).rem_euclid(360.0);
584        if dh > 180.0 {
585            dh -= 360.0;
586        }
587        let lerp = |a: f64, b: f64| a + (b - a) * t;
588        Color::hsla(h0 + dh * t, lerp(s0, s1), lerp(l0, l1), lerp(self.a, to.a))
589    }
590}
591
592/// The lossless interchange form: four space-separated components, exactly what
593/// [`Color::parse`] reads back. This is what crosses a JNI / C-ABI / JS boundary when a native
594/// color picker reports a pick, so the float precision `NSColor` and `GdkRGBA` really carry is
595/// not rounded to 8 bits on the way. For the form a person reads (and types into a dayscript
596/// step) use [`Color::to_hex_string`].
597impl std::fmt::Display for Color {
598    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
599        write!(f, "{} {} {} {}", self.r, self.g, self.b, self.a)
600    }
601}
602
603/// HSL hue channel → RGB component (helper for [`Color::hsla`]).
604fn hue2rgb(p: f64, q: f64, t: f64) -> f64 {
605    let t = t.rem_euclid(1.0);
606    if t < 1.0 / 6.0 {
607        p + (q - p) * 6.0 * t
608    } else if t < 1.0 / 2.0 {
609        q
610    } else if t < 2.0 / 3.0 {
611        p + (q - p) * (2.0 / 3.0 - t) * 6.0
612    } else {
613        p
614    }
615}
616
617/// The layout proposal: `None` = unconstrained on that axis (§7.2).
618#[derive(Clone, Copy, Debug, Default, PartialEq)]
619pub struct Proposal {
620    pub width: Option<f64>,
621    pub height: Option<f64>,
622}
623
624impl Proposal {
625    pub const UNCONSTRAINED: Proposal = Proposal {
626        width: None,
627        height: None,
628    };
629    #[inline]
630    #[must_use]
631    pub const fn new(width: Option<f64>, height: Option<f64>) -> Self {
632        Proposal { width, height }
633    }
634    #[inline]
635    #[must_use]
636    pub const fn exact(size: Size) -> Self {
637        Proposal {
638            width: Some(size.width),
639            height: Some(size.height),
640        }
641    }
642    /// Quantized key for the measurement cache (§7.4): tenth-of-a-point buckets.
643    #[must_use]
644    pub fn cache_key(&self) -> (u64, u64) {
645        #[inline]
646        fn q(v: Option<f64>) -> u64 {
647            match v {
648                None => u64::MAX,
649                Some(f) => (f * 10.0).round().max(0.0) as u64,
650            }
651        }
652        (q(self.width), q(self.height))
653    }
654}
655
656#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
657pub enum LayoutDirection {
658    #[default]
659    Ltr,
660    Rtl,
661}
662
663/// A cheap per-node visual transform (§8.4 animation): translation, uniform/non-uniform scale, and
664/// rotation about a unit anchor (`0.0..1.0` within the node's bounds; default center). Distinct
665/// from the layout frame: animating a `Transform` never triggers relayout, so it is the vehicle
666/// for movement/scaling animation. Each backend composes it onto the node's laid-out frame via its
667/// native transform channel (`CALayer/GskTransform/RenderTransform/NODE_TRANSFORM`/…).
668#[derive(Clone, Copy, Debug, PartialEq)]
669pub struct Transform {
670    pub tx: f64,
671    pub ty: f64,
672    pub sx: f64,
673    pub sy: f64,
674    pub rotate_deg: f64,
675    /// Anchor for scale/rotation as a unit fraction of the node's bounds (`0.5,0.5` = center).
676    pub anchor_x: f64,
677    pub anchor_y: f64,
678}
679
680impl Default for Transform {
681    fn default() -> Self {
682        Transform::IDENTITY
683    }
684}
685
686impl Transform {
687    pub const IDENTITY: Transform = Transform {
688        tx: 0.0,
689        ty: 0.0,
690        sx: 1.0,
691        sy: 1.0,
692        rotate_deg: 0.0,
693        anchor_x: 0.5,
694        anchor_y: 0.5,
695    };
696
697    #[inline]
698    #[must_use]
699    pub const fn translate(tx: f64, ty: f64) -> Transform {
700        Transform {
701            tx,
702            ty,
703            ..Transform::IDENTITY
704        }
705    }
706    #[inline]
707    #[must_use]
708    pub const fn scale(sx: f64, sy: f64) -> Transform {
709        Transform {
710            sx,
711            sy,
712            ..Transform::IDENTITY
713        }
714    }
715    #[inline]
716    #[must_use]
717    pub const fn rotate(deg: f64) -> Transform {
718        Transform {
719            rotate_deg: deg,
720            ..Transform::IDENTITY
721        }
722    }
723    /// Whether this transform has no visual effect; backends skip applying it.
724    #[inline]
725    #[must_use]
726    pub fn is_identity(&self) -> bool {
727        *self == Transform::IDENTITY
728    }
729}
730
731/// Linear interpolation of animatable values (`t` in `0.0..1.0`). This drives the **canvas /
732/// self-driven** animation path (docs/shapes.md §5) and Qt's sampled spring; native-widget
733/// animation does not use it; the toolkit interpolates on its own compositor.
734pub trait Animatable: Copy {
735    #[must_use]
736    fn lerp(self, to: Self, t: f64) -> Self;
737}
738
739#[inline]
740fn flerp(a: f64, b: f64, t: f64) -> f64 {
741    a + (b - a) * t
742}
743
744impl Animatable for f64 {
745    #[inline]
746    fn lerp(self, to: f64, t: f64) -> f64 {
747        flerp(self, to, t)
748    }
749}
750impl Animatable for Point {
751    #[inline]
752    fn lerp(self, to: Point, t: f64) -> Point {
753        Point::new(flerp(self.x, to.x, t), flerp(self.y, to.y, t))
754    }
755}
756impl Animatable for Size {
757    #[inline]
758    fn lerp(self, to: Size, t: f64) -> Size {
759        Size::new(
760            flerp(self.width, to.width, t),
761            flerp(self.height, to.height, t),
762        )
763    }
764}
765impl Animatable for Rect {
766    #[inline]
767    fn lerp(self, to: Rect, t: f64) -> Rect {
768        Rect {
769            origin: self.origin.lerp(to.origin, t),
770            size: self.size.lerp(to.size, t),
771        }
772    }
773}
774impl Animatable for Color {
775    #[inline]
776    fn lerp(self, to: Color, t: f64) -> Color {
777        Color::rgba(
778            flerp(self.r, to.r, t),
779            flerp(self.g, to.g, t),
780            flerp(self.b, to.b, t),
781            flerp(self.a, to.a, t),
782        )
783    }
784}
785impl Animatable for Transform {
786    #[inline]
787    fn lerp(self, to: Transform, t: f64) -> Transform {
788        // Anchor snaps to the destination's (it's a coordinate frame, not a visual value).
789        Transform {
790            tx: flerp(self.tx, to.tx, t),
791            ty: flerp(self.ty, to.ty, t),
792            sx: flerp(self.sx, to.sx, t),
793            sy: flerp(self.sy, to.sy, t),
794            rotate_deg: flerp(self.rotate_deg, to.rotate_deg, t),
795            anchor_x: to.anchor_x,
796            anchor_y: to.anchor_y,
797        }
798    }
799}
800
801#[cfg(test)]
802mod tests {
803    use super::*;
804
805    #[test]
806    fn rect_insets() {
807        let r = Rect::new(10.0, 10.0, 100.0, 50.0).inset_by(Insets::symmetric(4.0, 2.0));
808        assert_eq!(r, Rect::new(14.0, 12.0, 92.0, 46.0));
809    }
810
811    #[test]
812    fn hsl_primaries_and_roundtrip() {
813        let approx = |a: Color, b: Color| {
814            (a.r - b.r).abs() < 1e-6 && (a.g - b.g).abs() < 1e-6 && (a.b - b.b).abs() < 1e-6
815        };
816        assert!(approx(Color::hsl(0.0, 1.0, 0.5), Color::rgb(1.0, 0.0, 0.0))); // red
817        assert!(approx(
818            Color::hsl(120.0, 1.0, 0.5),
819            Color::rgb(0.0, 1.0, 0.0)
820        )); // green
821        assert!(approx(
822            Color::hsl(240.0, 1.0, 0.5),
823            Color::rgb(0.0, 0.0, 1.0)
824        )); // blue
825        assert!(approx(Color::hsl(0.0, 0.0, 0.5), Color::rgb(0.5, 0.5, 0.5))); // gray
826        assert!(approx(Color::hsv(0.0, 1.0, 1.0), Color::rgb(1.0, 0.0, 0.0))); // hsv red
827        // Hue wraps, and to_hsl inverts hsl.
828        let (h, s, l) = Color::hsl(370.0, 0.6, 0.4).to_hsl();
829        assert!((h - 10.0).abs() < 1e-3 && (s - 0.6).abs() < 1e-3 && (l - 0.4).abs() < 1e-3);
830        // Shortest-arc hue lerp red→(hue 300, magenta) goes the short way (down through 330), not
831        // through green; midpoint hue ≈ 330.
832        let mid = Color::hsl(0.0, 1.0, 0.5).lerp_hsl(Color::hsl(300.0, 1.0, 0.5), 0.5);
833        assert!((mid.to_hsl().0 - 330.0).abs() < 1.0);
834    }
835
836    #[test]
837    fn hsv_roundtrip_and_gray_hue() {
838        let c = Color::rgb(0.2, 0.7, 0.45);
839        let (h, s, v) = c.to_hsv();
840        let back = Color::hsv(h, s, v);
841        assert!((back.r - c.r).abs() < 1e-6 && (back.g - c.g).abs() < 1e-6);
842        assert!((back.b - c.b).abs() < 1e-6);
843        // A gray has no hue to report; saturation 0 is what the sliders need to show.
844        assert_eq!(Color::rgb(0.4, 0.4, 0.4).to_hsv(), (0.0, 0.0, 0.4));
845    }
846
847    #[test]
848    fn color_hex_and_component_parsing() {
849        // Every hex width, with and without the `#`.
850        let coral = Color::hex(0x00E8_6A3C);
851        for s in ["#e86a3c", "E86A3C", "#e86a3cff"] {
852            let p = Color::parse(s).unwrap();
853            assert!((p.r - coral.r).abs() < 1e-9, "{s}");
854            assert!(
855                (p.g - coral.g).abs() < 1e-9 && (p.b - coral.b).abs() < 1e-9,
856                "{s}"
857            );
858            assert_eq!(p.a, 1.0, "{s}");
859        }
860        assert_eq!(Color::parse("#f00").unwrap(), Color::rgb(1.0, 0.0, 0.0));
861        assert_eq!(
862            Color::parse("#0000").unwrap(),
863            Color::rgba(0.0, 0.0, 0.0, 0.0)
864        );
865        assert_eq!(Color::parse("#00000080").unwrap().a, 128.0 / 255.0);
866        // The lossless component form, what a native pick crosses a boundary as.
867        assert_eq!(Color::parse("1 0 0").unwrap(), Color::rgb(1.0, 0.0, 0.0));
868        let c = Color::rgba(0.937_254_901, 0.4, 0.298, 0.6);
869        assert_eq!(
870            Color::parse(&c.to_string()).unwrap(),
871            c,
872            "Display round-trips"
873        );
874        // 8-bit round trip through the human form.
875        assert_eq!(Color::parse(&coral.to_hex_string()).unwrap(), coral);
876        assert_eq!(
877            Color::rgba(0.0, 0.0, 0.0, 0.5).to_hex_string(),
878            "#00000080",
879            "alpha appears only when it is not opaque"
880        );
881        for bad in ["", "#12345", "not-a-color", "1 0", "1 0 0 0 0", "#gg0000"] {
882            assert!(Color::parse(bad).is_none(), "{bad:?} rejected");
883        }
884    }
885
886    #[test]
887    fn proposal_cache_key_quantizes() {
888        assert_eq!(
889            Proposal::new(Some(100.02), None).cache_key(),
890            Proposal::new(Some(100.04), None).cache_key()
891        );
892        assert_ne!(
893            Proposal::new(Some(100.0), None).cache_key(),
894            Proposal::UNCONSTRAINED.cache_key()
895        );
896    }
897}