Medlar/crates/app/src/theme.rs
2026-11-25 07:46:35 -06:00

424 lines
17 KiB
Rust

//! Material You colour roles, built from a seed in OKLCH space (tone == CIE L*).
//!
//! Every text role reaches the contrast level's ratio on every surface it may sit on: `fit` moves its tone until it does.
use crate::desktop::Desktop;
use crate::tokens;
use eframe::egui::{self, Color32, Stroke};
use medlar_core::settings::{Appearance, Contrast, Motion, Scheme, Settings};
fn srgb_to_lin(c: f64) -> f64 {
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
}
fn lin_to_srgb(c: f64) -> f64 {
if c <= 0.0031308 { 12.92 * c } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 }
}
fn lin(c: Color32) -> [f64; 3] {
[c.r(), c.g(), c.b()].map(|x| srgb_to_lin(x as f64 / 255.0))
}
fn oklch_of(c: Color32) -> (f64, f64, f64) {
let [r, g, b] = lin(c);
let l = (0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b).cbrt();
let m = (0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b).cbrt();
let s = (0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b).cbrt();
let ll = 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s;
let a = 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s;
let bb = 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s;
(ll, a.hypot(bb), bb.atan2(a).to_degrees().rem_euclid(360.0))
}
/// 0 black, 1 white, as the eye sees it.
pub fn lightness(c: Color32) -> f64 {
oklch_of(c).0
}
fn oklch_to_lin(l: f64, c: f64, h: f64) -> [f64; 3] {
let (a, b) = (c * h.to_radians().cos(), c * h.to_radians().sin());
let l_ = (l + 0.3963377774 * a + 0.2158037573 * b).powi(3);
let m_ = (l - 0.1055613458 * a - 0.0638541728 * b).powi(3);
let s_ = (l - 0.0894841775 * a - 1.2914855480 * b).powi(3);
[
4.0767416621 * l_ - 3.3077115913 * m_ + 0.2309699292 * s_,
-1.2684380046 * l_ + 2.6097574011 * m_ - 0.3413193965 * s_,
-0.0041960863 * l_ - 0.7034186147 * m_ + 1.7076147010 * s_,
]
}
/// The colour, with less chroma where the screen can't show it.
fn oklch(l: f64, c: f64, h: f64) -> Color32 {
let in_gamut = |rgb: [f64; 3]| rgb.iter().all(|v| (-1e-4..=1.0001).contains(v));
let mut rgb = oklch_to_lin(l, c, h);
if !in_gamut(rgb) {
let (mut lo, mut hi) = (0.0, c);
for _ in 0..18 {
let mid = (lo + hi) / 2.0;
if in_gamut(oklch_to_lin(l, mid, h)) { lo = mid } else { hi = mid }
}
rgb = oklch_to_lin(l, lo, h);
}
let [r, g, b] = rgb.map(|x| (lin_to_srgb(x.clamp(0.0, 1.0)) * 255.0).round() as u8);
Color32::from_rgb(r, g, b)
}
/// Hue in degrees and colourfulness of a seed.
pub fn hue_of(c: Color32) -> (f64, f64) {
let (_, chroma, hue) = oklch_of(c);
(hue, chroma)
}
/// A seed of this hue and colourfulness.
pub fn seed(hue: f64, chroma: f64) -> Color32 {
oklch(0.62, chroma, hue)
}
fn luminance(c: Color32) -> f64 {
let [r, g, b] = lin(c);
0.2126 * r + 0.7152 * g + 0.0722 * b
}
/// WCAG contrast ratio, 1 to 21.
pub fn contrast(a: Color32, b: Color32) -> f64 {
let (x, y) = (luminance(a), luminance(b));
(x.max(y) + 0.05) / (x.min(y) + 0.05)
}
pub fn mix(a: Color32, b: Color32, t: f32) -> Color32 {
let t = t.clamp(0.0, 1.0);
let l = |x: u8, y: u8| (x as f32 + (y as f32 - x as f32) * t).round() as u8;
Color32::from_rgba_premultiplied(l(a.r(), b.r()), l(a.g(), b.g()), l(a.b(), b.b()), l(a.a(), b.a()))
}
pub fn alpha(c: Color32, a: f32) -> Color32 {
c.gamma_multiply(a.clamp(0.0, 1.0))
}
/// `#rrggbb` or `rrggbb`.
pub fn hex(s: &str) -> Option<Color32> {
let s = s.trim().trim_start_matches('#');
if s.len() != 6 || !s.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let v = u32::from_str_radix(s, 16).ok()?;
Some(Color32::from_rgb((v >> 16) as u8, (v >> 8) as u8, v as u8))
}
#[derive(Clone, Copy)]
struct Tonal {
h: f64,
c: f64,
}
impl Tonal {
fn at(self, tone: f64) -> Color32 {
let l = if tone <= 8.0 { (tone / 903.2963).cbrt() } else { (tone + 16.0) / 116.0 };
oklch(l, self.c, self.h)
}
/// `tone`, or the nearest one further from the backgrounds that reaches `ratio` on all of them.
fn fit(self, tone: f64, dark_ground: bool, grounds: &[Color32], ratio: f64) -> Color32 {
let step = if dark_ground { 1.0 } else { -1.0 };
let mut t = tone;
loop {
let c = self.at(t);
if grounds.iter().all(|g| contrast(c, *g) >= ratio) || !(0.0..=100.0).contains(&(t + step)) {
return c;
}
t += step;
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Theme {
pub dark: bool,
pub primary: Color32,
pub on_primary: Color32,
pub primary_container: Color32,
pub on_primary_container: Color32,
pub secondary: Color32,
pub on_secondary: Color32,
pub secondary_container: Color32,
pub on_secondary_container: Color32,
pub tertiary: Color32,
pub on_tertiary: Color32,
pub tertiary_container: Color32,
pub on_tertiary_container: Color32,
pub error: Color32,
pub on_error: Color32,
pub error_container: Color32,
pub on_error_container: Color32,
/// Finished and checked.
pub success: Color32,
/// Slowed down, or needs a look.
pub warning: Color32,
pub surface: Color32,
pub lowest: Color32,
pub low: Color32,
pub container: Color32,
pub high: Color32,
pub highest: Color32,
pub on_surface: Color32,
/// Second lines, hints and icons at rest.
pub on_variant: Color32,
/// Borders that must be seen.
pub outline: Color32,
/// Hairlines between things.
pub outline_variant: Color32,
/// Toasts.
pub inverse_surface: Color32,
pub inverse_on_surface: Color32,
pub inverse_primary: Color32,
}
impl Theme {
/// D-012: the desktop's colour or the user's own; undecided means the desktop's when it has one.
pub fn build(s: &Settings, desktop: Desktop) -> Theme {
let own = hex(&s.own_color).or_else(|| hex(&Settings::default().own_color)).expect("the default colour is valid");
let seed = desktop.seed.filter(|_| s.desktop_colors != Some(false)).unwrap_or(own);
let dark = match s.appearance {
Appearance::Auto => desktop.dark.unwrap_or(true),
Appearance::Light => false,
Appearance::Dark | Appearance::Amoled => true,
};
Theme::from_seed(seed, dark, s.appearance == Appearance::Amoled, s.scheme, s.contrast)
}
pub fn from_seed(seed: Color32, dark: bool, amoled: bool, scheme: Scheme, level: Contrast) -> Theme {
let (_, sc, h) = oklch_of(seed);
// A grey seed has no hue worth boosting.
let scheme = if sc < 0.02 { Scheme::Mono } else { scheme };
let (pc, sec_c, ter_c, ter_shift, neutral_c) = match scheme {
Scheme::Tonal => (sc.clamp(0.085, 0.15), 0.04, 0.075, 60.0, 0.014),
Scheme::Vibrant => (sc.clamp(0.13, 0.19), 0.08, 0.11, 45.0, 0.022),
Scheme::Expressive => (sc.clamp(0.10, 0.16), 0.07, 0.12, 130.0, 0.026),
Scheme::Mono => (0.012, 0.008, 0.012, 0.0, 0.004),
};
let p = Tonal { h, c: pc };
let sec = Tonal { h, c: sec_c };
let ter = Tonal { h: (h + ter_shift) % 360.0, c: ter_c };
let err = Tonal { h: 25.0, c: 0.17 };
let good = Tonal { h: 150.0, c: 0.13 };
let warn = Tonal { h: 75.0, c: 0.13 };
let n = Tonal { h, c: neutral_c };
let nv = Tonal { h, c: (neutral_c * 1.8).max(if scheme == Scheme::Mono { 0.004 } else { 0.016 }) };
// Lowest ratio of text, and of borders and icons.
let (text, line) = match level {
Contrast::Standard => (4.5, 3.0),
Contrast::Medium => (7.0, 4.5),
Contrast::High => (10.0, 7.0),
};
let hairline = if level == Contrast::High { 3.0 } else { 1.0 };
let d = |dk: f64, lt: f64| if dark { dk } else { lt };
let surfaces = match (dark, amoled) {
(true, true) => [0.0, 0.0, 5.0, 8.0, 12.0, 17.0],
(true, false) => [6.0, 4.0, 10.0, 12.0, 17.0, 22.0],
(false, _) => [98.0, 100.0, 96.0, 94.0, 92.0, 90.0],
}
.map(|t| n.at(t));
let [surface, lowest, low, container, high, highest] = surfaces;
let on = |t: Tonal, dk: f64, lt: f64, ratio: f64| t.fit(d(dk, lt), dark, &surfaces, ratio);
let accent = |t: Tonal| {
let c = on(t, 80.0, 40.0, text);
(c, t.fit(d(20.0, 100.0), !dark, &[c], text))
};
let (primary, on_primary) = accent(p);
let (secondary, on_secondary) = accent(sec);
let (tertiary, on_tertiary) = accent(ter);
let (error, on_error) = accent(err);
let boxed = |t: Tonal| {
let c = t.at(d(30.0, 90.0));
(c, t.fit(d(90.0, 10.0), dark, &[c], text))
};
let (primary_container, on_primary_container) = boxed(p);
let (secondary_container, on_secondary_container) = boxed(sec);
let (tertiary_container, on_tertiary_container) = boxed(ter);
let (error_container, on_error_container) = boxed(err);
let inverse_surface = n.at(d(90.0, 20.0));
Theme {
dark,
primary,
on_primary,
primary_container,
on_primary_container,
secondary,
on_secondary,
secondary_container,
on_secondary_container,
tertiary,
on_tertiary,
tertiary_container,
on_tertiary_container,
error,
on_error,
error_container,
on_error_container,
success: on(good, 80.0, 40.0, text),
warning: on(warn, 80.0, 40.0, text),
surface,
lowest,
low,
container,
high,
highest,
on_surface: on(n, 90.0, 10.0, text),
on_variant: on(nv, 80.0, 30.0, text),
outline: on(nv, 60.0, 50.0, line),
outline_variant: on(nv, 30.0, 80.0, hairline),
inverse_surface,
inverse_on_surface: n.fit(d(20.0, 95.0), !dark, &[inverse_surface], text),
inverse_primary: p.fit(d(40.0, 80.0), !dark, &[inverse_surface], text),
}
}
/// Makes egui's own widgets (text fields, menus, tooltips) follow the theme.
pub fn apply(&self, ctx: &egui::Context, motion: Motion) {
ctx.set_theme(if self.dark { egui::Theme::Dark } else { egui::Theme::Light });
ctx.global_style_mut(|s| {
let v = &mut s.visuals;
*v = if self.dark { egui::Visuals::dark() } else { egui::Visuals::light() };
v.override_text_color = Some(self.on_surface);
v.weak_text_color = Some(self.on_variant);
v.panel_fill = self.surface;
v.window_fill = self.container;
v.window_stroke = Stroke::NONE;
v.window_corner_radius = tokens::radius::XL.into();
v.menu_corner_radius = tokens::radius::M.into();
v.window_shadow = tokens::elevation::floating(self.dark);
v.popup_shadow = v.window_shadow;
v.extreme_bg_color = self.lowest;
v.faint_bg_color = self.low;
v.code_bg_color = self.high;
v.hyperlink_color = self.primary;
v.error_fg_color = self.error;
v.warn_fg_color = self.warning;
v.selection.bg_fill = self.primary_container;
v.selection.stroke = Stroke::new(1.0, self.on_primary_container);
v.text_cursor.stroke = Stroke::new(2.0, self.primary);
// A blinking cursor draws frames for as long as a field has focus.
v.text_cursor.blink = !matches!(motion, Motion::Off | Motion::Reduced);
let w = &mut v.widgets;
for (state, fill, line) in [
(&mut w.noninteractive, self.surface, self.outline_variant),
(&mut w.inactive, self.high, self.outline),
(&mut w.hovered, self.highest, self.on_variant),
(&mut w.active, self.highest, self.primary),
(&mut w.open, self.high, self.outline),
] {
state.bg_fill = fill;
state.weak_bg_fill = fill;
state.bg_stroke = Stroke::new(tokens::size::HAIRLINE, line);
state.fg_stroke = Stroke::new(1.5, self.on_surface);
state.corner_radius = tokens::radius::S.into();
state.expansion = 0.0;
}
s.animation_time = if motion == Motion::Off { 0.0 } else { 0.12 };
s.spacing.item_spacing = [tokens::space::S; 2].into();
s.spacing.interact_size.y = tokens::size::HIT;
});
}
}
#[cfg(test)]
mod tests {
use super::*;
const SEEDS: [&str; 12] = [
"#b5622b", "#7f5fc4", "#d0485e", "#3f9c6b", "#c8a020", "#2b7fd4", "#f5b2e1", "#00ffff", "#ffff00", "#0000ff", "#000000",
"#808080",
];
fn every_theme(mut check: impl FnMut(&Theme, Contrast, &str)) {
for seed in SEEDS {
for (dark, amoled) in [(false, false), (true, false), (true, true)] {
for scheme in [Scheme::Tonal, Scheme::Vibrant, Scheme::Expressive, Scheme::Mono] {
for level in [Contrast::Standard, Contrast::Medium, Contrast::High] {
let t = Theme::from_seed(hex(seed).unwrap(), dark, amoled, scheme, level);
check(&t, level, &format!("{seed} dark={dark} amoled={amoled} {scheme:?} {level:?}"));
}
}
}
}
}
#[test]
fn text_and_icons_are_readable_in_every_mode() {
every_theme(|t, level, name| {
let (text, icon) = match level {
Contrast::Standard => (4.5, 3.0),
Contrast::Medium => (7.0, 4.5),
Contrast::High => (10.0, 7.0),
};
let surfaces = [t.surface, t.lowest, t.low, t.container, t.high, t.highest];
for (role, c, least) in [
("on_surface", t.on_surface, text),
("on_variant", t.on_variant, text),
("primary", t.primary, text),
("secondary", t.secondary, text),
("tertiary", t.tertiary, text),
("error", t.error, text),
("success", t.success, text),
("warning", t.warning, text),
("outline", t.outline, icon),
] {
for (i, ground) in surfaces.iter().enumerate() {
let c = contrast(c, *ground);
assert!(c >= least, "{name}: {role} on surface {i} is {c:.2}");
}
}
for (role, c, ground) in [
("on_primary", t.on_primary, t.primary),
("on_secondary", t.on_secondary, t.secondary),
("on_tertiary", t.on_tertiary, t.tertiary),
("on_error", t.on_error, t.error),
("on_primary_container", t.on_primary_container, t.primary_container),
("on_secondary_container", t.on_secondary_container, t.secondary_container),
("on_tertiary_container", t.on_tertiary_container, t.tertiary_container),
("on_error_container", t.on_error_container, t.error_container),
("inverse_on_surface", t.inverse_on_surface, t.inverse_surface),
("inverse_primary", t.inverse_primary, t.inverse_surface),
] {
let c = contrast(c, ground);
// What stands on a colour reaches at least 7, even at the high level.
assert!(c >= text.min(7.0), "{name}: {role} is {c:.2}");
}
});
}
#[test]
fn surfaces_step_the_right_way_and_amoled_is_black() {
every_theme(|t, _, name| {
let steps = [t.surface, t.low, t.container, t.high, t.highest].map(luminance);
let ok = if t.dark { steps.is_sorted() } else { steps.iter().rev().is_sorted() };
assert!(ok, "{name}");
});
let t = Theme::from_seed(hex("#b5622b").unwrap(), true, true, Scheme::Tonal, Contrast::Standard);
assert_eq!(t.surface, Color32::BLACK);
}
#[test]
fn desktop_or_own_colour() {
let pink = Desktop { seed: hex("#f5b2e1"), dark: Some(false) };
let mut s = Settings { own_color: "#2b7fd4".into(), ..Settings::default() };
let of = |seed: &str, dark| Theme::from_seed(hex(seed).unwrap(), dark, false, Scheme::Tonal, Contrast::Standard);
assert_eq!(Theme::build(&s, pink), of("#f5b2e1", false), "undecided follows the desktop");
assert_eq!(Theme::build(&s, Desktop::default()), of("#2b7fd4", true), "undecided without a desktop colour");
s.desktop_colors = Some(false);
assert_eq!(Theme::build(&s, pink), of("#2b7fd4", false), "own colour, the desktop's light mode");
s.appearance = Appearance::Dark;
assert_eq!(Theme::build(&s, pink), of("#2b7fd4", true));
s.own_color = "nonsense".into();
assert_eq!(Theme::build(&s, pink), of(&Settings::default().own_color, true));
}
#[test]
fn hex_takes_only_colours() {
assert_eq!(hex(" #0a0B0c "), Some(Color32::from_rgb(10, 11, 12)));
for bad in ["", "#fff", "#gggggg", "+12345", "ééé"] {
assert_eq!(hex(bad), None, "{bad}");
}
}
}