//! The UI's colours, either the brand palette or one derived from album art. //! //! A cover only contributes a hue and how colourful it is. Each role keeps the //! lightness it has in the brand palette, so text stays readable whatever the //! cover looks like. Colours are mixed in OKLab, where equal steps look equal. /// A colour in OKLab: lightness, then the green-red and blue-yellow axes. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Lab { pub l: f32, pub a: f32, pub b: f32, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Role { Bg, Panel, Raised, Line, Text, Muted, Faint, Accent, OnAccent, Highlight, Focus, Glow, LoginGlow, } impl Role { pub const ALL: [Role; 13] = [ Role::Bg, Role::Panel, Role::Raised, Role::Line, Role::Text, Role::Muted, Role::Faint, Role::Accent, Role::OnAccent, Role::Highlight, Role::Focus, Role::Glow, Role::LoginGlow, ]; /// The brand colour for this role. Must match the defaults of `Theme` in /// ui/app.slint, which is what the UI shows before any palette is applied. fn brand(self) -> u32 { match self { Role::Bg => 0x140b0c, Role::Panel => 0x1d1012, Role::Raised => 0x2b181b, Role::Line => 0x42272b, Role::Text | Role::OnAccent | Role::Focus => 0xfaebda, Role::Muted => 0xbea999, Role::Faint => 0x80685f, Role::Accent => 0xa51d2d, Role::Highlight => 0xe8757b, Role::Glow => 0x2a0b11, Role::LoginGlow => 0x3a0b13, } } /// Cream text and focus rings stay cream on every palette. fn follows_cover(self) -> bool { !matches!(self, Role::Text | Role::OnAccent | Role::Focus) } } /// What a cover contributes: its dominant hue in radians and its chroma. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Tone { pub hue: f32, pub chroma: f32, } /// The minimum contrast for text, WCAG AA for normal text. const MIN_CONTRAST: f32 = 4.5; #[derive(Clone, Copy, Debug, PartialEq)] pub struct Palette([Lab; Role::ALL.len()]); impl Palette { pub fn brand() -> Palette { Palette(Role::ALL.map(|r| Lab::from_rgb(r.brand()))) } /// The palette for a cover with this tone. pub fn from_tone(tone: Tone) -> Palette { let brand = Palette::brand(); // A dull cover gives a dull palette, a vivid one the brand's own vividness. let vividness = (tone.chroma / 0.12).clamp(0.5, 1.0); let mut roles = brand.0; for (i, role) in Role::ALL.into_iter().enumerate() { if !role.follows_cover() { continue; } let b = brand.0[i]; // Hue replaced outright: mixing towards the brand in OKLab would pass // through grey for a cover on the far side of the wheel from maroon. roles[i] = Lab::from_lch(b.l, b.chroma() * vividness, tone.hue).into_gamut(); } let mut p = Palette(roles); p.ensure_contrast(); p } pub fn get(&self, role: Role) -> Lab { self.0[role as usize] } /// The palette `t` of the way from `self` to `other`. pub fn mix(&self, other: &Palette, t: f32) -> Palette { // Exact at the ends, so a finished fade lands on the target itself. if t <= 0.0 { return *self; } if t >= 1.0 { return *other; } let mut out = self.0; for (o, (a, b)) in out.iter_mut().zip(self.0.iter().zip(other.0.iter())) { *o = a.mix(*b, t); } Palette(out) } /// Darkens the accent fill and lightens the highlight until cream text on /// the fill and the highlight on the background are both readable. fn ensure_contrast(&mut self) { let text = self.get(Role::OnAccent); let bg = self.get(Role::Bg); let accent = &mut self.0[Role::Accent as usize]; while contrast(*accent, text) < MIN_CONTRAST && accent.l > 0.2 { *accent = accent.with_lightness(accent.l - 0.01).into_gamut(); } let hl = &mut self.0[Role::Highlight as usize]; while contrast(*hl, bg) < MIN_CONTRAST && hl.l < 0.95 { *hl = hl.with_lightness(hl.l + 0.01).into_gamut(); } } } /// The dominant tone of an RGB image (3 bytes a pixel), or None when it has /// too little colour to base a palette on: greyscale, black and white, sepia /// that is nearly grey. pub fn tone(rgb: &[u8]) -> Option { const BINS: usize = 24; // Below this a pixel's hue is mostly compression noise. const CHROMATIC: f32 = 0.04; let mut weight = [0f32; BINS]; let mut sum_a = [0f32; BINS]; let mut sum_b = [0f32; BINS]; let mut sum_c2 = [0f32; BINS]; let (mut pixels, mut chromatic) = (0usize, 0usize); for px in rgb.as_chunks::<3>().0 { pixels += 1; let lab = Lab::from_rgb(u32::from_be_bytes([0, px[0], px[1], px[2]])); let c = lab.chroma(); // Near black and near white carry no usable hue either. if c < CHROMATIC || lab.l < 0.12 || lab.l > 0.97 { continue; } chromatic += 1; let hue = lab.b.atan2(lab.a).rem_euclid(std::f32::consts::TAU); let bin = ((hue / std::f32::consts::TAU) * BINS as f32) as usize % BINS; // Weighted by chroma, so a small vivid logo beats a large grey field. weight[bin] += c; sum_a[bin] += lab.a; sum_b[bin] += lab.b; sum_c2[bin] += c * c; } if pixels == 0 || chromatic * 50 < pixels { return None; } let around = |i: usize| [(i + BINS - 1) % BINS, i, (i + 1) % BINS]; let best = (0..BINS) .max_by(|&x, &y| { let wx: f32 = around(x).iter().map(|&j| weight[j]).sum(); let wy: f32 = around(y).iter().map(|&j| weight[j]).sum(); wx.total_cmp(&wy) }) .unwrap_or(0); let (mut a, mut b, mut w, mut c2) = (0f32, 0f32, 0f32, 0f32); for j in around(best) { a += sum_a[j]; b += sum_b[j]; w += weight[j]; c2 += sum_c2[j]; } Some(Tone { hue: b.atan2(a), chroma: c2 / w, }) } /// WCAG contrast ratio between two colours. pub fn contrast(x: Lab, y: Lab) -> f32 { let (lx, ly) = (x.luminance(), y.luminance()); (lx.max(ly) + 0.05) / (lx.min(ly) + 0.05) } impl Lab { pub fn from_rgb(rgb: u32) -> Lab { let [_, r, g, b] = rgb.to_be_bytes(); let (r, g, b) = (to_linear(r), to_linear(g), to_linear(b)); let l = (0.412_221_46 * r + 0.536_332_55 * g + 0.051_445_995 * b).cbrt(); let m = (0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b).cbrt(); let s = (0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b).cbrt(); Lab { l: 0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s, a: 1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s, b: 0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s, } } fn from_lch(l: f32, c: f32, hue: f32) -> Lab { Lab { l, a: c * hue.cos(), b: c * hue.sin(), } } fn linear(self) -> [f32; 3] { let l = (self.l + 0.396_337_78 * self.a + 0.215_803_76 * self.b).powi(3); let m = (self.l - 0.105_561_346 * self.a - 0.063_854_17 * self.b).powi(3); let s = (self.l - 0.089_484_18 * self.a - 1.291_485_5 * self.b).powi(3); [ 4.076_741_7 * l - 3.307_711_6 * m + 0.230_969_94 * s, -1.268_438 * l + 2.609_757_4 * m - 0.341_319_38 * s, -0.004_196_086_3 * l - 0.703_418_6 * m + 1.707_614_7 * s, ] } /// The sRGB colour as 8-bit channels, clipped to the displayable range. pub fn to_rgb(self) -> [u8; 3] { self.linear().map(from_linear) } pub fn chroma(self) -> f32 { self.a.hypot(self.b) } fn luminance(self) -> f32 { let [r, g, b] = self.to_rgb().map(to_linear); 0.2126 * r + 0.7152 * g + 0.0722 * b } fn mix(self, other: Lab, t: f32) -> Lab { Lab { l: self.l + (other.l - self.l) * t, a: self.a + (other.a - self.a) * t, b: self.b + (other.b - self.b) * t, } } fn with_lightness(self, l: f32) -> Lab { Lab { l, ..self } } fn in_gamut(self) -> bool { self.linear().iter().all(|&c| (-0.0005..=1.0005).contains(&c)) } /// Lowers the chroma, keeping lightness and hue, until sRGB can show it. fn into_gamut(self) -> Lab { if self.in_gamut() { return self; } let (mut lo, mut hi) = (0f32, 1f32); for _ in 0..20 { let mid = (lo + hi) / 2.0; let c = Lab { a: self.a * mid, b: self.b * mid, ..self }; if c.in_gamut() { lo = mid; } else { hi = mid; } } Lab { a: self.a * lo, b: self.b * lo, ..self } } } fn to_linear(c: u8) -> f32 { let c = c as f32 / 255.0; if c <= 0.040_45 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } } fn from_linear(c: f32) -> u8 { let c = c.clamp(0.0, 1.0); let s = if c <= 0.003_130_8 { c * 12.92 } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 }; (s * 255.0).round() as u8 } #[cfg(test)] mod tests { use super::*; use std::f32::consts::TAU; fn hex(rgb: [u8; 3]) -> u32 { u32::from_be_bytes([0, rgb[0], rgb[1], rgb[2]]) } /// A 24x24 image filled by `f(x, y)`. fn image(f: impl Fn(usize, usize) -> [u8; 3]) -> Vec { (0..24 * 24).flat_map(|i| f(i % 24, i / 24)).collect() } fn hue_distance(a: f32, b: f32) -> f32 { let d = (a - b).rem_euclid(TAU); d.min(TAU - d) } #[test] fn brand_palette_round_trips_exactly() { let p = Palette::brand(); for role in Role::ALL { assert_eq!(hex(p.get(role).to_rgb()), role.brand(), "{role:?}"); } } #[test] fn contrast_holds_for_every_hue_and_chroma() { for step in 0..72 { for chroma in [0.02, 0.06, 0.12, 0.25, 0.4] { let tone = Tone { hue: step as f32 * TAU / 72.0, chroma, }; let p = Palette::from_tone(tone); let cases = [ (Role::Text, Role::Bg), (Role::Text, Role::Panel), (Role::Text, Role::Raised), (Role::OnAccent, Role::Accent), (Role::Highlight, Role::Bg), (Role::Muted, Role::Bg), ]; for (fg, bg) in cases { let c = contrast(p.get(fg), p.get(bg)); assert!(c >= MIN_CONTRAST, "{fg:?} on {bg:?} is {c:.2} for {tone:?}"); } } } } #[test] fn cover_palette_keeps_cream_text() { let p = Palette::from_tone(Tone { hue: 4.0, chroma: 0.2 }); for role in [Role::Text, Role::OnAccent, Role::Focus] { assert_eq!(p.get(role), Palette::brand().get(role)); } } #[test] fn cover_palette_takes_the_cover_hue() { let blue = Lab::from_rgb(0x2050d0); let tone = Tone { hue: blue.b.atan2(blue.a), chroma: blue.chroma(), }; let accent = Palette::from_tone(tone).get(Role::Accent); let brand = Palette::brand().get(Role::Accent); let hue = |l: Lab| l.b.atan2(l.a); assert!(hue_distance(hue(accent), tone.hue) < hue_distance(hue(brand), tone.hue)); assert!(hue_distance(hue(accent), tone.hue) < 0.6); } #[test] fn cover_opposite_the_brand_hue_stays_colourful() { let cyan = Lab::from_rgb(0x30b8d8); let tone = Tone { hue: cyan.b.atan2(cyan.a), chroma: cyan.chroma(), }; let accent = Palette::from_tone(tone).get(Role::Accent); assert!(accent.chroma() > 0.08, "accent went grey: {accent:?}"); } #[test] fn saturated_cover_gives_its_hue() { let t = tone(&image(|_, _| [200, 30, 40])).expect("red has a tone"); let red = Lab::from_rgb(0xc81e28); assert!(hue_distance(t.hue, red.b.atan2(red.a)) < 0.15); assert!(t.chroma > 0.15); } #[test] fn dark_and_light_covers_still_give_a_tone() { assert!(tone(&image(|_, _| [40, 20, 70])).is_some()); assert!(tone(&image(|_, _| [240, 220, 160])).is_some()); } #[test] fn greyscale_cover_has_no_tone() { let grey = image(|x, y| { let v = ((x * 7 + y * 3) % 256) as u8; [v, v, v] }); assert_eq!(tone(&grey), None); assert_eq!(tone(&image(|x, _| if x < 12 { [0; 3] } else { [255; 3] })), None); assert_eq!(tone(&[]), None); } #[test] fn small_vivid_area_beats_a_grey_field() { let img = image(|x, y| if x < 5 && y < 5 { [220, 40, 40] } else { [128, 128, 128] }); let t = tone(&img).expect("the red patch is enough"); let red = Lab::from_rgb(0xdc2828); assert!(hue_distance(t.hue, red.b.atan2(red.a)) < 0.15); } #[test] fn dominant_hue_wins_over_a_minority() { let img = image(|x, _| if x < 18 { [30, 60, 200] } else { [220, 40, 40] }); let t = tone(&img).unwrap(); let blue = Lab::from_rgb(0x1e3cc8); assert!(hue_distance(t.hue, blue.b.atan2(blue.a)) < 0.15); } #[test] fn mixing_palettes_hits_both_ends() { let a = Palette::brand(); let b = Palette::from_tone(Tone { hue: 2.5, chroma: 0.15 }); assert_eq!(a.mix(&b, 0.0), a); assert_eq!(a.mix(&b, 1.0), b); let mid = a.mix(&b, 0.5).get(Role::Accent); let (x, y) = (a.get(Role::Accent), b.get(Role::Accent)); assert!((mid.l - (x.l + y.l) / 2.0).abs() < 1e-6); } }