Damson/src/theme.rs
astar76 8151aa71c0 Damson: a Material You code editor in Rust
Runs Kate's syntax definitions directly, on a hand-written editor core.
Spring-driven UI with a pop-out scrolling preview, baked-in terminal
grown from a morphing button, jelly tabs, command palette, side panels,
git, language servers and hot exit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 17:05:28 -06:00

268 lines
12 KiB
Rust

//! Material You colours: taken from Caelestia's scheme, or built from a seed in OKLCH space
//! (tone == CIE L*). Also picks the colours code is drawn in.
use crate::config::Settings;
use crate::syntax::DefStyle;
use eframe::egui::Color32;
use std::path::PathBuf;
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(c: Color32) -> (f64, f64, f64) {
let (r, g, b) = (srgb_to_lin(c.r() as f64 / 255.0), srgb_to_lin(c.g() as f64 / 255.0), srgb_to_lin(c.b() as f64 / 255.0));
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))
}
fn oklch_to_lin(l: f64, c: f64, h: f64) -> (f64, f64, f64) {
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_,
)
}
fn in_gamut(x: (f64, f64, f64)) -> bool {
[x.0, x.1, x.2].iter().all(|v| (-1e-4..=1.0001).contains(v))
}
pub fn oklch(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() as u8;
Color32::from_rgb(q(rgb.0), q(rgb.1), q(rgb.2))
}
fn tone_l(t: f64) -> f64 {
if t <= 8.0 { (t / 903.2963).cbrt() } else { (t + 16.0) / 116.0 }
}
#[derive(Clone, Copy)]
struct Tonal { h: f64, c: f64 }
impl Tonal {
fn at(&self, t: f64) -> Color32 {
oklch(tone_l(t), self.c, self.h)
}
}
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_unmultiplied(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 {
let [r, g, b, _] = c.to_srgba_unmultiplied();
Color32::from_rgba_unmultiplied(r, g, b, (a.clamp(0.0, 1.0) * 255.0).round() as u8)
}
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))
}
#[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 secondary_container: Color32, pub on_secondary_container: Color32,
pub tertiary: Color32,
pub tertiary_container: Color32, pub on_tertiary_container: Color32,
pub error: Color32, pub on_error: Color32,
pub surface: Color32,
pub lowest: Color32, pub low: Color32, pub container: Color32, pub high: Color32, pub highest: Color32,
pub on_surface: Color32, pub on_variant: Color32,
pub outline: Color32, pub outline_variant: Color32,
pub syntax: [Color32; 31],
pub ansi: [Color32; 16],
/// Hues used for added/changed/removed marks.
pub added: Color32, pub changed: Color32, pub removed: Color32,
}
fn caelestia_path() -> PathBuf {
dirs::state_dir().unwrap_or_else(|| PathBuf::from(".")).join("caelestia/scheme.json")
}
fn kde_accent() -> (Option<Color32>, Option<bool>) {
let Some(p) = dirs::config_dir().map(|d| d.join("kdeglobals")) else { return (None, None) };
let Ok(txt) = std::fs::read_to_string(p) else { return (None, None) };
let parse = |s: &str| -> Option<Color32> {
let v: Vec<u8> = s.split(',').take(3).filter_map(|x| x.trim().parse().ok()).collect();
(v.len() == 3).then(|| Color32::from_rgb(v[0], v[1], v[2]))
};
let (mut sec, mut accent, mut sel, mut win) = (String::new(), None, None, None);
for line in txt.lines() {
if let Some(s) = line.trim().strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
sec = s.to_string();
} else if let Some((k, v)) = line.split_once('=') {
match (sec.as_str(), k.trim()) {
("General", "AccentColor") => accent = parse(v),
("Colors:Selection", "BackgroundNormal") => sel = parse(v),
("Colors:Window", "BackgroundNormal") => win = parse(v),
_ => {}
}
}
}
(accent.or(sel), win.map(|w| rgb_to_oklch(w).0 < 0.6))
}
/// Seed colour and dark flag from Caelestia's current scheme.
fn caelestia_seed() -> Option<(Color32, bool)> {
let v: serde_json::Value = serde_json::from_slice(&std::fs::read(caelestia_path()).ok()?).ok()?;
let seed = hex(v["colours"]["primary"].as_str()?)?;
Some((seed, v["mode"].as_str() != Some("light")))
}
/// Something that changes when the desktop's colours do.
pub fn source_stamp() -> Option<std::time::SystemTime> {
let a = std::fs::metadata(caelestia_path()).ok().and_then(|m| m.modified().ok());
let b = dirs::config_dir().and_then(|d| std::fs::metadata(d.join("kdeglobals")).ok()).and_then(|m| m.modified().ok());
a.max(b)
}
impl Theme {
pub fn build(s: &Settings) -> Theme {
let (kde_seed, kde_dark) = kde_accent();
let cael = caelestia_seed();
let fallback = Color32::from_rgb(0x7f, 0x5f, 0xc4);
let custom = hex(&s.custom_color);
let (seed, sys_dark) = match s.color_source.as_str() {
"custom" => (custom.unwrap_or(fallback), cael.map(|c| c.1).or(kde_dark)),
"kde" => (kde_seed.unwrap_or(fallback), kde_dark),
"caelestia" => (cael.map(|c| c.0).or(kde_seed).unwrap_or(fallback), cael.map(|c| c.1)),
_ => (cael.map(|c| c.0).or(kde_seed).unwrap_or(fallback), cael.map(|c| c.1).or(kde_dark)),
};
let dark = match s.mode.as_str() { "dark" => true, "light" => false, _ => sys_dark.unwrap_or(true) };
Self::from_seed(seed, dark, &s.scheme)
}
pub fn from_seed(seed: Color32, dark: bool, scheme: &str) -> Theme {
let (_, sc, sh) = rgb_to_oklch(seed);
let (pc, sec_c, ter_c, ter_shift, neutral_c) = match scheme {
"vibrant" => (sc.clamp(0.13, 0.19), 0.08, 0.11, 45.0, 0.022),
"expressive" => (sc.clamp(0.10, 0.16), 0.07, 0.12, 130.0, 0.026),
"mono" => (0.012, 0.008, 0.012, 0.0, 0.004),
_ => (sc.clamp(0.085, 0.15), 0.04, 0.075, 60.0, 0.014),
};
let p = Tonal { h: sh, c: pc };
let sec = Tonal { h: sh, c: sec_c };
let ter = Tonal { h: (sh + ter_shift) % 360.0, c: ter_c };
let err = Tonal { h: 25.0, c: 0.17 };
let n = Tonal { h: sh, c: neutral_c };
let nv = Tonal { h: sh, c: (neutral_c * 1.8).max(0.016) };
let d = |dk: f64, lt: f64| if dark { dk } else { lt };
// code colours: fixed hue families pulled a little towards the seed so they sit in the scheme
let tone = d(82.0, 38.0);
let chroma = if scheme == "mono" { 0.02 } else if scheme == "vibrant" { 0.135 } else { 0.105 };
let pull = |h: f64| {
let delta = (sh - h + 540.0).rem_euclid(360.0) - 180.0;
h + delta * 0.14
};
let hue = |h: f64, t: f64, c: f64| oklch(tone_l(t), chroma * c, pull(h));
let main = n.at(d(90.0, 14.0));
let dim = nv.at(d(62.0, 48.0));
let key = p.at(d(80.0, 40.0));
let ctl = Tonal { h: (sh + 300.0) % 360.0, c: pc.max(0.1) }.at(d(80.0, 40.0));
let func = hue(235.0, tone + d(3.0, 0.0), 1.0);
let typ = ter.at(d(82.0, 38.0));
let string = hue(145.0, tone, 1.0);
let special = hue(175.0, tone, 1.0);
let number = hue(60.0, tone, 1.1);
let constant = hue(30.0, tone, 1.1);
let prep = hue(95.0, tone, 1.0);
let warn = hue(85.0, tone, 1.3);
let attr = hue(350.0, tone, 0.9);
let mut syntax = [main; 31];
for st in DefStyle::ALL {
use DefStyle::*;
syntax[st as usize] = match st {
Normal | Variable | Others => main,
Keyword => key, ControlFlow => ctl, Function => func, Operator => nv.at(d(78.0, 36.0)),
BuiltIn | Extension => func, Preprocessor | Import => prep, Attribute | Annotation => attr,
Char | SpecialChar | SpecialString => special, String | VerbatimString => string,
DataType => typ, DecVal | BaseN | Float => number, Constant => constant,
Comment | Documentation | CommentVar | RegionMarker => dim,
Information => func, Warning => warn, Alert => constant, Error => err.at(d(80.0, 40.0)),
};
}
let a = |h: f64, t: f64| oklch(tone_l(t), 0.12, pull(h));
let (lo, hi) = (d(72.0, 42.0), d(84.0, 54.0));
let ansi = [
n.at(d(24.0, 22.0)), a(25.0, lo), a(145.0, lo), a(85.0, lo), a(250.0, lo), a(320.0, lo), a(195.0, lo), n.at(d(82.0, 70.0)),
n.at(d(46.0, 44.0)), a(25.0, hi), a(145.0, hi), a(85.0, hi), a(250.0, hi), a(320.0, hi), a(195.0, hi), n.at(d(96.0, 92.0)),
];
Theme {
dark,
primary: p.at(d(80.0, 40.0)), on_primary: p.at(d(20.0, 100.0)),
primary_container: p.at(d(30.0, 90.0)), on_primary_container: p.at(d(90.0, 10.0)),
secondary: sec.at(d(80.0, 40.0)),
secondary_container: sec.at(d(30.0, 90.0)), on_secondary_container: sec.at(d(90.0, 10.0)),
tertiary: ter.at(d(80.0, 40.0)),
tertiary_container: ter.at(d(30.0, 90.0)), on_tertiary_container: ter.at(d(90.0, 10.0)),
error: err.at(d(80.0, 40.0)), on_error: err.at(d(20.0, 100.0)),
surface: n.at(d(6.0, 98.0)),
lowest: n.at(d(4.0, 100.0)), low: n.at(d(10.0, 96.0)), container: n.at(d(12.0, 94.0)),
high: n.at(d(17.0, 92.0)), highest: n.at(d(22.0, 90.0)),
on_surface: n.at(d(90.0, 10.0)), on_variant: nv.at(d(80.0, 30.0)),
outline: nv.at(d(60.0, 50.0)), outline_variant: nv.at(d(30.0, 80.0)),
syntax, ansi,
added: hue(145.0, d(74.0, 48.0), 1.3), changed: hue(235.0, d(74.0, 48.0), 1.3), removed: err.at(d(70.0, 50.0)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn contrast(a: Color32, b: Color32) -> f64 {
let lum = |c: Color32| 0.2126 * srgb_to_lin(c.r() as f64 / 255.0) + 0.7152 * srgb_to_lin(c.g() as f64 / 255.0) + 0.0722 * srgb_to_lin(c.b() as f64 / 255.0);
let (x, y) = (lum(a), lum(b));
(x.max(y) + 0.05) / (x.min(y) + 0.05)
}
#[test]
fn code_stays_readable_on_every_scheme() {
for seed in ["#7f5fc4", "#d0485e", "#3f9c6b", "#c8a020", "#2b7fd4"] {
for dark in [true, false] {
for sc in ["tonal", "vibrant", "expressive", "mono"] {
let t = Theme::from_seed(hex(seed).unwrap(), dark, sc);
for st in DefStyle::ALL {
let c = contrast(t.syntax[st as usize], t.low);
assert!(c >= 3.0, "{seed} dark={dark} {sc} {st:?} contrast {c:.2}");
}
}
}
}
}
}