| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
use serde::Serialize; |
| 38 |
use std::collections::{BTreeMap, HashMap}; |
| 39 |
use std::path::{Path, PathBuf}; |
| 40 |
|
| 41 |
|
| 42 |
pub const COLOR_SECTIONS: &[&str] = &["surface", "content", "action", "status", "line", "category"]; |
| 43 |
|
| 44 |
|
| 45 |
#[derive(Debug, Clone, Serialize)] |
| 46 |
#[serde(rename_all = "camelCase")] |
| 47 |
pub struct ThemeMeta { |
| 48 |
pub id: String, |
| 49 |
pub name: String, |
| 50 |
pub variant: String, |
| 51 |
pub is_custom: bool, |
| 52 |
} |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
#[derive(Debug, Serialize)] |
| 57 |
#[serde(rename_all = "camelCase")] |
| 58 |
pub struct ThemeColors { |
| 59 |
pub meta: ThemeMeta, |
| 60 |
pub colors: HashMap<String, String>, |
| 61 |
} |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 75 |
pub struct Rgb { |
| 76 |
pub r: u8, |
| 77 |
pub g: u8, |
| 78 |
pub b: u8, |
| 79 |
} |
| 80 |
|
| 81 |
impl Rgb { |
| 82 |
|
| 83 |
pub fn from_hex(s: &str) -> Option<Rgb> { |
| 84 |
let h = s.strip_prefix('#')?; |
| 85 |
let (r, g, b) = match h.len() { |
| 86 |
6 => ( |
| 87 |
u8::from_str_radix(&h[0..2], 16).ok()?, |
| 88 |
u8::from_str_radix(&h[2..4], 16).ok()?, |
| 89 |
u8::from_str_radix(&h[4..6], 16).ok()?, |
| 90 |
), |
| 91 |
3 => { |
| 92 |
let d = |c: &str| u8::from_str_radix(c, 16).ok().map(|v| v * 17); |
| 93 |
(d(&h[0..1])?, d(&h[1..2])?, d(&h[2..3])?) |
| 94 |
} |
| 95 |
_ => return None, |
| 96 |
}; |
| 97 |
Some(Rgb { r, g, b }) |
| 98 |
} |
| 99 |
|
| 100 |
|
| 101 |
pub fn to_hex(self) -> String { |
| 102 |
format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b) |
| 103 |
} |
| 104 |
|
| 105 |
pub fn tuple(self) -> (u8, u8, u8) { |
| 106 |
(self.r, self.g, self.b) |
| 107 |
} |
| 108 |
} |
| 109 |
|
| 110 |
|
| 111 |
#[derive(Clone, Copy, Debug)] |
| 112 |
pub struct Oklab { |
| 113 |
pub l: f32, |
| 114 |
pub a: f32, |
| 115 |
pub b: f32, |
| 116 |
} |
| 117 |
|
| 118 |
fn srgb_to_linear(c: u8) -> f32 { |
| 119 |
let c = c as f32 / 255.0; |
| 120 |
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } |
| 121 |
} |
| 122 |
|
| 123 |
fn linear_to_srgb(c: f32) -> u8 { |
| 124 |
let c = c.clamp(0.0, 1.0); |
| 125 |
let v = if c <= 0.0031308 { c * 12.92 } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 }; |
| 126 |
(v * 255.0).round().clamp(0.0, 255.0) as u8 |
| 127 |
} |
| 128 |
|
| 129 |
impl Rgb { |
| 130 |
|
| 131 |
pub fn to_oklab(self) -> Oklab { |
| 132 |
let (r, g, b) = (srgb_to_linear(self.r), srgb_to_linear(self.g), srgb_to_linear(self.b)); |
| 133 |
let l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b; |
| 134 |
let m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b; |
| 135 |
let s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b; |
| 136 |
let (l_, m_, s_) = (l.cbrt(), m.cbrt(), s.cbrt()); |
| 137 |
Oklab { |
| 138 |
l: 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_, |
| 139 |
a: 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_, |
| 140 |
b: 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_, |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
|
| 145 |
pub fn from_oklab(c: Oklab) -> Rgb { |
| 146 |
let l_ = c.l + 0.3963377774 * c.a + 0.2158037573 * c.b; |
| 147 |
let m_ = c.l - 0.1055613458 * c.a - 0.0638541728 * c.b; |
| 148 |
let s_ = c.l - 0.0894841775 * c.a - 1.2914855480 * c.b; |
| 149 |
let (l, m, s) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_); |
| 150 |
Rgb { |
| 151 |
r: linear_to_srgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s), |
| 152 |
g: linear_to_srgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s), |
| 153 |
b: linear_to_srgb(-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s), |
| 154 |
} |
| 155 |
} |
| 156 |
} |
| 157 |
|
| 158 |
|
| 159 |
fn rel_luminance(c: Rgb) -> f32 { |
| 160 |
0.2126 * srgb_to_linear(c.r) + 0.7152 * srgb_to_linear(c.g) + 0.0722 * srgb_to_linear(c.b) |
| 161 |
} |
| 162 |
|
| 163 |
|
| 164 |
pub fn wcag_contrast(a: Rgb, b: Rgb) -> f32 { |
| 165 |
let (la, lb) = (rel_luminance(a), rel_luminance(b)); |
| 166 |
let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) }; |
| 167 |
(hi + 0.05) / (lo + 0.05) |
| 168 |
} |
| 169 |
|
| 170 |
|
| 171 |
|
| 172 |
pub fn readable_on(bg: Rgb) -> Rgb { |
| 173 |
let white = Rgb { r: 255, g: 255, b: 255 }; |
| 174 |
let black = Rgb { r: 0, g: 0, b: 0 }; |
| 175 |
if wcag_contrast(white, bg) >= wcag_contrast(black, bg) { white } else { black } |
| 176 |
} |
| 177 |
|
| 178 |
|
| 179 |
pub fn lighten(c: Rgb, delta: f32) -> Rgb { |
| 180 |
let mut lab = c.to_oklab(); |
| 181 |
lab.l = (lab.l + delta).clamp(0.0, 1.0); |
| 182 |
Rgb::from_oklab(lab) |
| 183 |
} |
| 184 |
|
| 185 |
|
| 186 |
pub fn darken(c: Rgb, delta: f32) -> Rgb { |
| 187 |
lighten(c, -delta) |
| 188 |
} |
| 189 |
|
| 190 |
|
| 191 |
pub fn mix(a: Rgb, b: Rgb, t: f32) -> Rgb { |
| 192 |
let (x, y) = (a.to_oklab(), b.to_oklab()); |
| 193 |
Rgb::from_oklab(Oklab { |
| 194 |
l: x.l + (y.l - x.l) * t, |
| 195 |
a: x.a + (y.a - x.a) * t, |
| 196 |
b: x.b + (y.b - x.b) * t, |
| 197 |
}) |
| 198 |
} |
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
pub const BASE_INTENTS: &[(&str, &str)] = &[ |
| 208 |
("surface.page", "surface-page"), |
| 209 |
("surface.raised", "surface-raised"), |
| 210 |
("surface.sunken", "surface-sunken"), |
| 211 |
("surface.overlay", "surface-overlay"), |
| 212 |
("content.primary", "content"), |
| 213 |
("content.secondary", "content-secondary"), |
| 214 |
("content.muted", "content-muted"), |
| 215 |
("action.primary", "action"), |
| 216 |
("status.danger", "danger"), |
| 217 |
("status.success", "success"), |
| 218 |
("status.warning", "warning"), |
| 219 |
("status.info", "info"), |
| 220 |
("line.border", "border"), |
| 221 |
("category.one", "category-one"), |
| 222 |
("category.two", "category-two"), |
| 223 |
("category.three", "category-three"), |
| 224 |
("category.four", "category-four"), |
| 225 |
("category.five", "category-five"), |
| 226 |
("category.six", "category-six"), |
| 227 |
]; |
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
#[derive(Debug, Clone, Serialize)] |
| 232 |
#[serde(rename_all = "camelCase")] |
| 233 |
pub struct SemanticTokens { |
| 234 |
pub meta: ThemeMeta, |
| 235 |
|
| 236 |
pub intents: BTreeMap<String, String>, |
| 237 |
} |
| 238 |
|
| 239 |
impl SemanticTokens { |
| 240 |
|
| 241 |
pub fn hex(&self, key: &str) -> Option<&str> { |
| 242 |
self.intents.get(key).map(String::as_str) |
| 243 |
} |
| 244 |
|
| 245 |
|
| 246 |
pub fn rgb(&self, key: &str) -> Option<(u8, u8, u8)> { |
| 247 |
self.intents.get(key).and_then(|h| Rgb::from_hex(h)).map(Rgb::tuple) |
| 248 |
} |
| 249 |
} |
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
|
| 258 |
pub fn resolve(theme: &ThemeColors) -> SemanticTokens { |
| 259 |
let mut intents: BTreeMap<String, String> = BTreeMap::new(); |
| 260 |
|
| 261 |
|
| 262 |
|
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
for (src, token) in BASE_INTENTS { |
| 267 |
if let Some(rgb) = theme.colors.get(*src).and_then(|v| Rgb::from_hex(v)) { |
| 268 |
intents.insert((*token).to_string(), rgb.to_hex()); |
| 269 |
} |
| 270 |
} |
| 271 |
|
| 272 |
|
| 273 |
let get = |m: &BTreeMap<String, String>, k: &str| m.get(k).and_then(|h| Rgb::from_hex(h)); |
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
let mut derived: Vec<(String, Rgb)> = Vec::new(); |
| 278 |
if let Some(action) = get(&intents, "action") { |
| 279 |
derived.push(("action-hover".into(), lighten(action, 0.05))); |
| 280 |
derived.push(("content-on-action".into(), readable_on(action))); |
| 281 |
derived.push(("focus-ring".into(), action)); |
| 282 |
} |
| 283 |
if let Some(page) = get(&intents, "surface-page") { |
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
let mut o = page.to_oklab(); |
| 289 |
o.l = 0.08; |
| 290 |
let s = Rgb::from_oklab(o); |
| 291 |
intents.insert("overlay".into(), format!("rgba({}, {}, {}, 0.5)", s.r, s.g, s.b)); |
| 292 |
} |
| 293 |
if let Some(sunken) = get(&intents, "surface-sunken") { |
| 294 |
derived.push(("hover-surface".into(), sunken)); |
| 295 |
} |
| 296 |
if let Some(border) = get(&intents, "border") { |
| 297 |
derived.push(("border-strong".into(), darken(border, 0.05))); |
| 298 |
} |
| 299 |
|
| 300 |
for (token, rgb) in derived { |
| 301 |
intents.insert(token, rgb.to_hex()); |
| 302 |
} |
| 303 |
|
| 304 |
SemanticTokens { meta: theme.meta.clone(), intents } |
| 305 |
} |
| 306 |
|
| 307 |
|
| 308 |
|
| 309 |
pub fn intent_css_declarations(tokens: &SemanticTokens) -> String { |
| 310 |
let mut out = String::new(); |
| 311 |
for (token, hex) in &tokens.intents { |
| 312 |
out.push_str(" --"); |
| 313 |
out.push_str(token); |
| 314 |
out.push_str(": "); |
| 315 |
out.push_str(hex); |
| 316 |
out.push_str(";\n"); |
| 317 |
} |
| 318 |
out |
| 319 |
} |
| 320 |
|
| 321 |
|
| 322 |
|
| 323 |
pub fn intent_css_vars(tokens: &SemanticTokens) -> String { |
| 324 |
format!(":root {{\n{}}}\n", intent_css_declarations(tokens)) |
| 325 |
} |
| 326 |
|
| 327 |
|
| 328 |
|
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
pub fn validate_theme_id(id: &str) -> Result<(), String> { |
| 333 |
if !id |
| 334 |
.chars() |
| 335 |
.all(|c| c.is_alphanumeric() || c == '-' || c == '_') |
| 336 |
{ |
| 337 |
return Err(format!("Invalid theme ID: {}", id)); |
| 338 |
} |
| 339 |
Ok(()) |
| 340 |
} |
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
pub fn parse_meta(id: &str, table: &toml::Table, is_custom: bool) -> ThemeMeta { |
| 346 |
let meta = table.get("meta").and_then(|m| m.as_table()); |
| 347 |
let name = meta |
| 348 |
.and_then(|m| m.get("name")) |
| 349 |
.and_then(|v| v.as_str()) |
| 350 |
.unwrap_or(id) |
| 351 |
.to_string(); |
| 352 |
let variant = meta |
| 353 |
.and_then(|m| m.get("variant")) |
| 354 |
.and_then(|v| v.as_str()) |
| 355 |
.unwrap_or("dark") |
| 356 |
.to_string(); |
| 357 |
|
| 358 |
ThemeMeta { id: id.to_string(), name, variant, is_custom } |
| 359 |
} |
| 360 |
|
| 361 |
|
| 362 |
|
| 363 |
pub fn extract_colors(table: &toml::Table) -> HashMap<String, String> { |
| 364 |
let mut colors = HashMap::new(); |
| 365 |
for section in COLOR_SECTIONS { |
| 366 |
if let Some(sect) = table.get(*section).and_then(|s| s.as_table()) { |
| 367 |
for (key, val) in sect { |
| 368 |
if let Some(color) = val.as_str() { |
| 369 |
colors.insert(format!("{}.{}", section, key), color.to_string()); |
| 370 |
} |
| 371 |
} |
| 372 |
} |
| 373 |
} |
| 374 |
colors |
| 375 |
} |
| 376 |
|
| 377 |
|
| 378 |
|
| 379 |
|
| 380 |
|
| 381 |
pub fn list_themes_from_dirs(dirs: &[(PathBuf, bool)]) -> Vec<ThemeMeta> { |
| 382 |
let mut seen: HashMap<String, ThemeMeta> = HashMap::new(); |
| 383 |
|
| 384 |
for (dir, is_custom) in dirs { |
| 385 |
let entries = match std::fs::read_dir(dir) { |
| 386 |
Ok(e) => e, |
| 387 |
Err(_) => continue, |
| 388 |
}; |
| 389 |
|
| 390 |
for entry in entries { |
| 391 |
let entry = match entry { |
| 392 |
Ok(e) => e, |
| 393 |
Err(_) => continue, |
| 394 |
}; |
| 395 |
let path = entry.path(); |
| 396 |
if path.extension().and_then(|e| e.to_str()) != Some("toml") { |
| 397 |
continue; |
| 398 |
} |
| 399 |
|
| 400 |
let id = path |
| 401 |
.file_stem() |
| 402 |
.and_then(|s| s.to_str()) |
| 403 |
.unwrap_or_default() |
| 404 |
.to_string(); |
| 405 |
|
| 406 |
let content = match std::fs::read_to_string(&path) { |
| 407 |
Ok(c) => c, |
| 408 |
Err(_) => continue, |
| 409 |
}; |
| 410 |
let table: toml::Table = match content.parse() { |
| 411 |
Ok(t) => t, |
| 412 |
Err(_) => continue, |
| 413 |
}; |
| 414 |
|
| 415 |
seen.insert(id.clone(), parse_meta(&id, &table, *is_custom)); |
| 416 |
} |
| 417 |
} |
| 418 |
|
| 419 |
let mut themes: Vec<ThemeMeta> = seen.into_values().collect(); |
| 420 |
themes.sort_by(|a, b| a.name.cmp(&b.name)); |
| 421 |
themes |
| 422 |
} |
| 423 |
|
| 424 |
|
| 425 |
|
| 426 |
|
| 427 |
|
| 428 |
pub fn find_theme_path(dirs: &[(PathBuf, bool)], id: &str) -> Option<(PathBuf, bool)> { |
| 429 |
let filename = format!("{}.toml", id); |
| 430 |
|
| 431 |
for (dir, is_custom) in dirs.iter().rev() { |
| 432 |
let path = dir.join(&filename); |
| 433 |
if path.is_file() { |
| 434 |
return Some((path, *is_custom)); |
| 435 |
} |
| 436 |
} |
| 437 |
|
| 438 |
None |
| 439 |
} |
| 440 |
|
| 441 |
|
| 442 |
|
| 443 |
pub fn parse_theme_str(id: &str, content: &str, is_custom: bool) -> Result<ThemeColors, String> { |
| 444 |
validate_theme_id(id)?; |
| 445 |
let table: toml::Table = content |
| 446 |
.parse() |
| 447 |
.map_err(|e| format!("Failed to parse theme '{}': {}", id, e))?; |
| 448 |
let meta = parse_meta(id, &table, is_custom); |
| 449 |
let colors = extract_colors(&table); |
| 450 |
Ok(ThemeColors { meta, colors }) |
| 451 |
} |
| 452 |
|
| 453 |
|
| 454 |
pub fn load_theme(dirs: &[(PathBuf, bool)], id: &str) -> Result<ThemeColors, String> { |
| 455 |
validate_theme_id(id)?; |
| 456 |
|
| 457 |
let (path, is_custom) = |
| 458 |
find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{}' not found", id))?; |
| 459 |
|
| 460 |
let content = std::fs::read_to_string(&path) |
| 461 |
.map_err(|e| format!("Failed to read {}: {}", path.display(), e))?; |
| 462 |
|
| 463 |
let table: toml::Table = content |
| 464 |
.parse() |
| 465 |
.map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?; |
| 466 |
|
| 467 |
let meta = parse_meta(id, &table, is_custom); |
| 468 |
let colors = extract_colors(&table); |
| 469 |
|
| 470 |
Ok(ThemeColors { meta, colors }) |
| 471 |
} |
| 472 |
|
| 473 |
|
| 474 |
pub fn load_semantic(dirs: &[(PathBuf, bool)], id: &str) -> Result<SemanticTokens, String> { |
| 475 |
Ok(resolve(&load_theme(dirs, id)?)) |
| 476 |
} |
| 477 |
|
| 478 |
|
| 479 |
|
| 480 |
|
| 481 |
|
| 482 |
pub fn import_theme(source_path: &Path, custom_dir: &Path) -> Result<ThemeMeta, String> { |
| 483 |
let content = std::fs::read_to_string(source_path) |
| 484 |
.map_err(|e| format!("Failed to read {}: {}", source_path.display(), e))?; |
| 485 |
|
| 486 |
let table: toml::Table = content |
| 487 |
.parse() |
| 488 |
.map_err(|e| format!("Invalid TOML: {}", e))?; |
| 489 |
|
| 490 |
let has_colors = COLOR_SECTIONS |
| 491 |
.iter() |
| 492 |
.any(|s| table.get(*s).and_then(|v| v.as_table()).is_some()); |
| 493 |
if !has_colors { |
| 494 |
return Err(format!( |
| 495 |
"Theme file must have at least one color section ({})", |
| 496 |
COLOR_SECTIONS.join(", ") |
| 497 |
)); |
| 498 |
} |
| 499 |
|
| 500 |
let id = source_path |
| 501 |
.file_stem() |
| 502 |
.and_then(|s| s.to_str()) |
| 503 |
.ok_or("Invalid file name")? |
| 504 |
.to_string(); |
| 505 |
validate_theme_id(&id)?; |
| 506 |
|
| 507 |
std::fs::create_dir_all(custom_dir) |
| 508 |
.map_err(|e| format!("Failed to create {}: {}", custom_dir.display(), e))?; |
| 509 |
|
| 510 |
let dest = custom_dir.join(format!("{}.toml", id)); |
| 511 |
std::fs::copy(source_path, &dest) |
| 512 |
.map_err(|e| format!("Failed to copy theme: {}", e))?; |
| 513 |
|
| 514 |
Ok(parse_meta(&id, &table, true)) |
| 515 |
} |
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
|
| 520 |
|
| 521 |
pub fn delete_theme(custom_dir: &Path, id: &str) -> Result<(), String> { |
| 522 |
validate_theme_id(id)?; |
| 523 |
|
| 524 |
let path = custom_dir.join(format!("{}.toml", id)); |
| 525 |
if !path.is_file() { |
| 526 |
return Err(format!("Custom theme '{}' not found", id)); |
| 527 |
} |
| 528 |
|
| 529 |
std::fs::remove_file(&path) |
| 530 |
.map_err(|e| format!("Failed to delete {}: {}", path.display(), e)) |
| 531 |
} |
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
#[derive(Debug, Clone, Serialize)] |
| 536 |
#[serde(rename_all = "camelCase")] |
| 537 |
pub struct ThemePreview { |
| 538 |
pub meta: ThemeMeta, |
| 539 |
|
| 540 |
pub background: Option<String>, |
| 541 |
|
| 542 |
pub foreground: Option<String>, |
| 543 |
|
| 544 |
pub accent: Option<String>, |
| 545 |
|
| 546 |
pub border: Option<String>, |
| 547 |
} |
| 548 |
|
| 549 |
fn color_at(table: &toml::Table, section: &str, key: &str) -> Option<String> { |
| 550 |
table |
| 551 |
.get(section) |
| 552 |
.and_then(|s| s.as_table()) |
| 553 |
.and_then(|s| s.get(key)) |
| 554 |
.and_then(|v| v.as_str()) |
| 555 |
.map(|s| s.to_string()) |
| 556 |
} |
| 557 |
|
| 558 |
|
| 559 |
pub fn load_theme_preview(dirs: &[(PathBuf, bool)], id: &str) -> Result<ThemePreview, String> { |
| 560 |
validate_theme_id(id)?; |
| 561 |
|
| 562 |
let (path, is_custom) = |
| 563 |
find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{}' not found", id))?; |
| 564 |
|
| 565 |
let content = std::fs::read_to_string(&path) |
| 566 |
.map_err(|e| format!("Failed to read {}: {}", path.display(), e))?; |
| 567 |
|
| 568 |
let table: toml::Table = content |
| 569 |
.parse() |
| 570 |
.map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?; |
| 571 |
|
| 572 |
Ok(ThemePreview { |
| 573 |
meta: parse_meta(id, &table, is_custom), |
| 574 |
background: color_at(&table, "surface", "page"), |
| 575 |
foreground: color_at(&table, "content", "primary"), |
| 576 |
accent: color_at(&table, "action", "primary"), |
| 577 |
border: color_at(&table, "line", "border"), |
| 578 |
}) |
| 579 |
} |
| 580 |
|
| 581 |
|
| 582 |
pub fn export_theme(dirs: &[(PathBuf, bool)], id: &str, dest_path: &Path) -> Result<(), String> { |
| 583 |
validate_theme_id(id)?; |
| 584 |
|
| 585 |
let (source, _) = |
| 586 |
find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{}' not found", id))?; |
| 587 |
|
| 588 |
std::fs::copy(&source, dest_path) |
| 589 |
.map_err(|e| format!("Failed to export theme: {}", e))?; |
| 590 |
|
| 591 |
Ok(()) |
| 592 |
} |
| 593 |
|
| 594 |
|
| 595 |
|
| 596 |
|
| 597 |
|
| 598 |
|
| 599 |
|
| 600 |
|
| 601 |
|
| 602 |
|
| 603 |
|
| 604 |
|
| 605 |
|
| 606 |
pub fn bundled_themes_dir() -> Option<PathBuf> { |
| 607 |
let themes = Path::new(env!("CARGO_MANIFEST_DIR")).join("themes"); |
| 608 |
if themes.is_dir() { Some(themes) } else { None } |
| 609 |
} |
| 610 |
|
| 611 |
#[cfg(test)] |
| 612 |
mod tests { |
| 613 |
use super::*; |
| 614 |
use std::fs; |
| 615 |
|
| 616 |
|
| 617 |
|
| 618 |
#[test] |
| 619 |
fn validate_theme_id_alphanumeric() { |
| 620 |
assert!(validate_theme_id("darkmode").is_ok()); |
| 621 |
assert!(validate_theme_id("Theme123").is_ok()); |
| 622 |
} |
| 623 |
|
| 624 |
#[test] |
| 625 |
fn validate_theme_id_hyphens_underscores() { |
| 626 |
assert!(validate_theme_id("dark-mode").is_ok()); |
| 627 |
assert!(validate_theme_id("my_theme_v2").is_ok()); |
| 628 |
} |
| 629 |
|
| 630 |
#[test] |
| 631 |
fn validate_theme_id_rejects_path_traversal() { |
| 632 |
assert!(validate_theme_id("../etc/passwd").is_err()); |
| 633 |
assert!(validate_theme_id("foo/bar").is_err()); |
| 634 |
assert!(validate_theme_id("theme.toml").is_err()); |
| 635 |
} |
| 636 |
|
| 637 |
|
| 638 |
|
| 639 |
#[test] |
| 640 |
fn parse_meta_with_name_and_variant() { |
| 641 |
let table: toml::Table = "[meta]\nname = \"Nord\"\nvariant = \"light\"\n".parse().unwrap(); |
| 642 |
let meta = parse_meta("nord", &table, false); |
| 643 |
assert_eq!(meta.id, "nord"); |
| 644 |
assert_eq!(meta.name, "Nord"); |
| 645 |
assert_eq!(meta.variant, "light"); |
| 646 |
assert!(!meta.is_custom); |
| 647 |
} |
| 648 |
|
| 649 |
#[test] |
| 650 |
fn parse_meta_defaults_to_id_and_dark() { |
| 651 |
let table: toml::Table = "".parse().unwrap(); |
| 652 |
let meta = parse_meta("fallback", &table, true); |
| 653 |
assert_eq!(meta.name, "fallback"); |
| 654 |
assert_eq!(meta.variant, "dark"); |
| 655 |
assert!(meta.is_custom); |
| 656 |
} |
| 657 |
|
| 658 |
|
| 659 |
|
| 660 |
#[test] |
| 661 |
fn rgb_hex_roundtrip() { |
| 662 |
assert_eq!(Rgb::from_hex("#6196FF").unwrap(), Rgb { r: 0x61, g: 0x96, b: 0xff }); |
| 663 |
assert_eq!(Rgb::from_hex("#abc").unwrap(), Rgb { r: 0xaa, g: 0xbb, b: 0xcc }); |
| 664 |
assert_eq!(Rgb { r: 0x61, g: 0x96, b: 0xff }.to_hex(), "#6196ff"); |
| 665 |
assert!(Rgb::from_hex("not-a-color").is_none()); |
| 666 |
} |
| 667 |
|
| 668 |
#[test] |
| 669 |
fn oklab_roundtrips_within_tolerance() { |
| 670 |
for hex in ["#6196ff", "#2e3440", "#ffffff", "#000000", "#c0392b"] { |
| 671 |
let c = Rgb::from_hex(hex).unwrap(); |
| 672 |
let back = Rgb::from_oklab(c.to_oklab()); |
| 673 |
|
| 674 |
assert!((c.r as i16 - back.r as i16).abs() <= 1, "{hex} r"); |
| 675 |
assert!((c.g as i16 - back.g as i16).abs() <= 1, "{hex} g"); |
| 676 |
assert!((c.b as i16 - back.b as i16).abs() <= 1, "{hex} b"); |
| 677 |
} |
| 678 |
} |
| 679 |
|
| 680 |
#[test] |
| 681 |
fn wcag_contrast_known_pairs() { |
| 682 |
let white = Rgb { r: 255, g: 255, b: 255 }; |
| 683 |
let black = Rgb { r: 0, g: 0, b: 0 }; |
| 684 |
assert!((wcag_contrast(white, black) - 21.0).abs() < 0.01); |
| 685 |
assert!((wcag_contrast(white, white) - 1.0).abs() < 0.01); |
| 686 |
} |
| 687 |
|
| 688 |
#[test] |
| 689 |
fn readable_on_picks_by_wcag() { |
| 690 |
assert_eq!(readable_on(Rgb { r: 255, g: 255, b: 255 }), Rgb { r: 0, g: 0, b: 0 }); |
| 691 |
assert_eq!(readable_on(Rgb { r: 0, g: 0, b: 0 }), Rgb { r: 255, g: 255, b: 255 }); |
| 692 |
|
| 693 |
let action = Rgb::from_hex("#6196ff").unwrap(); |
| 694 |
assert_eq!(readable_on(action), Rgb { r: 0, g: 0, b: 0 }); |
| 695 |
} |
| 696 |
|
| 697 |
#[test] |
| 698 |
fn lighten_darken_move_oklab_lightness() { |
| 699 |
let c = Rgb::from_hex("#6196ff").unwrap(); |
| 700 |
let l0 = c.to_oklab().l; |
| 701 |
assert!(lighten(c, 0.05).to_oklab().l > l0); |
| 702 |
assert!(darken(c, 0.05).to_oklab().l < l0); |
| 703 |
} |
| 704 |
|
| 705 |
#[test] |
| 706 |
fn mix_endpoints_and_midpoint() { |
| 707 |
let a = Rgb::from_hex("#000000").unwrap(); |
| 708 |
let b = Rgb::from_hex("#6196ff").unwrap(); |
| 709 |
assert_eq!(mix(a, b, 0.0), a); |
| 710 |
assert_eq!(mix(a, b, 1.0), b); |
| 711 |
|
| 712 |
let mid = mix(a, b, 0.5).to_oklab().l; |
| 713 |
assert!(mid > a.to_oklab().l && mid < b.to_oklab().l); |
| 714 |
} |
| 715 |
|
| 716 |
|
| 717 |
|
| 718 |
fn nord_toml() -> &'static str { |
| 719 |
r##" |
| 720 |
[meta] |
| 721 |
name = "Nord" |
| 722 |
variant = "dark" |
| 723 |
|
| 724 |
[surface] |
| 725 |
page = "#2e3440" |
| 726 |
raised = "#3b4252" |
| 727 |
sunken = "#434c5e" |
| 728 |
overlay = "#3b4252" |
| 729 |
|
| 730 |
[content] |
| 731 |
primary = "#d8dee9" |
| 732 |
secondary = "#e5e9f0" |
| 733 |
muted = "#616e88" |
| 734 |
|
| 735 |
[action] |
| 736 |
primary = "#81a1c1" |
| 737 |
|
| 738 |
[status] |
| 739 |
danger = "#bf616a" |
| 740 |
success = "#a3be8c" |
| 741 |
warning = "#ebcb8b" |
| 742 |
info = "#88c0d0" |
| 743 |
|
| 744 |
[line] |
| 745 |
border = "#4c566a" |
| 746 |
|
| 747 |
[category] |
| 748 |
one = "#bf616a" |
| 749 |
two = "#a3be8c" |
| 750 |
three = "#81a1c1" |
| 751 |
four = "#ebcb8b" |
| 752 |
five = "#b48ead" |
| 753 |
six = "#88c0d0" |
| 754 |
"## |
| 755 |
} |
| 756 |
|
| 757 |
#[test] |
| 758 |
fn extract_colors_reads_intent_sections() { |
| 759 |
let table: toml::Table = nord_toml().parse().unwrap(); |
| 760 |
let colors = extract_colors(&table); |
| 761 |
assert_eq!(colors.get("surface.page").unwrap(), "#2e3440"); |
| 762 |
assert_eq!(colors.get("content.primary").unwrap(), "#d8dee9"); |
| 763 |
assert_eq!(colors.get("action.primary").unwrap(), "#81a1c1"); |
| 764 |
assert_eq!(colors.get("status.danger").unwrap(), "#bf616a"); |
| 765 |
assert_eq!(colors.get("line.border").unwrap(), "#4c566a"); |
| 766 |
assert_eq!(colors.get("category.five").unwrap(), "#b48ead"); |
| 767 |
assert_eq!(colors.len(), 19); |
| 768 |
} |
| 769 |
|
| 770 |
#[test] |
| 771 |
fn resolve_base_intents_passthrough() { |
| 772 |
let theme = parse_theme_str("nord", nord_toml(), false).unwrap(); |
| 773 |
let t = resolve(&theme); |
| 774 |
assert_eq!(t.hex("surface-page"), Some("#2e3440")); |
| 775 |
assert_eq!(t.hex("content"), Some("#d8dee9")); |
| 776 |
assert_eq!(t.hex("content-muted"), Some("#616e88")); |
| 777 |
assert_eq!(t.hex("action"), Some("#81a1c1")); |
| 778 |
assert_eq!(t.hex("danger"), Some("#bf616a")); |
| 779 |
assert_eq!(t.hex("border"), Some("#4c566a")); |
| 780 |
assert_eq!(t.hex("category-five"), Some("#b48ead")); |
| 781 |
} |
| 782 |
|
| 783 |
#[test] |
| 784 |
fn resolve_derived_intents() { |
| 785 |
let theme = parse_theme_str("nord", nord_toml(), false).unwrap(); |
| 786 |
let t = resolve(&theme); |
| 787 |
let action = Rgb::from_hex("#81a1c1").unwrap(); |
| 788 |
let page = Rgb::from_hex("#2e3440").unwrap(); |
| 789 |
let _ = page; |
| 790 |
assert_eq!(t.hex("action-hover").unwrap(), lighten(action, 0.05).to_hex()); |
| 791 |
assert_eq!(t.hex("content-on-action").unwrap(), readable_on(action).to_hex()); |
| 792 |
assert_eq!(t.hex("focus-ring"), Some("#81a1c1")); |
| 793 |
assert_eq!(t.hex("hover-surface"), Some("#434c5e")); |
| 794 |
|
| 795 |
|
| 796 |
|
| 797 |
assert!(t.hex("action-active").is_none()); |
| 798 |
assert!(t.hex("danger-surface").is_none()); |
| 799 |
assert!(t.hex("selection").is_none()); |
| 800 |
assert!(t.hex("row-stripe").is_none()); |
| 801 |
} |
| 802 |
|
| 803 |
#[test] |
| 804 |
fn resolve_overlay_is_dark_translucent_scrim() { |
| 805 |
let theme = parse_theme_str("nord", nord_toml(), false).unwrap(); |
| 806 |
let t = resolve(&theme); |
| 807 |
let overlay = t.hex("overlay").unwrap(); |
| 808 |
assert!(overlay.starts_with("rgba("), "overlay is translucent: {overlay}"); |
| 809 |
assert!(overlay.ends_with(", 0.5)")); |
| 810 |
|
| 811 |
let inner = overlay.trim_start_matches("rgba(").trim_end_matches(", 0.5)"); |
| 812 |
let parts: Vec<u8> = inner.split(", ").map(|p| p.parse().unwrap()).collect(); |
| 813 |
let scrim = Rgb { r: parts[0], g: parts[1], b: parts[2] }; |
| 814 |
assert!(scrim.to_oklab().l < 0.2, "scrim must be near-black"); |
| 815 |
} |
| 816 |
|
| 817 |
#[test] |
| 818 |
fn resolve_drops_non_hex_base_intent() { |
| 819 |
|
| 820 |
|
| 821 |
|
| 822 |
let theme = parse_theme_str( |
| 823 |
"x", |
| 824 |
"[surface]\npage = \"</style><script>alert(1)</script>\"\n[content]\nprimary = \"#111111\"\n", |
| 825 |
false, |
| 826 |
) |
| 827 |
.unwrap(); |
| 828 |
let t = resolve(&theme); |
| 829 |
assert!(t.hex("surface-page").is_none(), "non-hex base intent leaked"); |
| 830 |
assert_eq!(t.hex("content").unwrap(), "#111111"); |
| 831 |
|
| 832 |
assert!(!t.intents.values().any(|v| v.contains('<'))); |
| 833 |
} |
| 834 |
|
| 835 |
#[test] |
| 836 |
fn resolve_skips_derived_when_source_missing() { |
| 837 |
|
| 838 |
let theme = parse_theme_str( |
| 839 |
"x", |
| 840 |
"[surface]\npage = \"#000000\"\n[line]\nborder = \"#222222\"\n", |
| 841 |
false, |
| 842 |
) |
| 843 |
.unwrap(); |
| 844 |
let t = resolve(&theme); |
| 845 |
assert!(t.hex("action").is_none()); |
| 846 |
assert!(t.hex("action-hover").is_none()); |
| 847 |
assert!(t.hex("selection").is_none()); |
| 848 |
assert_eq!(t.hex("border-strong").unwrap(), darken(Rgb::from_hex("#222222").unwrap(), 0.05).to_hex()); |
| 849 |
} |
| 850 |
|
| 851 |
#[test] |
| 852 |
fn rgb_accessor_for_native_consumers() { |
| 853 |
let theme = parse_theme_str("nord", nord_toml(), false).unwrap(); |
| 854 |
let t = resolve(&theme); |
| 855 |
assert_eq!(t.rgb("action"), Some((0x81, 0xa1, 0xc1))); |
| 856 |
assert_eq!(t.rgb("nonexistent"), None); |
| 857 |
} |
| 858 |
|
| 859 |
|
| 860 |
|
| 861 |
#[test] |
| 862 |
fn intent_css_vars_wraps_root_and_includes_tokens() { |
| 863 |
let theme = parse_theme_str("nord", nord_toml(), false).unwrap(); |
| 864 |
let css = intent_css_vars(&resolve(&theme)); |
| 865 |
assert!(css.starts_with(":root {\n")); |
| 866 |
assert!(css.contains(" --surface-page: #2e3440;\n")); |
| 867 |
assert!(css.contains(" --danger: #bf616a;\n")); |
| 868 |
assert!(css.contains(" --action-hover: ")); |
| 869 |
assert!(css.trim_end().ends_with('}')); |
| 870 |
} |
| 871 |
|
| 872 |
|
| 873 |
|
| 874 |
#[test] |
| 875 |
fn load_and_resolve_round_trip() { |
| 876 |
let dir = tempfile::tempdir().unwrap(); |
| 877 |
fs::write(dir.path().join("nord.toml"), nord_toml()).unwrap(); |
| 878 |
let dirs = vec![(dir.path().to_path_buf(), false)]; |
| 879 |
let t = load_semantic(&dirs, "nord").unwrap(); |
| 880 |
assert_eq!(t.meta.name, "Nord"); |
| 881 |
assert_eq!(t.hex("action"), Some("#81a1c1")); |
| 882 |
} |
| 883 |
|
| 884 |
#[test] |
| 885 |
fn load_theme_rejects_invalid_id() { |
| 886 |
assert!(load_theme(&[], "../evil").is_err()); |
| 887 |
} |
| 888 |
|
| 889 |
#[test] |
| 890 |
fn list_themes_from_dirs_finds_toml_files() { |
| 891 |
let dir = tempfile::tempdir().unwrap(); |
| 892 |
fs::write(dir.path().join("t.toml"), "[meta]\nname = \"T\"\n").unwrap(); |
| 893 |
fs::write(dir.path().join("x.txt"), "ignored").unwrap(); |
| 894 |
let dirs = vec![(dir.path().to_path_buf(), false)]; |
| 895 |
let themes = list_themes_from_dirs(&dirs); |
| 896 |
assert_eq!(themes.len(), 1); |
| 897 |
assert_eq!(themes[0].id, "t"); |
| 898 |
} |
| 899 |
|
| 900 |
#[test] |
| 901 |
fn find_theme_path_reverse_priority() { |
| 902 |
let d1 = tempfile::tempdir().unwrap(); |
| 903 |
let d2 = tempfile::tempdir().unwrap(); |
| 904 |
fs::write(d1.path().join("s.toml"), "[meta]\n").unwrap(); |
| 905 |
fs::write(d2.path().join("s.toml"), "[meta]\n").unwrap(); |
| 906 |
let dirs = vec![(d1.path().to_path_buf(), false), (d2.path().to_path_buf(), true)]; |
| 907 |
let (path, is_custom) = find_theme_path(&dirs, "s").unwrap(); |
| 908 |
assert!(is_custom); |
| 909 |
assert_eq!(path, d2.path().join("s.toml")); |
| 910 |
} |
| 911 |
|
| 912 |
#[test] |
| 913 |
fn import_theme_valid_and_rejects_empty() { |
| 914 |
let src_dir = tempfile::tempdir().unwrap(); |
| 915 |
let custom_dir = tempfile::tempdir().unwrap(); |
| 916 |
|
| 917 |
let good = src_dir.path().join("my-theme.toml"); |
| 918 |
fs::write(&good, "[surface]\npage = \"#1a1b26\"\n").unwrap(); |
| 919 |
let meta = import_theme(&good, custom_dir.path()).unwrap(); |
| 920 |
assert_eq!(meta.id, "my-theme"); |
| 921 |
assert!(custom_dir.path().join("my-theme.toml").exists()); |
| 922 |
|
| 923 |
let empty = src_dir.path().join("empty.toml"); |
| 924 |
fs::write(&empty, "[meta]\nname = \"E\"\n").unwrap(); |
| 925 |
assert!(import_theme(&empty, custom_dir.path()).is_err()); |
| 926 |
} |
| 927 |
|
| 928 |
#[test] |
| 929 |
fn import_theme_rejects_invalid_toml() { |
| 930 |
let src_dir = tempfile::tempdir().unwrap(); |
| 931 |
let custom_dir = tempfile::tempdir().unwrap(); |
| 932 |
let src = src_dir.path().join("bad.toml"); |
| 933 |
fs::write(&src, "this is not [valid toml [[[").unwrap(); |
| 934 |
assert!(import_theme(&src, custom_dir.path()).is_err()); |
| 935 |
} |
| 936 |
|
| 937 |
#[test] |
| 938 |
fn delete_theme_removes_and_guards() { |
| 939 |
let custom = tempfile::tempdir().unwrap(); |
| 940 |
let path = custom.path().join("doomed.toml"); |
| 941 |
fs::write(&path, "[surface]\npage = \"#000\"\n").unwrap(); |
| 942 |
delete_theme(custom.path(), "doomed").unwrap(); |
| 943 |
assert!(!path.exists()); |
| 944 |
assert!(delete_theme(custom.path(), "../etc/passwd").is_err()); |
| 945 |
assert!(delete_theme(custom.path(), "ghost").is_err()); |
| 946 |
} |
| 947 |
|
| 948 |
#[test] |
| 949 |
fn export_theme_copies_file() { |
| 950 |
let src_dir = tempfile::tempdir().unwrap(); |
| 951 |
let dest_dir = tempfile::tempdir().unwrap(); |
| 952 |
let content = "[meta]\nname = \"E\"\n[surface]\npage = \"#ffffff\"\n"; |
| 953 |
fs::write(src_dir.path().join("e.toml"), content).unwrap(); |
| 954 |
let dirs = vec![(src_dir.path().to_path_buf(), false)]; |
| 955 |
let dest = dest_dir.path().join("out.toml"); |
| 956 |
export_theme(&dirs, "e", &dest).unwrap(); |
| 957 |
assert_eq!(fs::read_to_string(&dest).unwrap(), content); |
| 958 |
assert!(export_theme(&dirs, "missing", &dest).is_err()); |
| 959 |
} |
| 960 |
|
| 961 |
#[test] |
| 962 |
fn load_theme_preview_returns_role_swatches() { |
| 963 |
let dir = tempfile::tempdir().unwrap(); |
| 964 |
fs::write(dir.path().join("nord.toml"), nord_toml()).unwrap(); |
| 965 |
let dirs = vec![(dir.path().to_path_buf(), false)]; |
| 966 |
let p = load_theme_preview(&dirs, "nord").unwrap(); |
| 967 |
assert_eq!(p.background.as_deref(), Some("#2e3440")); |
| 968 |
assert_eq!(p.foreground.as_deref(), Some("#d8dee9")); |
| 969 |
assert_eq!(p.accent.as_deref(), Some("#81a1c1")); |
| 970 |
assert_eq!(p.border.as_deref(), Some("#4c566a")); |
| 971 |
} |
| 972 |
|
| 973 |
#[test] |
| 974 |
fn bundled_themes_dir_resolves_to_shipped_themes() { |
| 975 |
|
| 976 |
|
| 977 |
let dir = bundled_themes_dir().expect("makeover ships a themes/ directory"); |
| 978 |
assert!(dir.join("akari-dawn.toml").is_file()); |
| 979 |
assert!(dir.join("akari-night.toml").is_file()); |
| 980 |
} |
| 981 |
|
| 982 |
#[test] |
| 983 |
fn every_shipped_theme_loads() { |
| 984 |
|
| 985 |
|
| 986 |
|
| 987 |
let dir = bundled_themes_dir().unwrap(); |
| 988 |
let dirs = vec![(dir.clone(), false)]; |
| 989 |
let themes = list_themes_from_dirs(&dirs); |
| 990 |
assert!(themes.len() >= 30, "expected the full theme set, got {}", themes.len()); |
| 991 |
for meta in &themes { |
| 992 |
load_theme(&dirs, &meta.id) |
| 993 |
.unwrap_or_else(|e| panic!("shipped theme `{}` failed to load: {e}", meta.id)); |
| 994 |
} |
| 995 |
} |
| 996 |
} |
| 997 |
|