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