Mulberry/src/theme.rs
astar76 4fef60ba23 Rewrite Mulberry in Rust (egui + libmpv)
Port of the Python/PyQt6 app: same library database, playlists, hero panel,
lyrics, tag editor, MusicBrainz/cover tools, CD ripping, MPRIS and tray.

New: right-click 'Set <tag> to "value"' writes the clicked cell's tag into every
selected file (with undo). The seek bar now runs off a monotonic position clock
so it can't jump back and forth.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-24 14:46:05 -05:00

353 lines
12 KiB
Rust

//! Material You colour scheme generated from the system colours.
//!
//! Reads ~/.config/kdeglobals (accent, window background) when present, builds tonal
//! palettes in OKLCH space (tone == CIE L*) and produces the Material 3 colour roles.
use crate::config::settings;
use eframe::egui::Color32;
use std::path::PathBuf;
// ------------------------------------------------------------------ colour math
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
}
}
pub fn rgb_to_oklch(r: u8, g: u8, b: u8) -> (f64, f64, f64) {
let (r, g, b) = (srgb_to_lin(r as f64 / 255.0), srgb_to_lin(g as f64 / 255.0), srgb_to_lin(b as f64 / 255.0));
let l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;
let m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
let s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;
let (l, m, s) = (l.cbrt(), m.cbrt(), s.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))
}
fn oklch_to_lin(l: f64, c: f64, h: f64) -> (f64, f64, f64) {
let a = c * h.to_radians().cos();
let b = 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_,
)
}
fn in_gamut(rgb: (f64, f64, f64)) -> bool {
[rgb.0, rgb.1, rgb.2].iter().all(|x| (-1e-4..=1.0001).contains(x))
}
/// Convert with gamut mapping (reduce chroma until it fits sRGB).
pub fn oklch_to_color(l: f64, c: f64, h: f64) -> Color32 {
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 q = |x: f64| (lin_to_srgb(x.clamp(0.0, 1.0)) * 255.0).round().clamp(0.0, 255.0) as u8;
Color32::from_rgb(q(rgb.0), q(rgb.1), q(rgb.2))
}
fn tone_to_l(t: f64) -> f64 {
if t <= 8.0 {
(t / 903.2963).cbrt()
} else {
(t + 16.0) / 116.0
}
}
fn l_to_tone(l: f64) -> f64 {
let y = l.powi(3);
if y <= 0.008856 {
903.2963 * y
} else {
116.0 * l - 16.0
}
}
#[derive(Clone, Copy)]
struct Tonal {
h: f64,
c: f64,
}
impl Tonal {
fn at(&self, tone: f64) -> Color32 {
oklch_to_color(tone_to_l(tone), self.c, self.h)
}
}
pub fn mix(a: Color32, b: Color32, t: f32) -> Color32 {
let l = |x: u8, y: u8| (x as f32 + (y as f32 - x as f32) * t).round().clamp(0.0, 255.0) as u8;
Color32::from_rgba_unmultiplied(l(a.r(), b.r()), l(a.g(), b.g()), l(a.b(), b.b()), l(a.a(), b.a()))
}
/// The same colour with its alpha replaced (straight alpha, 0..1).
pub fn with_alpha(c: Color32, a: f32) -> Color32 {
Color32::from_rgba_unmultiplied(c.r(), c.g(), c.b(), (a.clamp(0.0, 1.0) * 255.0).round() as u8)
}
/// Multiply the existing alpha.
pub fn fade(c: Color32, a: f32) -> Color32 {
with_alpha(c, a * c.a() as f32 / 255.0)
}
pub fn hex(s: &str) -> Option<Color32> {
let s = s.trim().trim_start_matches('#');
if s.len() != 6 {
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))
}
pub fn lightness(c: Color32) -> f32 {
let (r, g, b) = (c.r() as f32 / 255.0, c.g() as f32 / 255.0, c.b() as f32 / 255.0);
(r.max(g).max(b) + r.min(g).min(b)) / 2.0
}
/// Pick a vivid representative colour from artwork (Material "score" style).
pub fn dominant_color(img: &image::RgbaImage) -> Option<Color32> {
let small = image::imageops::resize(img, 48, 48, image::imageops::FilterType::Triangle);
let mut buckets = [[0.0f64; 4]; 24];
let mut any = false;
for p in small.pixels() {
let (l, c, h) = rgb_to_oklch(p[0], p[1], p[2]);
if c < 0.03 || l < 0.2 || l > 0.95 {
continue;
}
any = true;
let b = &mut buckets[((h / 15.0) as usize).min(23)];
let w = c * c;
b[0] += w;
b[1] += h.to_radians().cos() * w;
b[2] += h.to_radians().sin() * w;
b[3] += c * w;
}
if !any {
return None;
}
let best = buckets.iter().max_by(|a, b| a[0].partial_cmp(&b[0]).unwrap())?;
let hue = best[2].atan2(best[1]).to_degrees().rem_euclid(360.0);
let chroma = best[3] / best[0];
Some(oklch_to_color(0.65, chroma.max(0.1), hue))
}
// ------------------------------------------------------------------ system colours
#[derive(Default, Clone)]
pub struct SystemColors {
pub accent: Option<Color32>,
pub window_bg: Option<Color32>,
}
fn kdeglobals_path() -> PathBuf {
let base = std::env::var_os("XDG_CONFIG_HOME")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| crate::config::home().join(".config"));
base.join("kdeglobals")
}
fn parse_rgb(s: &str) -> Option<Color32> {
let p: Vec<u8> = s.split(',').take(3).filter_map(|x| x.trim().parse().ok()).collect();
if p.len() == 3 {
Some(Color32::from_rgb(p[0], p[1], p[2]))
} else {
hex(s)
}
}
pub fn read_system() -> SystemColors {
let mut out = SystemColors::default();
let Ok(txt) = std::fs::read_to_string(kdeglobals_path()) else {
return out;
};
let mut section = String::new();
let (mut accent, mut sel, mut win) = (None, None, None);
for line in txt.lines() {
let line = line.trim();
if let Some(s) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
section = s.to_string();
} else if let Some((k, v)) = line.split_once('=') {
match (section.as_str(), k) {
("General", "AccentColor") => accent = parse_rgb(v),
("Colors:Selection", "BackgroundNormal") => sel = parse_rgb(v),
("Colors:Window", "BackgroundNormal") => win = parse_rgb(v),
_ => {}
}
}
}
out.accent = accent.or(sel);
out.window_bg = win;
out
}
pub fn system_mtime() -> Option<std::time::SystemTime> {
std::fs::metadata(kdeglobals_path()).ok()?.modified().ok()
}
// ------------------------------------------------------------------ theme
#[derive(Clone)]
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 surface: Color32,
pub surface_bright: Color32,
pub surface_container_lowest: Color32,
pub surface_container_low: Color32,
pub surface_container: Color32,
pub surface_container_high: Color32,
pub surface_container_highest: Color32,
pub on_surface: Color32,
pub on_surface_variant: Color32,
pub outline: Color32,
pub outline_variant: Color32,
pub inverse_surface: Color32,
pub inverse_on_surface: Color32,
}
impl Theme {
/// Build the scheme from settings, system colours and (optionally) the album art seed.
pub fn build(album_seed: Option<Color32>) -> Theme {
let sys = read_system();
let src = settings().get_str("appearance/color_source");
let seed = match src.as_str() {
"album" => album_seed,
"custom" => hex(&settings().get_str("appearance/custom_color")),
_ => None,
}
.or(sys.accent)
.unwrap_or(Color32::from_rgb(0x9a, 0x7f, 0xd1));
let dark = match settings().get_str("appearance/mode").as_str() {
"dark" => true,
"light" => false,
_ => sys.window_bg.map(|w| lightness(w) < 0.5).unwrap_or(true),
};
let (_, sc, sh) = rgb_to_oklch(seed.r(), seed.g(), seed.b());
let pc = sc.clamp(0.085, 0.15);
let primary = Tonal { h: sh, c: pc };
let secondary = Tonal { h: sh, c: 0.04 };
let tertiary = Tonal { h: (sh + 60.0) % 360.0, c: 0.075 };
let err = Tonal { h: 25.0, c: 0.17 };
// neutrals follow the system window background (hue/chroma/tone)
let (nh, nc, base_tone) = match (sys.window_bg, src.as_str()) {
(Some(w), "kde") => {
let (wl, wc, wh) = rgb_to_oklch(w.r(), w.g(), w.b());
(if wc > 0.006 { wh } else { sh }, wc.clamp(0.008, 0.035), Some(l_to_tone(wl)))
}
_ => (sh, 0.014, None),
};
let neutral = Tonal { h: nh, c: nc };
let nvar = Tonal { h: nh, c: (nc * 1.8).max(0.022) };
if dark {
let st = base_tone.map(|t| t.clamp(3.0, 16.0)).unwrap_or(6.0);
Theme {
dark,
primary: primary.at(80.0),
on_primary: primary.at(20.0),
primary_container: primary.at(30.0),
on_primary_container: primary.at(90.0),
secondary: secondary.at(80.0),
on_secondary: secondary.at(20.0),
secondary_container: secondary.at(30.0),
on_secondary_container: secondary.at(90.0),
tertiary: tertiary.at(80.0),
on_tertiary: tertiary.at(20.0),
tertiary_container: tertiary.at(30.0),
on_tertiary_container: tertiary.at(90.0),
error: err.at(80.0),
on_error: err.at(20.0),
surface: neutral.at(st),
surface_bright: neutral.at(st + 18.0),
surface_container_lowest: neutral.at((st - 2.0).max(1.0)),
surface_container_low: neutral.at(st + 4.0),
surface_container: neutral.at(st + 6.0),
surface_container_high: neutral.at(st + 11.0),
surface_container_highest: neutral.at(st + 16.0),
on_surface: neutral.at(90.0),
on_surface_variant: nvar.at(80.0),
outline: nvar.at(60.0),
outline_variant: nvar.at(30.0),
inverse_surface: neutral.at(90.0),
inverse_on_surface: neutral.at(20.0),
}
} else {
let st = base_tone.map(|t| t.clamp(90.0, 99.0)).unwrap_or(98.0);
Theme {
dark,
primary: primary.at(40.0),
on_primary: primary.at(100.0),
primary_container: primary.at(90.0),
on_primary_container: primary.at(10.0),
secondary: secondary.at(40.0),
on_secondary: secondary.at(100.0),
secondary_container: secondary.at(90.0),
on_secondary_container: secondary.at(10.0),
tertiary: tertiary.at(40.0),
on_tertiary: tertiary.at(100.0),
tertiary_container: tertiary.at(90.0),
on_tertiary_container: tertiary.at(10.0),
error: err.at(40.0),
on_error: err.at(100.0),
surface: neutral.at(st),
surface_bright: neutral.at(st),
surface_container_lowest: neutral.at(100.0),
surface_container_low: neutral.at(st - 2.0),
surface_container: neutral.at(st - 4.0),
surface_container_high: neutral.at(st - 6.0),
surface_container_highest: neutral.at(st - 8.0),
on_surface: neutral.at(10.0),
on_surface_variant: nvar.at(30.0),
outline: nvar.at(50.0),
outline_variant: nvar.at(80.0),
inverse_surface: neutral.at(20.0),
inverse_on_surface: neutral.at(95.0),
}
}
}
pub fn same_colors(&self, o: &Theme) -> bool {
self.dark == o.dark && self.primary == o.primary && self.surface == o.surface
}
}