//! Discovers, migrates and resolves themes for the TUI and mini. use std::borrow::Cow; use std::sync::{LazyLock, OnceLock}; use indexmap::{IndexMap, IndexSet}; use serde::Deserialize; use serde_json::Value; use serde_json::value::RawValue; use super::document::{decode, modes}; use super::{Theme, ThemeMode, resolve, v1, v1_new}; /// A built-in theme: its document stays raw JSON until the theme is first loaded, so startup parses only the one in /// use. #[derive(Deserialize)] struct Builtin { name: &'static str, #[serde(rename = "document")] raw: &'static RawValue, #[serde(skip)] document: OnceLock, /// A V1 theme's `migrateV1` document, which mini uses. #[serde(rename = "mini")] mini_raw: Option<&'static RawValue>, #[serde(skip)] mini: OnceLock, } impl Builtin { fn document(&self, mini: bool) -> &Value { let (raw, document) = match self.mini_raw { Some(raw) if mini => (raw, &self.mini), _ => (self.raw, &self.document), }; document.get_or_init(|| serde_json::from_str(raw.get()).expect("generated/themes.json is valid")) } } #[derive(Deserialize)] #[serde(bound(deserialize = "'de: 'static"))] struct Builtins { themes: Vec, } static BUILTINS: LazyLock = LazyLock::new(|| { serde_json::from_str(include_str!("generated/themes.json")).expect("generated/themes.json is valid") }); /// Where a theme comes from. #[derive(Clone, Copy, Debug)] pub enum ThemeSource<'a> { /// A built-in document, already in V2 form. Builtin(&'static Value), /// A custom file or the generated `system` theme: V1 (`{ theme }`) or V2 (`{ base, light, dark }`). Custom(&'a Value), } /// A theme resolved in a mode: the modes it supports and the one it resolved in. #[derive(Clone, Debug)] pub struct Loaded { pub modes: Vec, pub mode: ThemeMode, pub theme: Theme, } /// The built-in themes plus the custom and `system` themes currently known. #[derive(Clone, Debug, Default)] pub struct Catalog { custom: IndexMap, system: Option, mini: bool, } impl Catalog { /// Mini resolves V1 themes with the legacy color mapping. pub fn mini() -> Self { Self { mini: true, ..Self::default() } } /// Replaces the custom themes; values that are not theme documents are dropped (`setCustomThemes`). pub fn set_custom(&mut self, themes: IndexMap) { self.custom = themes.into_iter().filter(|(_, source)| is_theme_source(source)).collect(); } /// Adds or replaces custom theme `name`, when `source` is a theme document. pub fn add_custom(&mut self, name: &str, source: Value) { if is_theme_source(&source) { self.custom.insert(name.to_owned(), source); } } /// The generated `system` theme, or `None` to fall back to a custom `system` theme or `opencode`. pub fn set_system(&mut self, source: Option) { self.system = source; } /// Theme names in list order: the built-ins (`opencode` and `opencode-classic` after the V1 defaults), custom themes /// not named like a built-in, then `system`. pub fn names(&self) -> Vec { let mut names = IndexSet::new(); names.extend(BUILTINS.themes.iter().map(|theme| theme.name.to_owned())); names.extend(self.custom.keys().cloned()); names.insert("system".to_owned()); names.into_iter().collect() } pub fn has(&self, name: &str) -> bool { !name.is_empty() && self.source(name).is_some() } pub fn source(&self, name: &str) -> Option> { if name == "system" { let system = self.system.as_ref().or_else(|| self.custom.get("system")); return system.map(ThemeSource::Custom).or_else(|| self.source("opencode")); } if let Some(custom) = self.custom.get(name) { return Some(ThemeSource::Custom(custom)); } let builtin = BUILTINS.themes.iter().find(|theme| theme.name == name)?; Some(ThemeSource::Builtin(builtin.document(self.mini))) } /// `loadTheme`: the theme `name` in `mode`, or in its first mode when it lacks `mode`. pub fn load(&self, name: &str, mode: ThemeMode) -> Result { let source = self.source(name).ok_or_else(|| format!("Theme \"{name}\" was not found"))?; let document = parse(source, name, self.mini)?; let modes = modes(&document); let requested = if modes.contains(&mode) { mode } else { modes.first().copied().unwrap_or(mode) }; let (theme, mode) = resolve(&document, requested)?; Ok(Loaded { modes, mode, theme }) } } /// `isThemeSource`: an object with `theme` (V1) or `base` (V2). pub fn is_theme_source(source: &Value) -> bool { source.as_object().is_some_and(|object| object.contains_key("theme") || object.contains_key("base")) } /// `parseTheme`: V1 sources migrate, V2 sources pass the schema and must resolve in every mode they define. fn parse<'a>(source: ThemeSource<'a>, name: &str, mini: bool) -> Result, String> { let source = match source { ThemeSource::Builtin(document) => return Ok(Cow::Borrowed(document)), ThemeSource::Custom(source) => source, }; if source.get("theme").is_some() { let migrated = if mini { v1::migrate(source) } else { v1_new::migrate(source) }; return migrated.map(Cow::Owned); } let document = decode(source).map_err(|issue| invalid(name, &issue.value()))?; for mode in modes(&document) { resolve(&document, mode).map_err(|_| invalid(name, "value"))?; } Ok(Cow::Owned(document)) } /// `themeDecodeError`'s message. fn invalid(name: &str, value: &str) -> String { format!("Invalid theme: {name} {value} is an invalid value") }