SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Theme files: options, overlays and requires (#8876) (#9805)
Nathan Daneca005237a16f
diff --git a/crates/ui-egui/src/theme_files.rs b/crates/ui-egui/src/theme_files.rsindex 871db47332..b05f4c428e 100644--- a/crates/ui-egui/src/theme_files.rs+++ b/crates/ui-egui/src/theme_files.rs@@ -68,9 +68,9 @@ impl Base {}}-/// A theme: its id (the `theme` preference's value), name, base, optional radii and colour overrides, each a-/// `#rrggbb` / `#rrggbbaa` string or a list of them, keyed by [`keys`].-#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+/// A theme: identity, base value tables and optional declarations selecting literal overlays.+/// Colour overrides are `#rrggbb` / `#rrggbbaa` strings or lists, keyed by [`keys`].+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]pub struct ThemeFile {pub id: String,pub name: String,@@ -85,6 +85,160 @@ pub struct ThemeFile {/// SVG display roles and three-colour semantic ramps; omitted values keep compiled defaults.#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]pub icon_palette: BTreeMap<String, Value>,+ /// Theme-owned declarations, in file order; standard ids are normalized on import.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub options: Vec<OptionDef>,+ /// Conditional value tables, applied in file order with later entries winning by key.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub overlays: Vec<Overlay>,+ /// Levels newer than [`REQUIREMENTS_LEVEL`] disable options and overlays.+ #[serde(default = "requirements_level", skip_serializing_if = "is_current_level")]+ pub requires: u64,+}++/// Theme option/overlay format level understood by this app.+pub const REQUIREMENTS_LEVEL: u64 = 1;+pub const MAX_OPTIONS: usize = 16;+pub const MAX_OVERLAYS: usize = 32;+const STANDARD_OPTIONS: [&str; 4] = ["opacity", "blur", "tab_colours", "tab_fade_ms"];++fn requirements_level() -> u64 {+ REQUIREMENTS_LEVEL+}++fn is_current_level(level: &u64) -> bool {+ *level == REQUIREMENTS_LEVEL+}++impl Default for ThemeFile {+ fn default() -> Self {+ Self {+ id: String::new(),+ name: String::new(),+ base: Base::default(),+ colors: BTreeMap::new(),+ radii: BTreeMap::new(),+ borders: BTreeMap::new(),+ icon_palette: BTreeMap::new(),+ options: Vec::new(),+ overlays: Vec::new(),+ requires: REQUIREMENTS_LEVEL,+ }+ }+}++/// Saved option values use the same JSON primitives as defaults and comparisons.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(untagged)]+pub enum OptionValue {+ Bool(bool),+ Choice(String),+ Num(f32),+}++/// Localized text belongs to the theme, with English as the fallback.+pub type OptionText = BTreeMap<String, String>;++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct ChoiceValue {+ pub id: String,+ pub label: OptionText,+}++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(tag = "type", rename_all = "lowercase")]+pub enum OptionKind {+ Bool {+ default: bool,+ },+ Choice {+ default: String,+ values: Vec<ChoiceValue>,+ },+ Range {+ default: f32,+ min: f32,+ max: f32,+ step: f32,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ unit: Option<String>,+ },+}++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct OptionDef {+ pub id: String,+ #[serde(flatten)]+ pub kind: OptionKind,+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub label: OptionText,+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub help: OptionText,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub parent: Option<String>,+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub advanced: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub section: Option<String>,+}++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(untagged)]+pub enum Condition {+ Eq {+ opt: String,+ eq: OptionValue,+ },+ Range {+ opt: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ gte: Option<f32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ lte: Option<f32>,+ },+}++impl Condition {+ fn option(&self) -> &str {+ match self {+ Self::Eq { opt, .. } | Self::Range { opt, .. } => opt,+ }+ }+}++/// Overlay tables have exactly the same keys and bounds as the theme's base tables.+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+pub struct ThemeLayer {+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub colors: BTreeMap<String, Value>,+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub radii: BTreeMap<String, u8>,+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub borders: BTreeMap<String, Value>,+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub icon_palette: BTreeMap<String, Value>,+}++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct Overlay {+ pub when: Condition,+ #[serde(flatten)]+ pub values: ThemeLayer,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum OptionNoticeKind {+ UnknownOption,+ WrongType,+ UnknownChoice,+ NonFinite,+ Clamped,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct OptionNotice {+ pub id: String,+ pub kind: OptionNoticeKind,}/// Maximum imported radius, in logical UI points; widgets clamp to their own bounds.@@ -104,6 +258,12 @@ fn radius_slot<'a>(t: &'a mut Tokens, key: &str) -> Option<&'a mut u8> {}impl ThemeFile {+ /// A newer format level keeps the authored base tables but disables options and overlays.+ /// Computed from `requires` so it also works after restoring saved preferences.+ pub fn needs_newer(&self) -> bool {+ self.requires > REQUIREMENTS_LEVEL+ }+/// Validate direct control-channel preference updates as strictly as file imports.pub(crate) fn validate_radii(&self) -> Result<(), String> {for (key, value) in &self.radii {@@ -367,7 +527,8 @@ fn colors_for_key(key: &str, value: &Value, len: usize) -> Result<Vec<Color32>,}/// A theme file's text, checked: the format tag, a name, a base and only known keys with valid-/// colours and bounded radii. Nothing is taken from a file with any error; the message names every bad key.+/// colours, bounded shapes, option definitions and overlay comparisons. Nothing is taken from a+/// supported-level file with any error; messages name the offending key and overlay position.pub fn parse(text: &str) -> Result<ThemeFile, String> {if text.len() > MAX_BYTES {return Err(format!("a theme file is at most {} KiB", MAX_BYTES / 1024));@@ -390,6 +551,28 @@ pub fn from_value(v: &Value) -> Result<ThemeFile, String> {Some("light") => Base::Light,_ => return Err("`base` must be \"dark\" or \"light\"".into()),};+ let requires = match v.get("requires") {+ None => REQUIREMENTS_LEVEL,+ Some(value) => value.as_u64().ok_or("`requires` must be a nonnegative integer")?,+ };+ let layer = parse_layer(v)?;+ let options = if requires > REQUIREMENTS_LEVEL { Vec::new() } else { parse_options(v.get("options"))? };+ let overlays = if requires > REQUIREMENTS_LEVEL { Vec::new() } else { parse_overlays(v.get("overlays"), &options)? };+ Ok(ThemeFile {+ id: slug(name),+ name: name.to_string(),+ base,+ colors: layer.colors,+ radii: layer.radii,+ borders: layer.borders,+ icon_palette: layer.icon_palette,+ options,+ overlays,+ requires,+ })+}++fn parse_layer(v: &Value) -> Result<ThemeLayer, String> {let mut src = match v.get("colors") {None => serde_json::Map::new(),Some(Value::Object(o)) => o.clone(),@@ -453,7 +636,222 @@ pub fn from_value(v: &Value) -> Result<ThemeFile, String> {Some(_) => return Err("`icon_palette` must be an object of SVG roles and ramps".into()),};parse_icon_palette(&icon_palette)?;- Ok(ThemeFile { id: slug(name), name: name.to_string(), base, colors: src.into_iter().collect(), radii, borders, icon_palette })+ Ok(ThemeLayer { colors: src.into_iter().collect(), radii, borders, icon_palette })+}++fn valid_option_id(id: &str) -> bool {+ (1..=32).contains(&id.len())+ && id.bytes().next().is_some_and(|b| b.is_ascii_lowercase())+ && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')+}++fn option_number(v: &Value, key: &str) -> Result<f32, String> {+ v.get(key)+ .and_then(Value::as_f64)+ .map(|n| n as f32)+ .filter(|n| n.is_finite())+ .ok_or_else(|| format!("`{key}` must be a finite number representable as f32"))+}++fn option_text(v: Option<&Value>, key: &str, max: usize) -> Result<OptionText, String> {+ let Some(v) = v else { return Ok(BTreeMap::new()) };+ let obj = v.as_object().ok_or_else(|| format!("`{key}` must be a map of language codes to strings"))?;+ if obj.len() > 64 {+ return Err(format!("`{key}` has more than 64 languages"));+ }+ obj.iter()+ .map(|(language, value)| {+ if language.is_empty() || language.len() > 32 || !language.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {+ return Err(format!("`{key}` has an invalid language code"));+ }+ let text = value+ .as_str()+ .filter(|s| s.chars().count() <= max)+ .ok_or_else(|| format!("`{key}.{language}` must be a string of at most {max} characters"))?;+ Ok((language.clone(), text.into()))+ })+ .collect()+}++fn parse_option(v: &Value) -> Result<OptionDef, String> {+ let id = v.get("id").and_then(Value::as_str).filter(|id| valid_option_id(id)).ok_or("`id` must match [a-z][a-z0-9_]{0,31}")?;+ let kind = v.get("type").and_then(Value::as_str).ok_or("`type` must be bool, choice or range")?;+ let reserved = STANDARD_OPTIONS.contains(&id);+ let kind = if id == "tab_colours" || (!reserved && kind == "bool") {+ if kind != "bool" {+ return Err(format!("`{id}.type` must be bool"));+ }+ OptionKind::Bool { default: v.get("default").and_then(Value::as_bool).ok_or("`default` must be bool")? }+ } else if reserved || kind == "range" {+ if kind != "range" {+ return Err(format!("`{id}.type` must be range"));+ }+ let (floor, ceiling, standard_unit) = match id {+ "opacity" => (40.0, 100.0, Some("%")),+ "blur" => (0.0, 40.0, Some("px")),+ "tab_fade_ms" => (0.0, 600.0, Some("ms")),+ _ => (0.0, 0.0, None),+ };+ let min = if reserved && v.get("min").is_none() { floor } else { option_number(v, "min")? };+ let max = if reserved && v.get("max").is_none() { ceiling } else { option_number(v, "max")? };+ if min > max {+ return Err("`min` must not exceed `max`".into());+ }+ if reserved && (min < floor || max > ceiling) {+ return Err(format!("`min` / `max` for {id} must stay inside {floor} to {ceiling}"));+ }+ let step = if reserved { 1.0 } else { option_number(v, "step")? };+ if step <= 0.0 {+ return Err("`step` must be greater than zero".into());+ }+ let default = option_number(v, "default")?;+ let default = if reserved {+ default.clamp(min, max)+ } else {+ if default < min || default > max {+ return Err("`default` must be inside `min` / `max`".into());+ }+ default+ };+ let unit = if reserved {+ standard_unit.map(str::to_string)+ } else {+ v.get("unit")+ .map(|v| v.as_str().filter(|s| s.chars().count() <= 4).map(str::to_string).ok_or("`unit` must be a string of at most 4 characters"))+ .transpose()?+ };+ OptionKind::Range { default, min, max, step, unit }+ } else if kind == "choice" {+ let values = v.get("values").and_then(Value::as_array).filter(|v| (2..=12).contains(&v.len())).ok_or("`values` must have 2 to 12 choices")?;+ let mut ids = std::collections::BTreeSet::new();+ let mut choices = Vec::new();+ for value in values {+ let id = value.get("id").and_then(Value::as_str).filter(|id| valid_option_id(id)).ok_or("`values.id` must match [a-z][a-z0-9_]{0,31}")?;+ if !ids.insert(id) {+ return Err(format!("`values.id` duplicates {id}"));+ }+ let label = option_text(Some(value.get("label").ok_or("`values.label` is required")?), "values.label", 40)?;+ choices.push(ChoiceValue { id: id.into(), label });+ }+ let default = v.get("default").and_then(Value::as_str).filter(|id| ids.contains(id)).ok_or("`default` must name an id in `values`")?;+ OptionKind::Choice { default: default.into(), values: choices }+ } else {+ return Err("`type` must be bool, choice or range".into());+ };+ // Standard definitions are app-owned: even malformed presentation fields are ignored.+ if reserved {+ return Ok(OptionDef {+ id: id.into(),+ kind,+ label: BTreeMap::new(),+ help: BTreeMap::new(),+ parent: (id == "tab_fade_ms").then(|| "tab_colours".into()),+ advanced: false,+ section: None,+ });+ }+ let parent = v+ .get("parent")+ .map(|v| v.as_str().filter(|id| valid_option_id(id)).map(str::to_string).ok_or("`parent` must be an option id"))+ .transpose()?;+ let advanced = v.get("advanced").map(|v| v.as_bool().ok_or("`advanced` must be bool")).transpose()?.unwrap_or(false);+ let section = v+ .get("section")+ .map(|v| v.as_str().filter(|s| s.chars().count() <= 24).map(str::to_string).ok_or("`section` must be a string of at most 24 characters"))+ .transpose()?;+ Ok(OptionDef {+ id: id.into(),+ kind,+ label: option_text(v.get("label"), "label", 40)?,+ help: option_text(v.get("help"), "help", 160)?,+ parent,+ advanced,+ section,+ })+}++fn parse_options(v: Option<&Value>) -> Result<Vec<OptionDef>, String> {+ let Some(v) = v else { return Ok(Vec::new()) };+ let values = v.as_array().filter(|v| v.len() <= MAX_OPTIONS).ok_or("`options` must be an array of at most 16 entries")?;+ let mut options = Vec::new();+ let mut ids = std::collections::BTreeSet::new();+ for (position, value) in values.iter().enumerate() {+ let option = parse_option(value).map_err(|e| format!("`options[{}]`: {e}", position + 1))?;+ if !ids.insert(option.id.clone()) {+ return Err(format!("`options.id` duplicates {}", option.id));+ }+ options.push(option);+ }+ let mut parents = std::collections::BTreeSet::new();+ for option in &options {+ if let Some(parent) = &option.parent {+ if !options.iter().any(|o| &o.id == parent && matches!(o.kind, OptionKind::Bool { .. })) {+ return Err(format!("`options.{}.parent` must name a bool option", option.id));+ }+ if !parents.insert(parent) {+ return Err(format!("`options.parent` {parent} has more than one child"));+ }+ let mut ancestor = Some(parent.as_str());+ for _ in 0..=MAX_OPTIONS {+ let Some(id) = ancestor else { break };+ if id == option.id {+ return Err(format!("`options.{}.parent` forms a cycle", option.id));+ }+ ancestor = options.iter().find(|o| o.id == id).and_then(|o| o.parent.as_deref());+ }+ }+ }+ Ok(options)+}++fn parse_condition(v: &Value, options: &[OptionDef]) -> Result<Condition, String> {+ let obj = v.as_object().ok_or("`when` must be an object")?;+ let opt = v.get("opt").and_then(Value::as_str).ok_or("`when.opt` must be an option id")?;+ let option = options.iter().find(|o| o.id == opt).ok_or_else(|| format!("`when.opt` names unknown option {opt}"))?;+ if let Some(eq) = v.get("eq") {+ if obj.len() != 2 {+ return Err("`when.eq` cannot be combined with other comparisons".into());+ }+ let eq = match &option.kind {+ OptionKind::Bool { .. } => OptionValue::Bool(eq.as_bool().ok_or("`when.eq` must be bool")?),+ OptionKind::Choice { values, .. } => OptionValue::Choice(+ eq.as_str().filter(|id| values.iter().any(|v| v.id == *id)).ok_or("`when.eq` must name a choice in `values`")?.into(),+ ),+ OptionKind::Range { .. } => OptionValue::Num(option_number(v, "eq").map_err(|e| format!("`when`: {e}"))?),+ };+ return Ok(Condition::Eq { opt: opt.into(), eq });+ }+ if !matches!(option.kind, OptionKind::Range { .. }) {+ return Err("`when.gte` / `when.lte` require a range option".into());+ }+ if obj.keys().any(|k| !matches!(k.as_str(), "opt" | "gte" | "lte")) {+ return Err("`when` has an unknown comparison".into());+ }+ let bound = |key| v.get(key).map(|_| option_number(v, key).map_err(|e| format!("`when`: {e}"))).transpose();+ let (gte, lte) = (bound("gte")?, bound("lte")?);+ if gte.is_none() && lte.is_none() {+ return Err("`when` needs eq, gte or lte".into());+ }+ if matches!((gte, lte), (Some(a), Some(b)) if a > b) {+ return Err("`when.gte` must not exceed `when.lte`".into());+ }+ Ok(Condition::Range { opt: opt.into(), gte, lte })+}++fn parse_overlays(v: Option<&Value>, options: &[OptionDef]) -> Result<Vec<Overlay>, String> {+ let Some(v) = v else { return Ok(Vec::new()) };+ let values = v.as_array().filter(|v| v.len() <= MAX_OVERLAYS).ok_or("`overlays` must be an array of at most 32 entries")?;+ values+ .iter()+ .enumerate()+ .map(|(position, value)| {+ let parse = || {+ let when = parse_condition(value.get("when").ok_or("`when` is required")?, options)?;+ Ok(Overlay { when, values: parse_layer(value)? })+ };+ parse().map_err(|e: String| format!("`overlays[{}]`: {e}", position + 1))+ })+ .collect()}/// An id from a name: lower-case letters, digits and dashes.@@ -470,9 +868,155 @@ fn slug(name: &str) -> String {if s.is_empty() { "theme".into() } else { s }}-/// The theme's tokens: its base with its colours and radii on top. A colour the saved preferences hold-/// that this version can't read (a hand edit) is skipped, never an error.+/// Definitions from hand-edited preferences get the same bounds and reserved-id normalization+/// as imports. An invalid definition list cannot drive an overlay.+fn usable_options(theme: &ThemeFile) -> Vec<OptionDef> {+ if theme.needs_newer() || theme.options.len() > MAX_OPTIONS {+ return Vec::new();+ }+ serde_json::to_value(&theme.options).ok().and_then(|v| parse_options(Some(&v)).ok()).unwrap_or_default()+}++impl OptionDef {+ pub fn default_value(&self) -> OptionValue {+ match &self.kind {+ OptionKind::Bool { default } => OptionValue::Bool(*default),+ OptionKind::Choice { default, .. } => OptionValue::Choice(default.clone()),+ OptionKind::Range { default, .. } => OptionValue::Num(*default),+ }+ }+}++/// Values for every declared option. Missing values use defaults without a notice; invalid saved+/// values use defaults and report why. Unknown ids are omitted (there is no definition/default).+/// Range values are clamped, without rounding to `step`. Inactive children retain their values.+pub fn effective_values(theme: &ThemeFile, saved: &BTreeMap<String, OptionValue>) -> (BTreeMap<String, OptionValue>, Vec<OptionNotice>) {+ let options = usable_options(theme);+ let mut values: BTreeMap<_, _> = options.iter().map(|o| (o.id.clone(), o.default_value())).collect();+ let mut notices = Vec::new();+ for (id, saved) in saved {+ let Some(option) = options.iter().find(|o| &o.id == id) else {+ notices.push(OptionNotice { id: id.clone(), kind: OptionNoticeKind::UnknownOption });+ continue;+ };+ let mut notice = None;+ let value = match (&option.kind, saved) {+ (OptionKind::Bool { .. }, OptionValue::Bool(_)) => saved.clone(),+ (OptionKind::Choice { values, .. }, OptionValue::Choice(id)) if values.iter().any(|v| &v.id == id) => saved.clone(),+ (OptionKind::Choice { .. }, OptionValue::Choice(_)) => {+ notice = Some(OptionNoticeKind::UnknownChoice);+ option.default_value()+ }+ (OptionKind::Range { min, max, .. }, OptionValue::Num(n)) if n.is_finite() => {+ let clamped = n.clamp(*min, *max);+ if clamped != *n {+ notice = Some(OptionNoticeKind::Clamped);+ }+ OptionValue::Num(clamped)+ }+ (OptionKind::Range { .. }, OptionValue::Num(_)) => {+ notice = Some(OptionNoticeKind::NonFinite);+ option.default_value()+ }+ _ => {+ notice = Some(OptionNoticeKind::WrongType);+ option.default_value()+ }+ };+ values.insert(id.clone(), value);+ if let Some(kind) = notice {+ notices.push(OptionNotice { id: id.clone(), kind });+ }+ }+ (values, notices)+}++/// Standard options in the app's fixed order, each followed by its declared child, then custom+/// options in file order. Each definition appears once. No undeclared standard option is added.+pub fn ordered_options(theme: &ThemeFile) -> Vec<&OptionDef> {+ if theme.needs_newer() {+ return Vec::new();+ }+ let options = theme.options.get(..theme.options.len().min(MAX_OPTIONS)).unwrap_or_default();+ let mut ordered: Vec<&OptionDef> = Vec::new();+ for id in ["opacity", "blur", "tab_colours"] {+ let mut next = options.iter().find(|o| o.id == id);+ for _ in 0..MAX_OPTIONS {+ let Some(option) = next else { break };+ if ordered.iter().any(|o| o.id == option.id) {+ break;+ }+ ordered.push(option);+ next = options.iter().find(|o| o.parent.as_deref() == Some(option.id.as_str()));+ }+ }+ for option in options {+ if !ordered.iter().any(|o| o.id == option.id) {+ ordered.push(option);+ }+ }+ ordered+}++fn option_active(id: &str, options: &[OptionDef], values: &BTreeMap<String, OptionValue>) -> bool {+ let mut current = id;+ for _ in 0..=MAX_OPTIONS {+ let Some(option) = options.iter().find(|o| o.id == current) else { return false };+ let Some(parent) = option.parent.as_deref() else { return true };+ if values.get(parent) != Some(&OptionValue::Bool(true)) {+ return false;+ }+ current = parent;+ }+ false+}++fn condition_matches(condition: &Condition, values: &BTreeMap<String, OptionValue>) -> bool {+ match condition {+ Condition::Eq { opt, eq } => values.get(opt) == Some(eq),+ Condition::Range { opt, gte, lte } => matches!(values.get(opt), Some(OptionValue::Num(n))+ if n.is_finite() && gte.is_none_or(|a| *n >= a) && lte.is_none_or(|b| *n <= b)),+ }+}++/// Resolve at declared defaults. Files without options retain the original palette exactly.pub fn resolve(theme: &ThemeFile) -> Tokens {+ resolve_with(theme, &BTreeMap::new())+}++/// Resolve base tables, then matching overlays in file order. Later tables replace earlier+/// entries by key. Saved values are normalized here too, so callers cannot bypass finite checks.+pub fn resolve_with(theme: &ThemeFile, saved: &BTreeMap<String, OptionValue>) -> Tokens {+ if theme.needs_newer() || theme.overlays.is_empty() || theme.overlays.len() > MAX_OVERLAYS {+ return resolve_base(theme);+ }+ let options = usable_options(theme);+ let overlays = serde_json::to_value(&theme.overlays).ok().and_then(|v| parse_overlays(Some(&v), &options).ok()).unwrap_or_default();+ let (values, _) = effective_values(theme, saved);+ let mut merged = theme.clone();+ for overlay in overlays {+ if !option_active(overlay.when.option(), &options, &values) || !condition_matches(&overlay.when, &values) {+ continue;+ }+ // Legacy axis lists are local to a layer: an overlay's triad must override axes in+ // the base, while explicit axis keys in that same overlay still win over its triad.+ for key in LEGACY_AXES {+ if let Some(Value::Array(colors)) = overlay.values.colors.get(key) {+ for (axis, color) in ["axis_x", "axis_y", "axis_z"].into_iter().zip(colors) {+ merged.colors.insert(axis.into(), color.clone());+ }+ }+ }+ merged.colors.extend(overlay.values.colors);+ merged.radii.extend(overlay.values.radii);+ merged.borders.extend(overlay.values.borders);+ merged.icon_palette.extend(overlay.values.icon_palette);+ }+ resolve_base(&merged)+}++/// A colour the saved preferences hold that this version cannot read is skipped safely.+fn resolve_base(theme: &ThemeFile) -> Tokens {let mut t = if theme.base.is_dark() { Tokens::dark() } else { Tokens::light() };for k in LEGACY_AXES {if let Some(Ok(c)) = theme.colors.get(k).map(|v| colors_of(v, 3))@@ -619,6 +1163,33 @@ pub fn export(name: &str, base: Base, t: &Tokens) -> Value {json!({"format": FORMAT, "name": name, "base": base, "colors": colors, "radii": radii, "borders": borders, "icon_palette": icon_palette})}+/// Export a theme definition, preserving its options and overlays rather than flattening them+/// to the current tokens. The existing [`export`] remains a complete token snapshot.+pub fn export_file(theme: &ThemeFile) -> Value {+ let mut value = json!({"format": FORMAT, "name": theme.name, "base": theme.base, "colors": theme.colors});+ if let Some(obj) = value.as_object_mut() {+ if !theme.radii.is_empty() {+ obj.insert("radii".into(), json!(theme.radii));+ }+ if !theme.borders.is_empty() {+ obj.insert("borders".into(), json!(theme.borders));+ }+ if !theme.icon_palette.is_empty() {+ obj.insert("icon_palette".into(), json!(theme.icon_palette));+ }+ if !theme.options.is_empty() {+ obj.insert("options".into(), json!(theme.options));+ }+ if !theme.overlays.is_empty() {+ obj.insert("overlays".into(), json!(theme.overlays));+ }+ if !is_current_level(&theme.requires) {+ obj.insert("requires".into(), json!(theme.requires));+ }+ }+ value+}+// Theme sources are collected at build time; picker order is validated below.include!(concat!(env!("OUT_DIR"), "/builtin_themes.rs"));@@ -823,6 +1394,389 @@ impl Follow {mod tests {use super::*;+ fn option_theme(options: Value, overlays: Value) -> Value {+ json!({"format":FORMAT,"name":"Options","base":"dark","options":options,"overlays":overlays})+ }++ fn sample_options() -> Value {+ json!([+ {"id":"enabled","type":"bool","default":true,"label":{"en":"Enable","da":"Aktivér"},"help":{"en":"Theme-owned help"}},+ {"id":"style","type":"choice","default":"warm","parent":"enabled","advanced":true,"section":"Appearance",+ "values":[{"id":"warm","label":{"en":"Warm"}},{"id":"cool","label":{"en":"Cool"}}]},+ {"id":"amount","type":"range","default":5,"min":0,"max":10,"step":0.5,"unit":"pt"}+ ])+ }++ #[test]+ fn option_definitions_reject_bad_keys_and_hostile_numbers() {+ let mut cases = vec![+ (json!([{"id":"Bad","type":"bool","default":true}]), "id"),+ (json!([{"id":"a","type":"script","default":true}]), "type"),+ (json!([{"id":"a","type":"bool","default":1}]), "default"),+ (json!([{"id":"a","type":"bool","default":true},{"id":"a","type":"bool","default":false}]), "id"),+ (json!([{"id":"opacity","type":"bool","default":true}]), "type"),+ (json!([{"id":"tab_colours","type":"range","default":1}]), "type"),+ (json!([{"id":"a","type":"choice","default":"missing","values":[{"id":"x","label":{}},{"id":"y","label":{}}]}]), "default"),+ (json!([{"id":"a","type":"choice","default":"x","values":[{"id":"x","label":{}},{"id":"x","label":{}}]}]), "values.id"),+ (json!([{"id":"a","type":"choice","default":"x","values":[{"id":"x","label":{}}]}]), "values"),+ (json!([{"id":"a","type":"range","default":1,"min":2,"max":1,"step":1}]), "min"),+ (json!([{"id":"a","type":"range","default":3,"min":0,"max":2,"step":1}]), "default"),+ (json!([{"id":"a","type":"range","default":1,"min":0,"max":2,"step":0}]), "step"),+ (json!([{"id":"a","type":"range","default":1,"min":0,"max":2,"step":-1}]), "step"),+ (json!([{"id":"a","type":"range","default":1,"min":0,"max":2,"step":1,"unit":"points"}]), "unit"),+ (json!([{"id":"a","type":"bool","default":true,"label":{"en":"x".repeat(41)}}]), "label"),+ (json!([{"id":"a","type":"bool","default":true,"help":{"en":"x".repeat(161)}}]), "help"),+ (json!([{"id":"a","type":"bool","default":true,"section":"x".repeat(25)}]), "section"),+ (json!([{"id":"a".repeat(33),"type":"bool","default":true}]), "id"),+ (json!([{"id":"a","type":"bool","default":true,"parent":"missing"}]), "parent"),+ (json!([{"id":"a","type":"bool","default":true,"advanced":"yes"}]), "advanced"),+ (json!([{"id":"opacity","type":"range","default":80,"min":39}]), "min"),+ (json!([{"id":"blur","type":"range","default":10,"max":41}]), "max"),+ ];+ let mut too_many = Vec::new();+ for i in 0..17 {+ too_many.push(json!({"id":format!("o{i}"),"type":"bool","default":true}));+ }+ cases.push((json!(too_many), "options"));+ let mut too_many_choices = sample_options();+ too_many_choices[1]["values"] = json!((0..13).map(|i| json!({"id":format!("v{i}"),"label":{}})).collect::<Vec<_>>());+ cases.push((too_many_choices, "values"));+ for key in ["min", "max", "step", "default"] {+ // JSON cannot encode NaN/infinity; null, strings and finite f64 values overflowing+ // f32 must still name the precise field. Actual non-finite Rust values are below.+ for value in [Value::Null, json!("NaN"), json!("Infinity"), json!(1e100), json!(-1e100)] {+ let mut options = sample_options();+ options[2][key] = value;+ cases.push((options, key));+ }+ }+ for (options, key) in cases {+ let error = from_value(&option_theme(options, json!([]))).unwrap_err();+ assert!(error.contains(key), "expected {key}: {error}");+ }+ for number in ["NaN", "Infinity", "-Infinity", "1e400"] {+ let text = format!(+ r#"{{"format":"{FORMAT}","name":"Bad","base":"dark","options":[{{"id":"x","type":"range","min":0,"max":10,"step":1,"default":{number}}}]}}"#+ );+ assert!(parse(&text).is_err(), "{number} is not a JSON finite number");+ }+ }++ #[test]+ fn option_parents_must_be_unique_bool_parents_without_cycles() {+ let mut options = sample_options();+ options[1]["parent"] = json!("amount");+ assert!(from_value(&option_theme(options, json!([]))).unwrap_err().contains("parent"));+ let mut options = sample_options();+ options[2]["parent"] = json!("enabled");+ assert!(from_value(&option_theme(options, json!([]))).unwrap_err().contains("parent"));+ for options in [+ json!([{"id":"a","type":"bool","default":true,"parent":"a"}]),+ json!([{"id":"a","type":"bool","default":true,"parent":"b"},{"id":"b","type":"bool","default":true,"parent":"a"}]),+ json!([{"id":"tab_fade_ms","type":"range","default":100}]),+ ] {+ assert!(from_value(&option_theme(options, json!([]))).unwrap_err().contains("parent"));+ }+ }++ #[test]+ fn option_and_overlay_limits_accept_their_boundaries_and_count_unicode_characters() {+ let mut options = sample_options().as_array().unwrap().clone();+ options[0]["label"] = json!({"en":"é".repeat(40)});+ options[0]["help"] = json!({"en":"é".repeat(160)});+ options[0]["section"] = json!("é".repeat(24));+ options[1]["values"] = json!((0..12).map(|i| json!({"id":format!("v{i}"),"label":{"en":"é".repeat(40)}})).collect::<Vec<_>>());+ options[1]["default"] = json!("v11");+ options[2]["unit"] = json!("é".repeat(4));+ for i in options.len()..MAX_OPTIONS {+ options.push(json!({"id":format!("o{i}"),"type":"bool","default":false}));+ }+ let overlays = (0..MAX_OVERLAYS).map(|i| json!({"when":{"opt":"enabled","eq":true},"radii":{"radius_sm":i}})).collect::<Vec<_>>();+ let theme = from_value(&option_theme(json!(options), json!(overlays))).unwrap();+ assert_eq!((theme.options.len(), theme.overlays.len()), (MAX_OPTIONS, MAX_OVERLAYS));+ assert_eq!(resolve(&theme).radius_sm, 31);+ assert_eq!(from_value(&export_file(&theme)).unwrap(), theme);+ }++ #[test]+ fn reserved_options_are_app_owned_and_ordered_with_their_children() {+ let file = from_value(&option_theme(+ json!([+ {"id":"custom_first","type":"bool","default":false},+ {"id":"tab_fade_ms","type":"range","default":9999,"min":100,"max":500,"unit":"bad","parent":"wrong","step":null},+ {"id":"tab_colours","type":"bool","default":true,"advanced":"ignored","label":null},+ {"id":"blur","type":"range","default":-5,"help":false,"section":42},+ {"id":"custom_child","type":"choice","default":"a","parent":"tab_fade_ms",+ "values":[{"id":"a","label":{}},{"id":"b","label":{}}]},+ {"id":"opacity","type":"range","default":200,"min":60,"max":90,"step":0,"unit":false}+ ]),+ json!([]),+ ))+ .unwrap_err();+ assert!(file.contains("parent"), "a reserved range cannot be a bool parent");+ let file = from_value(&option_theme(+ json!([+ {"id":"custom_first","type":"bool","default":false},+ {"id":"tab_fade_ms","type":"range","default":9999,"min":100,"max":500,"unit":"bad","parent":"wrong","step":null},+ {"id":"tab_colours","type":"bool","default":true,"advanced":"ignored","label":null},+ {"id":"blur","type":"range","default":-5,"help":false,"section":42},+ {"id":"custom_child","type":"bool","default":true,"parent":"custom_first"},+ {"id":"opacity","type":"range","default":200,"min":60,"max":90,"step":0,"unit":false}+ ]),+ json!([]),+ ))+ .unwrap();+ let (values, notices) = effective_values(&file, &BTreeMap::new());+ assert!(notices.is_empty());+ assert_eq!(values["opacity"], OptionValue::Num(90.0));+ assert_eq!(values["blur"], OptionValue::Num(0.0));+ assert_eq!(values["tab_fade_ms"], OptionValue::Num(500.0));+ let fade = file.options.iter().find(|o| o.id == "tab_fade_ms").unwrap();+ assert_eq!(fade.parent.as_deref(), Some("tab_colours"));+ assert!(matches!(&fade.kind, OptionKind::Range { min:100.0, max:500.0, step:1.0, unit:Some(unit), .. } if unit == "ms"));+ assert!(+ file.options+ .iter()+ .filter(|o| STANDARD_OPTIONS.contains(&o.id.as_str()))+ .all(|o| o.label.is_empty() && o.help.is_empty() && !o.advanced && o.section.is_none())+ );+ assert_eq!(+ ordered_options(&file).iter().map(|o| o.id.as_str()).collect::<Vec<_>>(),+ ["opacity", "blur", "tab_colours", "tab_fade_ms", "custom_first", "custom_child"]+ );+ let child = from_value(&option_theme(+ json!([+ {"id":"child","type":"bool","default":false,"parent":"tab_colours"},+ {"id":"other","type":"bool","default":false},+ {"id":"tab_colours","type":"bool","default":true}+ ]),+ json!([]),+ ))+ .unwrap();+ assert_eq!(ordered_options(&child).iter().map(|o| o.id.as_str()).collect::<Vec<_>>(), ["tab_colours", "child", "other"]);+ }++ #[test]+ fn effective_option_values_fall_back_clamp_and_report_each_saved_problem() {+ let theme = from_value(&option_theme(sample_options(), json!([]))).unwrap();+ let defaults = effective_values(&theme, &BTreeMap::new());+ assert!(defaults.1.is_empty());+ for (saved, expected, kind) in [+ (OptionValue::Choice("typo".into()), OptionValue::Choice("warm".into()), OptionNoticeKind::UnknownChoice),+ (OptionValue::Bool(false), OptionValue::Choice("warm".into()), OptionNoticeKind::WrongType),+ ] {+ let (values, notices) = effective_values(&theme, &BTreeMap::from([("style".into(), saved)]));+ assert_eq!(values["style"], expected);+ assert_eq!(notices, [OptionNotice { id: "style".into(), kind }]);+ }+ for (n, expected, kind) in [+ (-1.0, 0.0, OptionNoticeKind::Clamped),+ (20.0, 10.0, OptionNoticeKind::Clamped),+ (f32::NAN, 5.0, OptionNoticeKind::NonFinite),+ (f32::INFINITY, 5.0, OptionNoticeKind::NonFinite),+ (f32::NEG_INFINITY, 5.0, OptionNoticeKind::NonFinite),+ ] {+ let (values, notices) = effective_values(&theme, &BTreeMap::from([("amount".into(), OptionValue::Num(n))]));+ assert_eq!(values["amount"], OptionValue::Num(expected));+ assert_eq!(notices, [OptionNotice { id: "amount".into(), kind }]);+ }+ let (values, notices) = effective_values(+ &theme,+ &BTreeMap::from([+ ("enabled".into(), OptionValue::Choice("bad".into())),+ ("style".into(), OptionValue::Choice("bad".into())),+ ("amount".into(), OptionValue::Num(99.0)),+ ("removed".into(), OptionValue::Bool(true)),+ ]),+ );+ assert_eq!(notices.len(), 4);+ assert!(!values.contains_key("removed"));+ assert_eq!(values["enabled"], OptionValue::Bool(true));+ let saved = BTreeMap::from([+ ("enabled".into(), OptionValue::Bool(false)),+ ("style".into(), OptionValue::Choice("cool".into())),+ ("amount".into(), OptionValue::Num(4.25)),+ ]);+ assert_eq!(effective_values(&theme, &saved), (saved, Vec::new()), "step is a UI increment, not quantization");+ }++ #[test]+ fn overlays_reject_unknown_options_types_comparisons_and_invalid_tables() {+ let mut cases = vec![+ (json!({"opt":"missing","eq":true}), json!({}), "opt"),+ (json!({"opt":"enabled","eq":1}), json!({}), "eq"),+ (json!({"opt":"style","eq":"missing"}), json!({}), "eq"),+ (json!({"opt":"amount","eq":false}), json!({}), "eq"),+ (json!({"opt":"enabled","gte":0}), json!({}), "gte"),+ (json!({"opt":"style","lte":10}), json!({}), "lte"),+ (json!({"opt":"amount","gte":9,"lte":2}), json!({}), "gte"),+ (json!({"opt":"amount"}), json!({}), "when"),+ (json!({"opt":"amount","eq":2,"gte":0}), json!({}), "eq"),+ (json!({"opt":"amount","gt":2}), json!({}), "when"),+ (json!({"opt":"enabled","eq":true}), json!({"colors":{"panle":"#000000"}}), "panle"),+ (json!({"opt":"enabled","eq":true}), json!({"radii":{"radius_sm":33}}), "radii.radius_sm"),+ (json!({"opt":"enabled","eq":true}), json!({"borders":{"primary":{"width":5,"color":"#ffffff"}}}), "borders.primary.width"),+ (json!({"opt":"enabled","eq":true}), json!({"icon_palette":{"ink":"#ffffff80"}}), "icon_palette.ink"),+ ];+ for key in ["eq", "gte", "lte"] {+ cases.push((json!({"opt":"amount",key:1e100}), json!({}), key));+ }+ for (when, mut overlay, key) in cases {+ overlay["when"] = when;+ let error = from_value(&option_theme(+ sample_options(),+ json!([+ {"when":{"opt":"enabled","eq":false}}, overlay+ ]),+ ))+ .unwrap_err();+ assert!(error.contains("overlays[2]") && error.contains(key), "{key}: {error}");+ }+ let overlays = vec![json!({"when":{"opt":"enabled","eq":true}}); 33];+ assert!(from_value(&option_theme(sample_options(), json!(overlays))).unwrap_err().contains("overlays"));+ }++ #[test]+ fn matching_overlays_apply_in_file_order_and_preserve_other_table_entries() {+ let mut source = option_theme(+ sample_options(),+ json!([+ {"when":{"opt":"enabled","eq":true},"colors":{"panel":"#123456","axis_x":"#111111"},"radii":{"radius_sm":1},+ "borders":{"primary":{"width":2,"color":"#abcdef"}},"icon_palette":{"ink":"#112233"}},+ {"when":{"opt":"amount","gte":5,"lte":5},"colors":{"panel":"#abcdef","triad":["#222222","#333333","#444444"]},+ "radii":{"radius_md":2},"icon_palette":{"line":"#445566"}},+ {"when":{"opt":"amount","eq":6},"colors":{"panel":"#000000"}},+ {"when":{"opt":"style","eq":"cool"},"colors":{"panel":"#ffffff"}}+ ]),+ );+ source["colors"] = json!({"text":"#fedcba","axis_x":"#000000"});+ source["radii"] = json!({"radius_lg":3});+ source["borders"] = json!({"control":{"width":1,"color":"#123456"}});+ source["icon_palette"] = json!({"solid":["#ffffff","#777777","#000000"]});+ let theme = from_value(&source).unwrap();+ let resolved = resolve(&theme);+ assert_eq!(resolved.panel, parse_color("#abcdef").unwrap());+ assert_eq!(resolved.text, parse_color("#fedcba").unwrap());+ assert_eq!(resolved.axes(), [parse_color("#222222").unwrap(), parse_color("#333333").unwrap(), parse_color("#444444").unwrap()]);+ assert_eq!((resolved.radius_sm, resolved.radius_md, resolved.radius_lg), (1, 2, 3));+ assert_eq!(resolved.borders.primary.unwrap().width, 2.0);+ assert_eq!(resolved.borders.control.unwrap().width, 1.0);+ let palette = export_icon_palette(resolved.icon_palette);+ assert_eq!(palette["ink"], json!("#112233"));+ assert_eq!(palette["line"], json!("#445566"));+ assert_eq!(palette["solid"], source["icon_palette"]["solid"]);+ assert_eq!(resolve_with(&theme, &BTreeMap::from([("amount".into(), OptionValue::Num(6.0))])).panel, Color32::BLACK);+ let no_matches = BTreeMap::from([("enabled".into(), OptionValue::Bool(false)), ("amount".into(), OptionValue::Num(1.0))]);+ assert_eq!(resolve_with(&theme, &no_matches), resolve_base(&theme));+ assert_eq!(resolve_with(&theme, &effective_values(&theme, &BTreeMap::new()).0), resolved);+ }++ #[test]+ fn inactive_children_never_match_overlays_and_values_resume_when_parent_is_on() {+ let theme = from_value(&option_theme(+ sample_options(),+ json!([+ {"when":{"opt":"style","eq":"cool"},"colors":{"panel":"#123456"}}+ ]),+ ))+ .unwrap();+ let mut saved = BTreeMap::from([("enabled".into(), OptionValue::Bool(false)), ("style".into(), OptionValue::Choice("cool".into()))]);+ let effective = effective_values(&theme, &saved).0;+ assert_eq!(effective["style"], OptionValue::Choice("cool".into()));+ assert_eq!(resolve_with(&theme, &effective), resolve_base(&theme));+ saved.insert("enabled".into(), OptionValue::Bool(true));+ assert_eq!(resolve_with(&theme, &saved).panel, parse_color("#123456").unwrap());+ }++ #[test]+ fn options_and_overlays_roundtrip_without_changing_old_export_shape() {+ let theme = from_value(&option_theme(+ sample_options(),+ json!([+ {"when":{"opt":"amount","gte":4},"colors":{"panel":"#123456"}},+ {"when":{"opt":"style","eq":"warm"},"radii":{"radius_sm":0}}+ ]),+ ))+ .unwrap();+ let exported = export_file(&theme);+ assert_eq!(from_value(&exported).unwrap(), theme);+ assert_eq!(parse(&exported.to_string()).unwrap(), theme);+ assert_eq!(serde_json::from_value::<ThemeFile>(serde_json::to_value(&theme).unwrap()).unwrap(), theme);+ let old = from_value(&json!({"format":FORMAT,"name":"Old","base":"light"})).unwrap();+ assert_eq!(from_value(&export_file(&old)).unwrap(), old);+ for value in [export_file(&old), serde_json::to_value(&old).unwrap(), export("Snapshot", theme.base, &resolve(&theme))] {+ for key in ["options", "overlays", "requires"] {+ assert!(value.get(key).is_none(), "{key}: {value}");+ }+ }+ let snapshot = export("Snapshot", theme.base, &resolve(&theme));+ assert_eq!(+ snapshot.as_object().unwrap().keys().map(String::as_str).collect::<Vec<_>>(),+ ["base", "borders", "colors", "format", "icon_palette", "name", "radii"]+ );+ assert_eq!(resolve(&from_value(&snapshot).unwrap()), resolve(&theme));+ }++ #[test]+ fn newer_requirements_keep_base_tables_without_reading_future_option_syntax() {+ let source = json!({"format":FORMAT,"name":"Future","base":"light","requires":2,"colors":{"panel":"#123456"},+ "radii":{"radius_sm":0},"options":{"future":"syntax"},"overlays":false});+ let theme = from_value(&source).unwrap();+ assert!(theme.needs_newer());+ assert!(theme.options.is_empty() && theme.overlays.is_empty() && ordered_options(&theme).is_empty());+ assert_eq!(resolve(&theme).panel, parse_color("#123456").unwrap());+ assert_eq!(resolve(&theme).radius_sm, 0);+ assert_eq!(from_value(&export_file(&theme)).unwrap(), theme);+ let restored: ThemeFile = serde_json::from_value(serde_json::to_value(&theme).unwrap()).unwrap();+ assert!(restored.needs_newer());+ assert_eq!(resolve(&restored), resolve_base(&theme));+ for invalid in [json!(-1), json!(1.5), json!("2"), Value::Null] {+ let mut source = source.clone();+ source["requires"] = invalid;+ assert!(from_value(&source).unwrap_err().contains("requires"));+ }+ }++ #[test]+ fn all_shipped_themes_keep_the_original_resolver_output_and_serialization() {+ assert_eq!(builtin().len(), BUILTIN.len());+ for theme in builtin() {+ assert!(theme.options.is_empty() && theme.overlays.is_empty() && !theme.needs_newer());+ assert_eq!(resolve(theme), resolve_base(theme), "{}", theme.id);+ assert_eq!(resolve_with(theme, &BTreeMap::from([("opacity".into(), OptionValue::Num(40.0))])), resolve_base(theme), "{}", theme.id);+ let stored = serde_json::to_value(theme).unwrap();+ for key in ["options", "overlays", "requires"] {+ assert!(stored.get(key).is_none(), "{}: {key}", theme.id);+ }+ }+ }++ #[test]+ fn malformed_saved_definitions_and_comparisons_resolve_without_panics() {+ let mut theme = from_value(&option_theme(+ sample_options(),+ json!([+ {"when":{"opt":"amount","gte":0},"colors":{"panel":"#ffffff"}}+ ]),+ ))+ .unwrap();+ for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {+ let original = theme.clone();+ theme.options[2].kind = OptionKind::Range { default: invalid, min: 0.0, max: 10.0, step: 1.0, unit: None };+ assert_eq!(resolve(&theme), resolve_base(&theme));+ theme = original.clone();+ theme.options[2].kind = OptionKind::Range { default: 5.0, min: invalid, max: 10.0, step: 1.0, unit: None };+ assert_eq!(resolve(&theme), resolve_base(&theme));+ theme = original.clone();+ theme.overlays[0].when = Condition::Range { opt: "amount".into(), gte: Some(invalid), lte: None };+ assert_eq!(resolve(&theme), resolve_base(&theme));+ theme = original;+ }+ theme.requires = 2;+ assert_eq!(resolve(&theme), resolve_base(&theme));+ assert!(effective_values(&theme, &BTreeMap::new()).0.is_empty());+ }+#[test]fn navigation_board_colours_are_themeable_and_roundtrip_on_both_bases() {for (base, tokens, colours) in [diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.mdindex 611c278d6e..24ae3cc861 100644--- a/docs/book/src/guide/ui-tour.md+++ b/docs/book/src/guide/ui-tour.md@@ -292,6 +292,103 @@ Command icons use the shared SVG palette.Imported themes are kept with your preferences, so they work in the browser app too. Colourvision modes still apply on top of any theme.+#### Theme-file options and overlays++Theme authors can add `options` and `overlays` to `solidcraft-theme/1`. This is a file-format+and resolver API; this version has no controls for changing or saving option values. Import+uses the declared defaults. Existing files need no changes, and **Export…** still writes a+complete snapshot of the resolved colours, radii, borders and icon palette.++For example, add these two keys alongside a theme's `colors`:++```json+{+ "options": [+ {+ "id": "warm_accent",+ "type": "bool",+ "default": true,+ "label": {"en": "Warm accent"},+ "help": {"en": "Use a warmer accent colour."}+ },+ {+ "id": "rounding",+ "type": "range",+ "default": 4,+ "min": 0,+ "max": 12,+ "step": 1,+ "unit": "pt",+ "parent": "warm_accent"+ }+ ],+ "overlays": [+ {+ "when": {"opt": "warm_accent", "eq": true},+ "colors": {"accent": "#cc7744"}+ },+ {+ "when": {"opt": "rounding", "gte": 4, "lte": 12},+ "radii": {"control_radius": 8}+ }+ ]+}+```++A file can declare up to 16 options. Each `id` is unique and matches+`[a-z][a-z0-9_]{0,31}`. Every option has a `type` and `default`:++- `bool`: the default is `true` or `false`.+- `choice`: `values` contains 2 to 12 entries, each with a unique `id` in the same syntax+ and a localized `label` map, for example `{"id":"warm","label":{"en":"Warm"}}`.+ The default names one of those ids.+- `range`: finite numeric `min`, `max` and positive `step` are required, with `min` no larger+ than `max` and the default inside those bounds. Optional `unit` has at most 4 characters.+ Numbers must fit a finite 32-bit float. Saved values are clamped to the bounds; `step`+ is an increment for future controls, not a rounding rule.++Optional `label` and `help` maps use language codes as keys, with `en` as the fallback.+Labels have at most 40 characters and help strings at most 160, per language. Each map+supports up to 64 language codes, each at most 32 ASCII letters, digits, hyphens or underscores.+These texts belong to the theme and need no application catalog entries. `advanced` is an+optional boolean; `section` is an optional string of at most 24 characters. `parent` names+a declared boolean option, with at most one child per parent and no cycles. While the+parent is off, overlays referring to the child are inactive; the child's value is retained.++Four ids are reserved for definitions owned by the app:++| Id | Type | Bounds | Unit | Parent |+|---|---|---|---|---|+| `opacity` | range | 40–100 | `%` | — |+| `blur` | range | 0–40 | `px` | — |+| `tab_colours` | bool | — | — | — |+| `tab_fade_ms` | range | 0–600 | `ms` | `tab_colours` |++A theme declares these with their required type and a default; it may also narrow a range's+`min` and `max`. The default is clamped to those bounds. Other fields are ignored, including+presentation text, `step` (fixed at 1 for standard ranges), unit and parent. A wrong type or+bounds outside the standard range are import errors. Declaring `tab_fade_ms` also requires+declaring its boolean parent, `tab_colours`. Custom options cannot redefine reserved ids.+These declarations alone do not change opacity, blur or tab behaviour in this version.+The resolver exposes declared standard options in the order `opacity`, `blur`, `tab_colours`,+each immediately followed by its child, then custom options in declared order.++Up to 32 overlays apply in file order, after the base palette and the theme's own value tables.+Later matching entries win by key. Every overlay has one `when`: `{"opt":"id","eq":value}`+for an exact, correctly typed comparison, or `gte`, `lte`, or both for inclusive range bounds.+A choice comparison must name a declared choice. Unknown option ids, mixed comparisons and+malformed values are refused with the overlay's one-based position. An overlay may override+`colors`, `radii`, `borders` and `icon_palette`; all their existing key and value checks apply.+Overlays only select literal tables: there are no scripts, expressions or interpolation.++The optional integer `requires` defaults to 1, this app's supported level. A larger level+loads the authored base value tables, disables options and overlays, and exposes a+`needs_newer` flag through the theme API for future UI. The theme-definition API can export+options and overlays intact; the existing token snapshot export keeps its previous shape.+The value resolver reports notices for unknown saved ids, wrong types, unknown choices,+non-finite numbers and clamped values. Invalid saved values for declared options fall back to defaults;+unknown saved ids are omitted because they have no definition or default.+#### Follow a theme fileIn the desktop app, **Follow a theme file** (under the themes) takes a theme file that another