Skip to main content

egui_pop_tokens/
color.rs

1//! Colours: sRGB with straight alpha, read from DTCG colour values, and the
2//! WCAG 2.x contrast ratio.
3
4use std::fmt;
5
6/// An sRGB colour with straight (not premultiplied) alpha, each channel
7/// from 0 to 1.
8#[derive(Clone, Copy, Debug, PartialEq)]
9pub struct Color {
10    pub r: f32,
11    pub g: f32,
12    pub b: f32,
13    pub a: f32,
14}
15
16impl Color {
17    pub const BLACK: Color = Color::rgb(0.0, 0.0, 0.0);
18    pub const WHITE: Color = Color::rgb(1.0, 1.0, 1.0);
19    /// What a missing colour shows as: loud on purpose.
20    pub const MISSING: Color = Color::rgb(1.0, 0.0, 1.0);
21
22    /// An opaque colour.
23    pub const fn rgb(r: f32, g: f32, b: f32) -> Color {
24        Color { r, g, b, a: 1.0 }
25    }
26
27    /// Reads `#rgb`, `#rrggbb` or `#rrggbbaa`.
28    pub fn from_hex(text: &str) -> Option<Color> {
29        let h = text.strip_prefix('#')?;
30        if !h.is_ascii() {
31            return None;
32        }
33        let byte = |i: usize| {
34            u8::from_str_radix(h.get(i..i + 2)?, 16)
35                .ok()
36                .map(|b| f32::from(b) / 255.0)
37        };
38        let nibble = |i: usize| {
39            u8::from_str_radix(h.get(i..=i)?, 16)
40                .ok()
41                .map(|b| f32::from(b * 17) / 255.0)
42        };
43        match h.len() {
44            3 => Some(Color::rgb(nibble(0)?, nibble(1)?, nibble(2)?)),
45            6 => Some(Color::rgb(byte(0)?, byte(2)?, byte(4)?)),
46            8 => Some(Color {
47                a: byte(6)?,
48                ..Color::rgb(byte(0)?, byte(2)?, byte(4)?)
49            }),
50            _ => None,
51        }
52    }
53
54    /// From OKLCH: lightness 0 to 1, chroma, hue in degrees. Out-of-gamut
55    /// colours are clipped to sRGB.
56    pub fn from_oklch(l: f32, c: f32, h: f32, alpha: f32) -> Color {
57        let (hs, hc) = f64::from(h).to_radians().sin_cos();
58        let c = f64::from(c);
59        Color::from_oklab(f64::from(l), c * hc, c * hs, alpha)
60    }
61
62    /// From OKLab: lightness 0 to 1, a and b axes.
63    pub fn from_oklab(l: f64, a: f64, b: f64, alpha: f32) -> Color {
64        let l_ = l + 0.396_337_777_4 * a + 0.215_803_757_3 * b;
65        let m_ = l - 0.105_561_345_8 * a - 0.063_854_172_8 * b;
66        let s_ = l - 0.089_484_177_5 * a - 1.291_485_548_0 * b;
67        let (l3, m3, s3) = (l_.powi(3), m_.powi(3), s_.powi(3));
68        let r = 4.076_741_662_1 * l3 - 3.307_711_591_3 * m3 + 0.230_969_929_2 * s3;
69        let g = -1.268_438_004_6 * l3 + 2.609_757_401_1 * m3 - 0.341_319_396_5 * s3;
70        let bl = -0.004_196_086_3 * l3 - 0.703_418_614_7 * m3 + 1.707_614_701_0 * s3;
71        Color {
72            r: encode(r),
73            g: encode(g),
74            b: encode(bl),
75            a: alpha,
76        }
77    }
78
79    /// From linear-light sRGB channels.
80    pub fn from_linear(r: f32, g: f32, b: f32, alpha: f32) -> Color {
81        Color {
82            r: encode(f64::from(r)),
83            g: encode(f64::from(g)),
84            b: encode(f64::from(b)),
85            a: alpha,
86        }
87    }
88
89    /// The linear-light sRGB channels, `[r, g, b]`, alpha ignored.
90    pub fn to_linear(self) -> [f64; 3] {
91        [decode(self.r), decode(self.g), decode(self.b)]
92    }
93
94    /// In OKLab, `[l, a, b]`: lightness 0 to 1 and the two colour axes;
95    /// alpha ignored. The inverse of [`Color::from_oklab`].
96    pub fn to_oklab(self) -> [f64; 3] {
97        let [r, g, b] = self.to_linear();
98        linear_to_oklab(r, g, b)
99    }
100
101    /// The channels as bytes, `[r, g, b, a]`, straight alpha.
102    pub fn to_srgba_u8(self) -> [u8; 4] {
103        let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
104        [b(self.r), b(self.g), b(self.b), b(self.a)]
105    }
106
107    /// `#rrggbb`, or `#rrggbbaa` when not opaque.
108    pub fn to_hex(self) -> String {
109        let [r, g, b, a] = self.to_srgba_u8();
110        if a == 255 {
111            format!("#{r:02x}{g:02x}{b:02x}")
112        } else {
113            format!("#{r:02x}{g:02x}{b:02x}{a:02x}")
114        }
115    }
116
117    /// This colour painted over `background`, which is taken as opaque.
118    pub fn over(self, background: Color) -> Color {
119        let a = self.a.clamp(0.0, 1.0);
120        let mix = |f: f32, b: f32| f * a + b * (1.0 - a);
121        Color::rgb(
122            mix(self.r, background.r),
123            mix(self.g, background.g),
124            mix(self.b, background.b),
125        )
126    }
127
128    /// WCAG 2.x relative luminance of the colour, alpha ignored.
129    pub fn relative_luminance(self) -> f32 {
130        let [r, g, b] = self.to_linear();
131        (0.2126 * r + 0.7152 * g + 0.0722 * b) as f32
132    }
133
134    /// Whether the colour reads as dark (relative luminance under that of
135    /// a middle grey).
136    pub fn is_dark(self) -> bool {
137        self.relative_luminance() < 0.18
138    }
139}
140
141impl fmt::Display for Color {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        f.write_str(&self.to_hex())
144    }
145}
146
147/// An sRGB channel to linear light, clipped to 0..1 first.
148fn decode(c: f32) -> f64 {
149    let c = f64::from(c.clamp(0.0, 1.0));
150    if c <= 0.040_45 {
151        c / 12.92
152    } else {
153        ((c + 0.055) / 1.055).powf(2.4)
154    }
155}
156
157/// Linear-light sRGB to OKLab (Björn Ottosson's matrices).
158pub(crate) fn linear_to_oklab(r: f64, g: f64, b: f64) -> [f64; 3] {
159    let l = 0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b;
160    let m = 0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b;
161    let s = 0.088_302_461_9 * r + 0.281_718_837_6 * g + 0.629_978_700_5 * b;
162    let (l, m, s) = (l.cbrt(), m.cbrt(), s.cbrt());
163    [
164        0.210_454_255_3 * l + 0.793_617_785_0 * m - 0.004_072_046_8 * s,
165        1.977_998_495_1 * l - 2.428_592_205_0 * m + 0.450_593_709_9 * s,
166        0.025_904_037_1 * l + 0.782_771_766_2 * m - 0.808_675_766_0 * s,
167    ]
168}
169
170/// Linear light to the sRGB transfer curve, clipped to 0..1.
171fn encode(x: f64) -> f32 {
172    let x = x.clamp(0.0, 1.0);
173    let v = if x <= 0.003_130_8 {
174        12.92 * x
175    } else {
176        1.055 * x.powf(1.0 / 2.4) - 0.055
177    };
178    v as f32
179}
180
181/// The WCAG 2.x contrast ratio of a foreground over a background, from 1
182/// to 21. A translucent foreground is first painted over the background;
183/// the background is taken as opaque.
184pub fn contrast_ratio(foreground: Color, background: Color) -> f32 {
185    let background = Color {
186        a: 1.0,
187        ..background
188    };
189    let fg = foreground.over(background).relative_luminance();
190    let bg = background.relative_luminance();
191    let (hi, lo) = if fg > bg { (fg, bg) } else { (bg, fg) };
192    (hi + 0.05) / (lo + 0.05)
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    #[test]
200    fn hex_round_trips() {
201        for text in ["#000000", "#f0c060", "#12345678"] {
202            assert_eq!(Color::from_hex(text).unwrap().to_hex(), text);
203        }
204        assert_eq!(Color::from_hex("#fff"), Some(Color::WHITE));
205        assert_eq!(Color::from_hex("f0c060"), None);
206        assert_eq!(Color::from_hex("#f0c06"), None);
207        assert_eq!(Color::from_hex("#gg0000"), None);
208    }
209
210    #[test]
211    fn contrast_matches_wcag_reference_values() {
212        assert!((contrast_ratio(Color::BLACK, Color::WHITE) - 21.0).abs() < 1e-3);
213        assert!((contrast_ratio(Color::WHITE, Color::WHITE) - 1.0).abs() < 1e-6);
214        // #767676 on white is the classic 4.54:1.
215        let grey = Color::from_hex("#767676").unwrap();
216        assert!((contrast_ratio(grey, Color::WHITE) - 4.54).abs() < 0.01);
217        // Symmetric.
218        assert_eq!(
219            contrast_ratio(grey, Color::BLACK),
220            contrast_ratio(Color::BLACK, grey)
221        );
222    }
223
224    #[test]
225    fn translucent_foregrounds_are_composited_first() {
226        let half_white = Color {
227            a: 0.5,
228            ..Color::WHITE
229        };
230        let r = contrast_ratio(half_white, Color::BLACK);
231        assert!(r > 1.0 && r < 21.0 / 2.0, "{r}");
232    }
233
234    #[test]
235    fn oklch_converts_to_srgb() {
236        assert_eq!(Color::from_oklch(1.0, 0.0, 0.0, 1.0).to_hex(), "#ffffff");
237        assert_eq!(Color::from_oklch(0.0, 0.0, 0.0, 1.0).to_hex(), "#000000");
238        // The gold accent of pop-dark, written in OKLCH in its theme file.
239        assert_eq!(
240            Color::from_oklch(0.832, 0.126, 83.0, 1.0).to_hex(),
241            "#f0c060"
242        );
243    }
244}