Skip to main content

native_theme/
color.rs

1// Rgba color type with custom hex serde
2
3use serde::de;
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5use std::fmt;
6use std::str::FromStr;
7
8/// An sRGB color with alpha, stored as four u8 components.
9///
10/// All values are in the sRGB color space. When parsing hex strings,
11/// alpha defaults to 255 (fully opaque) if omitted.
12///
13/// # Hex Format
14///
15/// Supports parsing from and displaying as hex strings:
16/// - `#RGB` / `RGB` -- 3-digit shorthand (each digit doubled: `#abc` -> `#aabbcc`)
17/// - `#RGBA` / `RGBA` -- 4-digit shorthand with alpha
18/// - `#RRGGBB` / `RRGGBB` -- standard 6-digit hex
19/// - `#RRGGBBAA` / `RRGGBBAA` -- 8-digit hex with alpha
20///
21/// Display outputs lowercase hex: `#rrggbb` when alpha is 255,
22/// `#rrggbbaa` otherwise.
23///
24/// # Examples
25///
26/// ```
27/// use native_theme::color::Rgba;
28///
29/// // Create an opaque color
30/// let blue = Rgba::rgb(0, 120, 215);
31/// assert_eq!(blue.a, 255);
32///
33/// // Parse from a hex string
34/// let parsed: Rgba = "#3daee9".parse().unwrap();
35/// assert_eq!(parsed.r, 61);
36///
37/// // Convert to f32 array for toolkit interop
38/// let arr = Rgba::rgb(255, 0, 0).to_f32_array();
39/// assert_eq!(arr, [1.0, 0.0, 0.0, 1.0]);
40/// ```
41///
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
43pub struct Rgba {
44    /// Red component (0-255).
45    pub r: u8,
46    /// Green component (0-255).
47    pub g: u8,
48    /// Blue component (0-255).
49    pub b: u8,
50    /// Alpha component (0-255, where 255 is fully opaque).
51    pub a: u8,
52}
53
54// Phase 93-01 (G1): no `impl Default for Rgba`. §16 of the v0.5.7 API
55// critique flagged that a theme library where `Rgba::default()` silently
56// returns "transparent black" is a footgun. Callers who need a named zero
57// colour use `Rgba::TRANSPARENT`, `Rgba::BLACK`, or `Rgba::WHITE` (all
58// `const`). Task 1 of this plan broke the sole transitive bound chain that
59// forced the Default impl (see `resolve::validate_helpers::require`).
60
61impl Rgba {
62    /// Create an opaque color (alpha = 255).
63    #[must_use]
64    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
65        Self { r, g, b, a: 255 }
66    }
67
68    /// Create a color with explicit red, green, blue, and alpha components.
69    #[must_use]
70    pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
71        Self { r, g, b, a }
72    }
73
74    /// Transparent black `(0, 0, 0, 0)` -- the zero colour.
75    ///
76    /// ```
77    /// use native_theme::color::Rgba;
78    ///
79    /// assert_eq!(Rgba::TRANSPARENT, Rgba::new(0, 0, 0, 0));
80    /// assert_eq!(Rgba::BLACK, Rgba::new(0, 0, 0, 255));
81    /// assert_eq!(Rgba::WHITE, Rgba::new(255, 255, 255, 255));
82    /// ```
83    pub const TRANSPARENT: Self = Self {
84        r: 0,
85        g: 0,
86        b: 0,
87        a: 0,
88    };
89
90    /// Opaque black `(0, 0, 0, 255)`.
91    pub const BLACK: Self = Self {
92        r: 0,
93        g: 0,
94        b: 0,
95        a: 255,
96    };
97
98    /// Opaque white `(255, 255, 255, 255)`.
99    pub const WHITE: Self = Self {
100        r: 255,
101        g: 255,
102        b: 255,
103        a: 255,
104    };
105
106    /// Create a color from floating-point components in the 0.0..=1.0 range.
107    ///
108    /// Values are clamped to 0.0..=1.0 before conversion.
109    ///
110    /// Note: round-trip through `from_f32` -> `to_f32_array` is lossy due to
111    /// u8 quantization (e.g., `from_f32(0.5, ...)` -> r=128 ->
112    /// `to_f32_array()` -> 0.50196...).
113    #[must_use]
114    pub fn from_f32(r: f32, g: f32, b: f32, a: f32) -> Self {
115        Self {
116            r: (r.clamp(0.0, 1.0) * 255.0).round() as u8,
117            g: (g.clamp(0.0, 1.0) * 255.0).round() as u8,
118            b: (b.clamp(0.0, 1.0) * 255.0).round() as u8,
119            a: (a.clamp(0.0, 1.0) * 255.0).round() as u8,
120        }
121    }
122
123    /// Convert to `[r, g, b, a]` in the 0.0..=1.0 range (for toolkit interop).
124    ///
125    /// Note: round-trip through `from_f32` -> `to_f32_array` is lossy due to
126    /// u8 quantization (256 discrete steps per channel).
127    #[must_use]
128    pub fn to_f32_array(&self) -> [f32; 4] {
129        [
130            self.r as f32 / 255.0,
131            self.g as f32 / 255.0,
132            self.b as f32 / 255.0,
133            self.a as f32 / 255.0,
134        ]
135    }
136}
137
138/// `layer` composited over `base`: source-over with straight (not
139/// premultiplied) alpha in sRGB, each colour `[r, g, b, a]` in `0.0..=1.0`
140/// as [`Rgba::to_f32_array`] gives it.
141///
142/// The result covers `a = layer.a + base.a × (1 − layer.a)`, and each channel
143/// is the two channels weighted by what each contributes, divided by `a`, so
144/// a translucent layer over a translucent base covers more than either. Where
145/// one input decides the result, that input is returned exactly, with no
146/// division to move it by an ulp:
147///
148/// - an opaque layer (`layer.a >= 1`) is the layer;
149/// - a transparent layer (`layer.a <= 0`) is `base`, a transparent one
150///   included;
151/// - a layer over a transparent base (`base.a <= 0`) is the layer.
152///
153/// This is how a platform lays a stated hover or pressed colour over a
154/// widget's fill (a state *layer*), for a toolkit that replaces the fill per
155/// state instead: the iced and gpui connectors composite with it, so an
156/// application drawing a layered state of its own matches them. The blend is
157/// in sRGB rather than linear light, because it reproduces the composite the
158/// platform performed when it measured the value a preset records, and
159/// platform compositors blend in sRGB.
160///
161/// ```
162/// use native_theme::color::composite_over;
163///
164/// let half_black = [0.0, 0.0, 0.0, 0.5];
165/// assert_eq!(composite_over(half_black, [1.0, 1.0, 1.0, 1.0]), [0.5, 0.5, 0.5, 1.0]);
166/// assert_eq!(composite_over(half_black, half_black)[3], 0.75);
167/// ```
168#[must_use]
169pub fn composite_over(layer: [f32; 4], base: [f32; 4]) -> [f32; 4] {
170    let [lr, lg, lb, la] = layer;
171    let [br, bg, bb, ba] = base;
172    if la >= 1.0 {
173        return layer;
174    }
175    if la <= 0.0 {
176        return base;
177    }
178    if ba <= 0.0 {
179        return layer;
180    }
181    // How much of `base` reaches the result, in the composite's own alpha.
182    let under = ba * (1.0 - la);
183    let a = la + under;
184    let channel = |l: f32, b: f32| (l * la + b * under) / a;
185    [channel(lr, br), channel(lg, bg), channel(lb, bb), a]
186}
187
188impl fmt::Display for Rgba {
189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190        if self.a == 255 {
191            write!(f, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
192        } else {
193            write!(
194                f,
195                "#{:02x}{:02x}{:02x}{:02x}",
196                self.r, self.g, self.b, self.a
197            )
198        }
199    }
200}
201
202/// Error returned when parsing a hex color string fails.
203///
204/// Wraps a human-readable message describing the failure cause.
205/// Implements [`std::error::Error`] so it works with `?` in functions
206/// returning `Box<dyn Error>`.
207#[derive(Debug, Clone)]
208pub struct ParseColorError(String);
209
210impl fmt::Display for ParseColorError {
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        f.write_str(&self.0)
213    }
214}
215
216impl std::error::Error for ParseColorError {}
217
218/// Parse one ASCII hex digit byte to a nibble (0..=15).
219fn hex_nibble(b: u8, label: &str) -> Result<u8, ParseColorError> {
220    char::from(b)
221        .to_digit(16)
222        .and_then(|v| u8::try_from(v).ok())
223        .ok_or_else(|| ParseColorError(format!("invalid {label} hex digit {:?}", char::from(b))))
224}
225
226/// Combine two nibbles (high, low) into a byte. Inputs assumed 0..=15.
227fn hex_byte(hi: u8, lo: u8) -> u8 {
228    // wrapping_shl(4) on 0..=15 produces 0..=240 in u8; BitOr is not panic-prone.
229    hi.wrapping_shl(4) | (lo & 0x0f)
230}
231
232/// Expand a nibble to a byte by doubling it: `0xf -> 0xff`, `0xa -> 0xaa`.
233/// Equivalent to `n * 17` for `n` in 0..=15, but panic-free.
234fn double_nibble(n: u8) -> u8 {
235    n.wrapping_shl(4) | (n & 0x0f)
236}
237
238impl FromStr for Rgba {
239    type Err = ParseColorError;
240
241    fn from_str(s: &str) -> Result<Self, Self::Err> {
242        let hex = s.strip_prefix('#').unwrap_or(s);
243
244        if hex.is_empty() {
245            return Err(ParseColorError("empty hex color string".into()));
246        }
247
248        // A non-ASCII char is 2+ bytes in UTF-8, so its bytes could fill the
249        // single-byte slots below and be reported as a wrong digit or length.
250        if !hex.is_ascii() {
251            return Err(ParseColorError(format!(
252                "invalid hex color {s:?}: not ASCII hex digits"
253            )));
254        }
255
256        // Destructure hex bytes directly: with ASCII input each byte is one char,
257        // and this avoids panic-prone string slicing / indexing.
258        match hex.as_bytes() {
259            // #RGB shorthand: each digit doubled (e.g., 'a' -> 0xaa)
260            [r, g, b] => {
261                let r = hex_nibble(*r, "red")?;
262                let g = hex_nibble(*g, "green")?;
263                let b = hex_nibble(*b, "blue")?;
264                Ok(Rgba::rgb(
265                    double_nibble(r),
266                    double_nibble(g),
267                    double_nibble(b),
268                ))
269            }
270            // #RGBA shorthand
271            [r, g, b, a] => {
272                let r = hex_nibble(*r, "red")?;
273                let g = hex_nibble(*g, "green")?;
274                let b = hex_nibble(*b, "blue")?;
275                let a = hex_nibble(*a, "alpha")?;
276                Ok(Rgba::new(
277                    double_nibble(r),
278                    double_nibble(g),
279                    double_nibble(b),
280                    double_nibble(a),
281                ))
282            }
283            // #RRGGBB
284            [r1, r2, g1, g2, b1, b2] => {
285                let r = hex_byte(hex_nibble(*r1, "red")?, hex_nibble(*r2, "red")?);
286                let g = hex_byte(hex_nibble(*g1, "green")?, hex_nibble(*g2, "green")?);
287                let b = hex_byte(hex_nibble(*b1, "blue")?, hex_nibble(*b2, "blue")?);
288                Ok(Rgba::rgb(r, g, b))
289            }
290            // #RRGGBBAA
291            [r1, r2, g1, g2, b1, b2, a1, a2] => {
292                let r = hex_byte(hex_nibble(*r1, "red")?, hex_nibble(*r2, "red")?);
293                let g = hex_byte(hex_nibble(*g1, "green")?, hex_nibble(*g2, "green")?);
294                let b = hex_byte(hex_nibble(*b1, "blue")?, hex_nibble(*b2, "blue")?);
295                let a = hex_byte(hex_nibble(*a1, "alpha")?, hex_nibble(*a2, "alpha")?);
296                Ok(Rgba::new(r, g, b, a))
297            }
298            other => Err(ParseColorError(format!(
299                "invalid hex color length {}: expected 3, 4, 6, or 8 hex digits",
300                other.len()
301            ))),
302        }
303    }
304}
305
306impl Serialize for Rgba {
307    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
308        serializer.serialize_str(&self.to_string())
309    }
310}
311
312impl<'de> Deserialize<'de> for Rgba {
313    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
314        let s = String::deserialize(deserializer)?;
315        Rgba::from_str(&s).map_err(de::Error::custom)
316    }
317}
318
319/// Convert premultiplied RGBA pixel data to straight (non-premultiplied) alpha.
320///
321/// For each pixel where `a > 0 && a < 255`:
322///   `channel = min(255, channel * 255 / a)`
323///
324/// Fully opaque pixels (a == 255) and fully transparent pixels (a == 0)
325/// are left unchanged.
326///
327/// Used by `rasterize`, `sficons`, and `winicons` modules (feature/platform gated).
328#[allow(dead_code)]
329pub(crate) fn unpremultiply_alpha(buffer: &mut [u8]) {
330    // `as_chunks_mut::<4>()` splits the buffer into `[u8; 4]` pixels plus a
331    // remainder shorter than one pixel; the remainder is dropped, as
332    // `chunks_exact_mut(4)` did. Array destructuring binds each byte without
333    // panic-prone indexing.
334    for pixel in buffer.as_chunks_mut::<4>().0 {
335        let [r, g, b, a] = pixel;
336        let a_val = u16::from(*a);
337        // `a_val in 1..=254` guarantees the divisor is non-zero; `saturating_mul`
338        // cannot overflow u16 (max 255 * 255 = 65025 < 65535). The `.min(255)` cap
339        // makes the final `as u8` a lossless conversion (no truncation of high bits).
340        if (1..255).contains(&a_val) {
341            #[allow(clippy::integer_division, clippy::arithmetic_side_effects)]
342            {
343                *r = (u16::from(*r).saturating_mul(255) / a_val).min(255) as u8;
344                *g = (u16::from(*g).saturating_mul(255) / a_val).min(255) as u8;
345                *b = (u16::from(*b).saturating_mul(255) / a_val).min(255) as u8;
346            }
347        }
348    }
349}
350
351/// Draw a monochrome straight-alpha RGBA raster in `rgb`.
352///
353/// Every pixel takes `rgb` and keeps its alpha, so the glyph's coverage is
354/// unchanged. `None` leaves the buffer as it is.
355///
356/// Used by `sficons` and `winicons` (platform gated) for their monochrome
357/// glyphs; full-colour icons are never passed here.
358#[allow(dead_code)]
359pub(crate) fn tint_monochrome(buffer: &mut [u8], rgb: Option<[u8; 3]>) {
360    let Some([r, g, b]) = rgb else {
361        return;
362    };
363    for pixel in buffer.as_chunks_mut::<4>().0 {
364        let [_, _, _, a] = *pixel;
365        *pixel = [r, g, b, a];
366    }
367}
368
369#[cfg(test)]
370#[allow(clippy::unwrap_used, clippy::expect_used)]
371mod tests {
372    use super::*;
373
374    // === Constructor tests ===
375
376    #[test]
377    fn rgb_constructor_sets_alpha_255() {
378        let c = Rgba::rgb(61, 174, 233);
379        assert_eq!(
380            c,
381            Rgba {
382                r: 61,
383                g: 174,
384                b: 233,
385                a: 255
386            }
387        );
388    }
389
390    #[test]
391    fn rgba_constructor_sets_all_fields() {
392        let c = Rgba::new(61, 174, 233, 128);
393        assert_eq!(
394            c,
395            Rgba {
396                r: 61,
397                g: 174,
398                b: 233,
399                a: 128
400            }
401        );
402    }
403
404    // === FromStr parsing tests ===
405
406    #[test]
407    fn parse_6_digit_hex_with_hash() {
408        let c: Rgba = "#3daee9".parse().unwrap();
409        assert_eq!(c, Rgba::rgb(61, 174, 233));
410    }
411
412    #[test]
413    fn parse_8_digit_hex_with_hash() {
414        let c: Rgba = "#3daee980".parse().unwrap();
415        assert_eq!(c, Rgba::new(61, 174, 233, 128));
416    }
417
418    #[test]
419    fn parse_6_digit_hex_without_hash() {
420        let c: Rgba = "3daee9".parse().unwrap();
421        assert_eq!(c, Rgba::rgb(61, 174, 233));
422    }
423
424    #[test]
425    fn parse_3_digit_shorthand() {
426        let c: Rgba = "#abc".parse().unwrap();
427        assert_eq!(c, Rgba::rgb(0xaa, 0xbb, 0xcc));
428    }
429
430    #[test]
431    fn parse_4_digit_shorthand() {
432        let c: Rgba = "#abcd".parse().unwrap();
433        assert_eq!(c, Rgba::new(0xaa, 0xbb, 0xcc, 0xdd));
434    }
435
436    #[test]
437    fn parse_uppercase_hex() {
438        let c: Rgba = "#AABBCC".parse().unwrap();
439        assert_eq!(c, Rgba::rgb(0xaa, 0xbb, 0xcc));
440    }
441
442    #[test]
443    fn parse_empty_string_is_error() {
444        assert!("".parse::<Rgba>().is_err());
445    }
446
447    #[test]
448    fn parse_invalid_hex_chars_is_error() {
449        assert!("#gggggg".parse::<Rgba>().is_err());
450    }
451
452    #[test]
453    fn parse_invalid_length_5_chars_is_error() {
454        assert!("#12345".parse::<Rgba>().is_err());
455    }
456
457    #[test]
458    fn parse_non_ascii_three_bytes_names_the_input() {
459        let err = "#é0".parse::<Rgba>().unwrap_err();
460        assert_eq!(
461            err.to_string(),
462            "invalid hex color \"#é0\": not ASCII hex digits"
463        );
464    }
465
466    #[test]
467    fn parse_non_ascii_two_bytes_names_the_input() {
468        let err = "#é".parse::<Rgba>().unwrap_err();
469        assert_eq!(
470            err.to_string(),
471            "invalid hex color \"#é\": not ASCII hex digits"
472        );
473    }
474
475    // === Display tests ===
476
477    #[test]
478    fn display_omits_alpha_when_255() {
479        assert_eq!(Rgba::rgb(61, 174, 233).to_string(), "#3daee9");
480    }
481
482    #[test]
483    fn display_includes_alpha_when_not_255() {
484        assert_eq!(Rgba::new(61, 174, 233, 128).to_string(), "#3daee980");
485    }
486
487    // === Serde round-trip tests ===
488
489    #[test]
490    fn serde_json_round_trip() {
491        let c = Rgba::rgb(61, 174, 233);
492        let json = serde_json::to_string(&c).unwrap();
493        assert_eq!(json, "\"#3daee9\"");
494        let deserialized: Rgba = serde_json::from_str(&json).unwrap();
495        assert_eq!(deserialized, c);
496    }
497
498    #[test]
499    fn serde_toml_round_trip() {
500        #[derive(Debug, PartialEq, Serialize, Deserialize)]
501        struct Wrapper {
502            color: Rgba,
503        }
504        let w = Wrapper {
505            color: Rgba::new(61, 174, 233, 128),
506        };
507        let toml_str = toml::to_string(&w).unwrap();
508        let deserialized: Wrapper = toml::from_str(&toml_str).unwrap();
509        assert_eq!(deserialized, w);
510    }
511
512    // === to_f32_array tests ===
513
514    #[test]
515    fn to_f32_array_black() {
516        let arr = Rgba::rgb(0, 0, 0).to_f32_array();
517        assert_eq!(arr, [0.0, 0.0, 0.0, 1.0]);
518    }
519
520    #[test]
521    fn to_f32_array_white_transparent() {
522        let arr = Rgba::new(255, 255, 255, 0).to_f32_array();
523        assert_eq!(arr, [1.0, 1.0, 1.0, 0.0]);
524    }
525
526    // === Trait tests ===
527
528    #[test]
529    fn rgba_is_copy() {
530        let a = Rgba::rgb(1, 2, 3);
531        let b = a; // Copy
532        assert_eq!(a, b); // a still accessible after copy
533    }
534
535    #[test]
536    fn rgba_is_hash() {
537        use std::collections::HashSet;
538        let mut set = HashSet::new();
539        set.insert(Rgba::rgb(1, 2, 3));
540        assert!(set.contains(&Rgba::rgb(1, 2, 3)));
541    }
542
543    // === from_f32 tests ===
544
545    #[test]
546    fn from_f32_basic() {
547        let c = Rgba::from_f32(1.0, 0.5, 0.0, 1.0);
548        assert_eq!(c.r, 255);
549        assert_eq!(c.g, 128); // 0.5 * 255 = 127.5, round to 128
550        assert_eq!(c.b, 0);
551        assert_eq!(c.a, 255);
552    }
553
554    #[test]
555    fn from_f32_clamps_out_of_range() {
556        let c = Rgba::from_f32(-0.5, 1.5, 0.0, 0.0);
557        assert_eq!(c.r, 0);
558        assert_eq!(c.g, 255);
559    }
560
561    // === tint_monochrome tests ===
562
563    #[test]
564    fn tint_monochrome_colours_a_white_glyph_and_keeps_alpha() {
565        let mut buf = [255u8, 255, 255, 255, 255, 255, 255, 127];
566        tint_monochrome(&mut buf, Some([10, 20, 30]));
567        assert_eq!(buf, [10, 20, 30, 255, 10, 20, 30, 127]);
568    }
569
570    #[test]
571    fn tint_monochrome_keeps_a_transparent_pixel_transparent() {
572        let mut buf = [0u8, 0, 0, 0];
573        tint_monochrome(&mut buf, Some([10, 20, 30]));
574        assert_eq!(buf[3], 0);
575    }
576
577    #[test]
578    fn tint_monochrome_without_a_colour_leaves_the_bytes() {
579        let original = [255u8, 255, 255, 127, 0, 0, 0, 255, 1, 2, 3, 0];
580        let mut buf = original;
581        tint_monochrome(&mut buf, None);
582        assert_eq!(buf, original);
583    }
584
585    // === composite_over tests ===
586
587    #[test]
588    fn composite_over_a_transparent_layer_is_the_base_exactly() {
589        let layer = [0.9, 0.1, 0.3, 0.0];
590        for base in [
591            [0.2, 0.4, 0.6, 1.0],
592            [0.2, 0.4, 0.6, 0.3],
593            // A transparent base keeps its own channels: nothing is divided.
594            [0.2, 0.4, 0.6, 0.0],
595        ] {
596            assert_eq!(composite_over(layer, base), base, "over {base:?}");
597        }
598    }
599
600    #[test]
601    fn composite_over_a_transparent_base_is_the_layer_exactly() {
602        let base = [0.2, 0.4, 0.6, 0.0];
603        for layer in [[0.9, 0.1, 0.3, 0.3], [0.1, 0.2, 0.3, 0.078_431_375]] {
604            assert_eq!(composite_over(layer, base), layer, "{layer:?}");
605        }
606    }
607
608    #[test]
609    fn composite_over_an_opaque_layer_is_the_layer() {
610        let layer = [0.3, 0.7, 0.1, 1.0];
611        for base in [[0.2, 0.4, 0.6, 1.0], [1.0, 1.0, 1.0, 0.25]] {
612            assert_eq!(composite_over(layer, base), layer, "over {base:?}");
613        }
614    }
615
616    /// Over an opaque base the result is opaque and each channel is the
617    /// plain mix `l·la + b·(1 − la)`.
618    #[test]
619    fn composite_over_an_opaque_base_is_the_plain_mix() {
620        let (layer, base) = ([0.9_f32, 0.1, 0.3, 0.5], [0.2_f32, 0.4, 0.6, 1.0]);
621        let [r, g, b, a] = composite_over(layer, base);
622        assert_eq!(a, 1.0);
623        let mix = |l: f32, b: f32| l * layer[3] + b * (1.0 - layer[3]);
624        assert_eq!(
625            [r, g, b],
626            [
627                mix(layer[0], base[0]),
628                mix(layer[1], base[1]),
629                mix(layer[2], base[2])
630            ]
631        );
632    }
633
634    /// A translucent layer over a translucent base covers more than either,
635    /// `la + ba·(1 − la)`, and its channels are un-premultiplied by that.
636    #[test]
637    fn composite_over_two_translucent_colours_covers_both() {
638        let (layer, base) = ([0.8_f32, 0.2, 0.4, 0.5], [1.0_f32, 1.0, 1.0, 0.25]);
639        let [r, g, b, a] = composite_over(layer, base);
640        assert_eq!(a, 0.5 + 0.25 * 0.5);
641        let under = 0.25 * 0.5;
642        let channel = |l: f32, b: f32| (l * 0.5 + b * under) / a;
643        assert_eq!(
644            [r, g, b],
645            [channel(0.8, 1.0), channel(0.2, 1.0), channel(0.4, 1.0)]
646        );
647        // Associative: stacked on the base first, then painted on white, is
648        // painting the base and then the layer.
649        let white = [1.0, 1.0, 1.0, 1.0];
650        let stacked = composite_over(composite_over(layer, base), white);
651        let painted = composite_over(layer, composite_over(base, white));
652        for (s, p) in stacked.into_iter().zip(painted) {
653            assert!((s - p).abs() < 1e-6, "{stacked:?} against {painted:?}");
654        }
655    }
656
657    /// macos-tahoe light's push button is `#00000014` (macos-tahoe.toml
658    /// `[light.button]`, docs/platform-facts.md:1177), and the pressed fill a
659    /// connector derives from it keeps that alpha; the pressed button is one
660    /// over the other, alpha 0.0784 → 0.1507 (the M6 T9 ruling).
661    #[test]
662    fn composite_over_macos_tahoe_lights_two_button_fills_is_source_over() {
663        let fill = Rgba::new(0, 0, 0, 0x14).to_f32_array();
664        let [.., a] = composite_over(fill, fill);
665        assert_eq!(a, fill[3] + fill[3] * (1.0 - fill[3]));
666        assert!((a - 0.1507).abs() < 5e-5, "{a}");
667    }
668}