Nacre/src/theme.rs
astar76 8b2b2a5655 S003: first launch on Xvfb, smoke harness, epaint glyph panic and quit segfault fixed
- tools/smoke.sh + tests/smoke/{launch,https,restore}.txt: hidden Xvfb run with a throwaway home
- vendor/epaint: render glyphs single-threaded (Servo enables vello_cpu/multithreading), D-006
- App::quit drops every Servo handle before the GL contexts, so Servo shuts down cleanly
- D-005: smoke runs use Xvfb

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 18:01:15 -06:00

323 lines
12 KiB
Rust

//! Colours and shapes for the interface, from the Appearance settings. Kept plain on purpose:
//! one accent colour drives a small set of roles; the designed look comes later.
use egui::{Color32, CornerRadius, Visuals};
use crate::store::settings::{ColourFallback, ColourSource, Motion, Roundness, Settings, ThemeMode};
/// Palette presets shown in Appearance (the swatches in the screenshot).
pub const PRESETS: &[&str] = &["#6750A4", "#B3261E", "#7D5260", "#006A6A", "#386A20", "#984061", "#0061A4", "#8B5000", "#5B5F97", "#006E1C", "#9C4146", "#625B71"];
/// Scheme styles: (key, label).
pub const VARIANTS: &[(&str, &str)] = &[("tonal_spot", "Tonal spot"), ("vibrant", "Vibrant"), ("expressive", "Expressive"), ("neutral", "Neutral"), ("monochrome", "Monochrome"), ("fidelity", "Fidelity"), ("content", "Content")];
pub fn parse_hex(text: &str) -> Option<Color32> {
let t = text.trim().trim_start_matches('#');
let v = u32::from_str_radix(t, 16).ok()?;
match t.len() {
6 => Some(Color32::from_rgb((v >> 16) as u8, (v >> 8) as u8, v as u8)),
3 => {
let r = ((v >> 8) & 0xF) as u8 * 17;
let g = ((v >> 4) & 0xF) as u8 * 17;
let b = (v & 0xF) as u8 * 17;
Some(Color32::from_rgb(r, g, b))
},
_ => None,
}
}
/// "rgb(1, 2, 3)", "rgba(...)" or "#abc" from CSS.
pub fn parse_css_color(text: &str) -> Option<Color32> {
let t = text.trim();
if t.starts_with('#') {
return parse_hex(t);
}
let inner = t.strip_prefix("rgba(").or_else(|| t.strip_prefix("rgb("))?.trim_end_matches(')');
let nums: Vec<f32> = inner.split([',', ' ', '/']).filter(|s| !s.is_empty()).filter_map(|s| s.trim().parse().ok()).collect();
if nums.len() < 3 || nums.get(3).is_some_and(|a| *a < 0.5) {
return None;
}
Some(Color32::from_rgb(nums[0] as u8, nums[1] as u8, nums[2] as u8))
}
pub fn to_hex(c: Color32) -> String {
format!("#{:02X}{:02X}{:02X}", c.r(), c.g(), c.b())
}
fn to_hsl(c: Color32) -> (f32, f32, f32) {
let (r, g, b) = (c.r() as f32 / 255.0, c.g() as f32 / 255.0, c.b() as f32 / 255.0);
let max = r.max(g).max(b);
let min = r.min(g).min(b);
let l = (max + min) / 2.0;
if (max - min).abs() < 1e-6 {
return (0.0, 0.0, l);
}
let d = max - min;
let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) };
let h = if max == r { (g - b) / d + if g < b { 6.0 } else { 0.0 } } else if max == g { (b - r) / d + 2.0 } else { (r - g) / d + 4.0 };
(h * 60.0, s, l)
}
fn from_hsl(h: f32, s: f32, l: f32) -> Color32 {
let hue = |p: f32, q: f32, mut t: f32| {
if t < 0.0 {
t += 1.0;
}
if t > 1.0 {
t -= 1.0;
}
if t < 1.0 / 6.0 {
p + (q - p) * 6.0 * t
} else if t < 0.5 {
q
} else if t < 2.0 / 3.0 {
p + (q - p) * (2.0 / 3.0 - t) * 6.0
} else {
p
}
};
let (s, l) = (s.clamp(0.0, 1.0), l.clamp(0.0, 1.0));
if s == 0.0 {
let v = (l * 255.0) as u8;
return Color32::from_rgb(v, v, v);
}
let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s };
let p = 2.0 * l - q;
let h = h.rem_euclid(360.0) / 360.0;
Color32::from_rgb((hue(p, q, h + 1.0 / 3.0) * 255.0) as u8, (hue(p, q, h) * 255.0) as u8, (hue(p, q, h - 1.0 / 3.0) * 255.0) as u8)
}
/// The system accent colour: KDE's kdeglobals, else GNOME's accent-color setting.
pub fn system_accent() -> Option<Color32> {
#[cfg(unix)]
{
if let Some(path) = dirs::config_dir().map(|d| d.join("kdeglobals"))
&& let Ok(text) = std::fs::read_to_string(path)
{
let mut in_general = false;
for line in text.lines() {
let line = line.trim();
if line.starts_with('[') {
in_general = line == "[General]";
} else if in_general && let Some(v) = line.strip_prefix("AccentColor=") {
let n: Vec<u8> = v.split(',').filter_map(|p| p.trim().parse().ok()).collect();
if n.len() >= 3 {
return Some(Color32::from_rgb(n[0], n[1], n[2]));
}
}
}
}
if let Ok(out) = std::process::Command::new("gsettings").args(["get", "org.gnome.desktop.interface", "accent-color"]).output() {
let name = String::from_utf8_lossy(&out.stdout).trim().trim_matches('\'').to_owned();
let c = match name.as_str() {
"blue" => "#3584E4",
"teal" => "#2190A4",
"green" => "#3A944A",
"yellow" => "#C88800",
"orange" => "#ED5B00",
"red" => "#E62D42",
"pink" => "#D56199",
"purple" => "#9141AC",
"slate" => "#6F8396",
_ => "",
};
if !c.is_empty() {
return parse_hex(c);
}
}
None
}
#[cfg(not(unix))]
{
None
}
}
/// Whether the system prefers dark (used for "System" mode before winit reports a theme).
pub fn system_dark(winit_theme: Option<winit::window::Theme>) -> bool {
match winit_theme {
Some(winit::window::Theme::Dark) => true,
Some(winit::window::Theme::Light) => false,
None => {
#[cfg(unix)]
{
std::process::Command::new("gsettings").args(["get", "org.gnome.desktop.interface", "color-scheme"]).output().map(|o| String::from_utf8_lossy(&o.stdout).contains("dark")).unwrap_or(true)
}
#[cfg(not(unix))]
{
true
}
},
}
}
/// The colour roles the interface uses.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Palette {
pub dark: bool,
pub accent: Color32,
pub on_accent: Color32,
pub accent_soft: Color32,
pub surface: Color32,
pub surface_high: Color32,
pub surface_low: Color32,
pub text: Color32,
pub text_weak: Color32,
pub outline: Color32,
pub error: Color32,
pub warning: Color32,
pub success: Color32,
}
impl Palette {
pub fn new(seed: Color32, dark: bool, variant: &str, contrast: f32) -> Palette {
let (h, s, _) = to_hsl(seed);
let s = match variant {
"vibrant" => (s * 1.25).min(1.0),
"expressive" => (s * 1.1).min(1.0),
"neutral" => s * 0.35,
"monochrome" => 0.0,
"fidelity" | "content" => s,
_ => s * 0.8,
};
let h2 = if variant == "expressive" { h + 60.0 } else { h };
let c = contrast.clamp(-1.0, 1.0) * 0.08;
let tint = if variant == "monochrome" { 0.0 } else { (s * 0.22).min(0.18) };
if dark {
Palette {
dark,
accent: from_hsl(h, s.max(0.3).min(0.8), 0.72 + c),
on_accent: from_hsl(h, 0.6, 0.18),
accent_soft: from_hsl(h2, s * 0.5, 0.28),
surface: from_hsl(h, tint, 0.075 - c * 0.5),
surface_high: from_hsl(h, tint, 0.14),
surface_low: from_hsl(h, tint, 0.05),
text: from_hsl(h, tint * 0.5, 0.92 + c),
text_weak: from_hsl(h, tint, 0.68 + c),
outline: from_hsl(h, tint, 0.32),
error: Color32::from_rgb(0xF2, 0xB8, 0xB5),
warning: Color32::from_rgb(0xFF, 0xCC, 0x80),
success: Color32::from_rgb(0xA5, 0xD6, 0xA7),
}
} else {
Palette {
dark,
accent: from_hsl(h, s.max(0.35).min(0.85), 0.40 - c),
on_accent: Color32::WHITE,
accent_soft: from_hsl(h2, s * 0.6, 0.88),
surface: from_hsl(h, tint, 0.975 + c * 0.2),
surface_high: from_hsl(h, tint, 0.92),
surface_low: from_hsl(h, tint, 0.995),
text: from_hsl(h, tint * 0.5, 0.10 - c),
text_weak: from_hsl(h, tint, 0.36 - c),
outline: from_hsl(h, tint, 0.78),
error: Color32::from_rgb(0xB3, 0x26, 0x1E),
warning: Color32::from_rgb(0x8B, 0x50, 0x00),
success: Color32::from_rgb(0x38, 0x6A, 0x20),
}
}
}
}
/// Seed colour from the settings; `site` is the current page's colour when the source is "Website".
pub fn seed(settings: &Settings, site: Option<Color32>, system: Option<Color32>) -> Color32 {
let preset = parse_hex(&settings.theme.preset).unwrap_or(Color32::from_rgb(0x67, 0x50, 0xA4));
let fallback = || match settings.theme.fallback {
ColourFallback::System => system.unwrap_or(preset),
ColourFallback::Palette => preset,
};
match settings.theme.source {
ColourSource::Website => site.filter(|c| { let (_, s, l) = to_hsl(*c); s > 0.15 && l > 0.1 && l < 0.9 }).unwrap_or_else(fallback),
ColourSource::System => system.unwrap_or(preset),
ColourSource::Palette => preset,
ColourSource::Custom => parse_hex(&settings.theme.custom).unwrap_or(preset),
}
}
pub fn is_dark(settings: &Settings, system_is_dark: bool) -> bool {
match settings.theme.mode {
ThemeMode::System => system_is_dark,
ThemeMode::Light => false,
ThemeMode::Dark => true,
}
}
pub fn corner(settings: &Settings) -> u8 {
match settings.ui.roundness {
Roundness::Subtle => 4,
Roundness::Normal => 8,
Roundness::Round => 14,
}
}
/// Seconds for UI animations (0 = off).
pub fn animation_time(settings: &Settings) -> f32 {
match settings.ui.motion {
Motion::Off => 0.0,
Motion::Fast => 0.06,
Motion::Normal => 0.1,
Motion::Slow => 0.18,
}
}
/// egui visuals for a palette.
pub fn visuals(p: &Palette, corner_radius: u8) -> Visuals {
let mut v = if p.dark { Visuals::dark() } else { Visuals::light() };
let r = CornerRadius::same(corner_radius);
v.panel_fill = p.surface;
v.window_fill = p.surface_high;
v.extreme_bg_color = p.surface_low;
v.faint_bg_color = p.surface_high;
v.override_text_color = Some(p.text);
v.hyperlink_color = p.accent;
v.selection.bg_fill = p.accent.gamma_multiply(0.45);
v.selection.stroke.color = p.accent;
v.window_corner_radius = r;
v.menu_corner_radius = r;
v.window_stroke.color = p.outline;
v.error_fg_color = p.error;
v.warn_fg_color = p.warning;
for w in [&mut v.widgets.noninteractive, &mut v.widgets.inactive, &mut v.widgets.hovered, &mut v.widgets.active, &mut v.widgets.open] {
w.corner_radius = r;
}
v.widgets.noninteractive.bg_fill = p.surface;
v.widgets.noninteractive.bg_stroke.color = p.outline;
v.widgets.noninteractive.fg_stroke.color = p.text;
v.widgets.inactive.bg_fill = p.surface_high;
v.widgets.inactive.weak_bg_fill = p.surface_high;
v.widgets.inactive.fg_stroke.color = p.text;
v.widgets.hovered.bg_fill = p.accent_soft;
v.widgets.hovered.weak_bg_fill = p.accent_soft;
v.widgets.hovered.bg_stroke.color = p.accent;
v.widgets.active.bg_fill = p.accent;
v.widgets.active.weak_bg_fill = p.accent;
v.widgets.active.fg_stroke.color = p.on_accent;
v
}
#[cfg(test)]
mod tests {
use super::*;
/// epaint 0.37.0 panicked rasterizing glyphs once Servo turned on vello_cpu's multithreading
/// (vendor/epaint patch). Laying out text renders glyphs.
#[test]
fn egui_draws_text() {
let ctx = egui::Context::default();
let output = ctx.run_ui(Default::default(), |ui| {
ui.label("Nacre");
});
assert!(!output.shapes.is_empty());
}
#[test]
fn colours() {
assert_eq!(parse_hex("#6750A4"), Some(Color32::from_rgb(0x67, 0x50, 0xA4)));
assert_eq!(parse_css_color("rgb(10, 20, 30)"), Some(Color32::from_rgb(10, 20, 30)));
assert_eq!(parse_css_color("rgba(0, 0, 0, 0)"), None);
let c = Color32::from_rgb(200, 100, 50);
let (h, s, l) = to_hsl(c);
let back = from_hsl(h, s, l);
assert!((back.r() as i32 - 200).abs() <= 1 && (back.g() as i32 - 100).abs() <= 1);
}
}