Cotton code
799 lines · 41.1 KB · RustRaw
//! THEME definitions — a database's skin as data (design note 26203e21 §6).//!//! A face has structure (what goes where, already data in table definitions)//! and skin: colour, type, corner, spacing, stroke, texture, the cap. A theme//! row names a face FAMILY shipped in the binary (`paper` today, `plain`//! next) and overrides any of the family's own knobs; every key but `id` is//! optional, so `{"id": "paper", "family": "paper"}` is Cotton as it draws//! today. `resolved()` lays each key a row names over its shipped family's//! values before a renderer reads it. One row per theme per database//! (`cotton_theme_definitions`); the built-ins ship in//! `crates/cotton-core/kits/shell/themes/` and are written into every//! database, and the database wears its own row when it has one.//!//! The row, in the definitions' snake_case://!//! ```json//! { "id": "studio", "name": "Studio", "family": "plain",//!   "palette": { "light": { "accent": "#C6534B", "pencil": 0.55,//!                           "tags": { "fill": "#FAEFE1", "ink": "#2E2925" } },//!                "dark":  { … } },//!   "type": { "title": "fraunces_text", "body": "courier" },//!   "scale": { "tokens": { "radius": 8, "spacing": 12, "stroke": 1 } },//!   "texture": { "grain": true, "shadow": "soft", "tilt": true },//!   "cap": { "colour": "navy", "texture": "enamel" } }//! ```//!//! A theme sets palette, type, acts, cards, objects and the tokens under//! `scale.tokens` ([`THEME_SCALE_TOKENS`]); nothing else. Every other size,//! count and timing a face draws with is Swift's, beside the code that reads//! it (architect, 14 Oct 2026).//!//! Read tolerantly like every definition kind: a key or a value this build//! cannot name is kept and passed over (the app keeps the family's own), a//! family it does not ship draws `paper`. [`ThemeDefinition::validate`]//! refuses only what is malformed — a colour that is not one, a size that is//! not a number; [`ThemeDefinition::strict`] holds an authored theme to the//! roles, faces and values this build draws.use std::collections::BTreeMap;use serde::{Deserialize, Serialize};use serde_json::{Map, Value};use super::tolerant::{self, Unknown};use super::{is_valid_id, refusal_words, DefinitionError};use crate::records::page::CAP_COLOURS;/// The face families this build ships.pub const THEME_FAMILIES: &[&str] = &["paper", "plain"];/// The theme a database without a row of its own wears.pub const DEFAULT_THEME: &str = "paper";/// The built-in themes: `(id, json)`, compiled in.pub const BUILTIN_THEME_FILES: &[(&str, &str)] = &[    ("paper", include_str!("../../kits/shell/themes/paper.json")),    ("plain", include_str!("../../kits/shell/themes/plain.json")),];/// The palette's colour roles (hex or precise `color(srgb r g b)`), as a row spells them.pub const THEME_COLOUR_ROLES: &[&str] = &[    "ground", "ground_muted", "ground_elevated", "ink", "ink_body", "ink_secondary", "ink_tertiary",    "hairline", "accent", "accent_contrast", "chip_ground", "highlight", "selection", "success",    "success_light", "error", "error_light", "warning", "warning_light", "print", "paper", "shadow",];/// A tag's two colours.pub const THEME_TAG_KEYS: &[&str] = &["fill", "ink"];/// The papers a record is printed on (the app's `PaperDye`), each the measured/// colour of its photographed master.pub const THEME_DYES: &[&str] = &["cream", "buff", "blue", "sage", "pink", "straw", "peach", "newsprint"];/// The papers a card is printed on by its pace band (`transforms::pace::Pace`).pub const THEME_PACES: &[&str] = &["late", "soon", "upcoming", "someday", "done"];/// The stocks and inks the deck's faces are printed with (programme/// cardtrial): the cream and buff stocks, the shadow under a card, the slip/// a corner's words sit on, a photograph's mount, the note's sprigs, the/// document's ruling and margin, a mount's initials, an invitation's green/// print and the sage disc of a guest with no picture, and the pencilled mark/// round a face's selected part. An ink's strength is its colour's alpha.pub const THEME_FACE_INKS: &[&str] = &[    "cream", "buff", "shadow", "slip", "mount", "ornament", "ruling", "margin", "initials", "invitation",    "invitation_disc", "mark", "passport_ink", "passport_red", "passport_violet", "passport_blue", "passport_brown",];/// The type roles.pub const THEME_TYPE_ROLES: &[&str] =    &["display", "title", "body", "meta", "hand", "figure", "cap", "interface", "script", "text_page_title", "text_editor_title", "text_screen_title", "text_row_title", "text_row_title_compact", "text_body", "text_preview", "text_caption", "text_section_label", "text_code"];/// The faces a type role can name: the house faces, the system's, and the/// brand faces the app bundles for a business's look (Montserrat).pub const THEME_FACES: &[&str] = &[    "fraunces_title", "fraunces_text", "courier", "courier_italic", "caveat", "instrument_italic",    "courier_new", "menlo", "system_bold", "system_heavy", "system", "system_semibold", "system_medium", "system_italic", "system_monospaced",    "montserrat", "montserrat_semibold",];/// A number an authored theme may set: inclusive bounds, in the token's own/// unit (points, a fraction, a weight, milliseconds, degrees). A value outside/// is refused with its key, its value and these bounds ([`ThemeDefinition::out_of_range`]).#[derive(Debug, Clone, Copy, PartialEq, Serialize)]pub struct ThemeRange {    pub min: f64,    pub max: f64,}const fn r(min: f64, max: f64) -> ThemeRange { ThemeRange { min, max } }/// The measures a theme sets — its `scale.tokens`: the corner, the inset,/// the gap, the line, the nav circles' row, and the type's sizes, line boxes/// and weights — each with the range an authored theme may set it to. An/// authored theme naming any other knob is refused, and so is a value outside/// its range ([`ThemeDefinition::strict`]). This table is the one place a/// token and its range are named (architect, 14 Oct 2026).pub const THEME_SCALE_TOKENS: &[(&str, ThemeRange)] = &[    ("radius", r(0.0, 40.0)), ("radius_min", r(0.0, 40.0)), ("radius_fraction", r(0.0, 1.0)),    ("spacing", r(2.0, 40.0)), ("inset_fraction", r(0.0, 0.25)), ("inset_min", r(0.0, 48.0)),    ("inset_max", r(0.0, 64.0)), ("stroke", r(0.25, 4.0)), ("hairline", r(0.25, 2.0)),    ("title_size", r(10.0, 40.0)), ("body_size", r(10.0, 28.0)), ("meta_size", r(8.0, 24.0)),    ("hand_size", r(8.0, 32.0)), ("monogram_size", r(0.1, 0.6)), ("section_title_size", r(12.0, 48.0)), ("screen_title_size", r(16.0, 60.0)),    ("nav_circle", r(24.0, 64.0)), ("nav_row_top", r(0.0, 32.0)), ("nav_row_air", r(0.0, 40.0)),    ("type_page_title_size", r(16.0, 60.0)), ("type_page_title_line_height", r(18.0, 80.0)),    ("type_editor_title_size", r(16.0, 60.0)), ("type_editor_title_line_height", r(18.0, 80.0)),    ("type_screen_title_size", r(12.0, 40.0)), ("type_screen_title_line_height", r(14.0, 52.0)),    ("type_row_title_size", r(12.0, 32.0)), ("type_row_title_line_height", r(14.0, 44.0)),    ("type_row_title_compact_size", r(10.0, 28.0)), ("type_row_title_compact_line_height", r(12.0, 38.0)),    ("type_body_size", r(10.0, 28.0)), ("type_body_line_height", r(12.0, 40.0)),    ("type_preview_size", r(10.0, 24.0)), ("type_preview_line_height", r(12.0, 34.0)),    ("type_caption_size", r(8.0, 20.0)), ("type_caption_line_height", r(10.0, 28.0)),    ("type_section_label_size", r(8.0, 20.0)), ("type_section_label_line_height", r(10.0, 28.0)),    ("type_section_label_tracking", r(-2.0, 4.0)), ("type_code_size", r(8.0, 20.0)),    ("type_code_line_height", r(10.0, 28.0)), ("type_weight_regular", r(100.0, 900.0)),    ("type_weight_medium", r(100.0, 900.0)), ("type_weight_semibold", r(100.0, 900.0)),    ("type_weight_bold", r(100.0, 900.0)), ("type_weight_heavy", r(100.0, 900.0)),    // Home's fan of cards (lane fan, 14 Oct 2026).    ("fan_tile_w", r(60.0, 240.0)), ("fan_radius", r(150.0, 1200.0)), ("fan_step_deg", r(4.0, 45.0)),    ("fan_visible_deg", r(20.0, 180.0)),    ("fan_cap_size", r(40.0, 72.0)),    ("fan_cap_lift", r(0.0, 16.0)),    ("fan_caps_gap", r(0.0, 40.0)),    ("fan_caps_faint", r(0.1, 1.0)),    // A tool's views as an outer ring of slips about the fan's pivot, above    // its cards: the ring's radius, one slip's size and the gap between two    // (views programme, master note 57th–58th amendments, 20 Oct 2026).    ("ring_radius", r(300.0, 900.0)), ("ring_slip_w", r(48.0, 160.0)), ("ring_slip_h", r(20.0, 56.0)),    ("ring_slip_gap", r(0.0, 32.0)),    // While reading, the fan collapses into one small circle, the record    // button smaller; a scroll back up blooms it (lane fancollapse, 15 Oct 2026).    ("fan_collapsed_size", r(28.0, 72.0)), ("fan_collapse_scroll", r(4.0, 120.0)), ("fan_bloom_scroll", r(4.0, 120.0)),    ("fan_collapse_response", r(0.1, 1.5)), ("fan_collapse_damping", r(0.3, 1.0)),    // A page's title in its head row, beside its circles (fan3 part 7).    ("head_title_size", r(14.0, 40.0)),    // A record's title in its head row, one size below a page's (fan3 part 10).    ("head_record_title_size", r(14.0, 40.0)),    // From a page's head row to its first content (fan3 part 10 refinement).    ("page_head_gap", r(0.0, 48.0)),    // A record page's slips (recordslips, 17 Oct 2026): a slip's inner    // inset, the air between slips, its corner, its top and bottom edge, how    // far a lifted slip rises (scale) and casts (shadow radius).    ("slip_pad", r(2.0, 32.0)), ("slip_gap", r(0.0, 32.0)), ("slip_radius", r(0.0, 24.0)),    ("slip_edge", r(0.0, 3.0)), ("slip_lift", r(1.0, 1.2)), ("slip_shadow", r(0.0, 24.0)),    // A list's slip (recordface row 1, 21 Oct 2026): whether its edge is torn    // (0 cut, 1 deckled) and whether it leans by its seed (0 square, 1 tilted).    ("slip_deckle", r(0.0, 1.0)), ("slip_tilt", r(0.0, 1.0)),    // A lifted slip's acts (slipacts, 18 Oct 2026): how dark the rest of the    // page goes, each act's row (never under a fingertip's 44 points), the    // object beside its word, the list's least width; and the chevron a slip    // whose tap leaves the page carries at rest.    ("page_dim", r(0.0, 0.6)), ("slip_act_row", r(44.0, 80.0)), ("slip_act_glyph", r(12.0, 40.0)),    ("slip_list_w", r(160.0, 360.0)), ("slip_chevron", r(4.0, 16.0)),    ("fan_top", r(0.0, 120.0)), ("fan_lift", r(0.0, 40.0)), ("fan_settled_scale", r(1.0, 1.5)),    ("fan_hold_ms", r(150.0, 1500.0)), ("fan_silence_ms", r(300.0, 5000.0)),    // A swipe turns one tile; a fling's reach is a share of the whole fan    // (walker pass 2, 16 Oct 2026): points a second, the share, a step's fraction.    ("fan_fling_min", r(50.0, 3000.0)), ("fan_fling_full", r(300.0, 10000.0)), ("fan_fling_reach", r(0.05, 1.0)),    ("fan_swipe_lean", r(0.05, 0.5)), ("fan_snap_response", r(0.1, 1.5)), ("fan_snap_damping", r(0.3, 1.0)),    ("fan_turn_ms_per_deg", r(0.0, 30.0)), ("fan_turn_ms_max", r(100.0, 3000.0)), ("fan_turn_ms_min", r(0.0, 1500.0)),    ("fan_overscroll", r(0.0, 1.0)), ("fan_tap_slop", r(0.0, 30.0)), ("fan_poster_scale", r(1.0, 4.0)),    ("fan_picture_quality", r(0.1, 1.0)), ("fan_picture_reach", r(1.0, 12.0)), ("fan_picture_scale", r(1.0, 4.0)),    ("fan_picture_settle_ms", r(0.0, 2000.0)), ("fan_ghost_wash", r(0.0, 1.0)),    ("fan_record_size", r(40.0, 120.0)), ("fan_record_glyph", r(0.2, 0.8)),    ("fan_record_hint_size", r(8.0, 20.0)), ("fan_record_pill_size", r(12.0, 40.0)), ("fan_record_pill_pad", r(4.0, 32.0)),    ("fan_record_pulse", r(0.0, 60.0)), ("fan_record_pulse_opacity", r(0.0, 1.0)), ("fan_record_pulse_ms", r(300.0, 4000.0)),    // The spoken words above the record button: one line, its start fading    // out to the left as the newest words come (lane voiceline, 16 Oct 2026).    ("voice_line_lines", r(1.0, 1.0)), ("voice_line_fade", r(0.0, 64.0)),    // A record opened on a fan card's page with no slip on screen to zoom    // out of cross-fades in this long (lane trail, 15 Oct 2026).    ("fan_open_fade_ms", r(0.0, 1000.0)),    // The least width a tile on a shelf — a row of tiles that scrolls sideways — is laid    // out at: a slip's own width, so a slip on a shelf never folds its words a    // letter a line (lane slipwidth, 15 Oct 2026).    ("shelf_tile_min_w", r(120.0, 480.0)),    // The hits an expanded search section reads per page, as it pages through    // its kind (localfirst, architect 15 Oct 2026: nothing is read all at once).    ("search_page", r(10.0, 500.0)),    // The deck's card paper (textures-v2, architect 22 Oct 2026): each    // layer's opacity over the stock's fill, and how much darker the sheets    // under the card are than their stock.    ("card_mottle_opacity", r(0.0, 1.0)), ("card_rim_opacity", r(0.0, 1.0)),    ("card_rule_opacity", r(0.0, 1.0)), ("card_shadow_opacity", r(0.0, 1.0)), ("card_under_shade", r(0.0, 0.5)),];/// The numbers a theme sets outside `scale.tokens`, by path: the pencil's/// strength, the cards' faint and off objects and their outlines. An array's/// range holds for each of its values.pub const THEME_NUMBER_RANGES: &[(&str, ThemeRange)] = &[    ("palette.light.pencil", r(0.0, 1.0)), ("palette.dark.pencil", r(0.0, 1.0)),    ("cards.empty_outline_opacity", r(0.0, 1.0)), ("cards.faint_object_opacity", r(0.0, 1.0)),    ("cards.off_object_opacity", r(0.0, 1.0)), ("cards.empty_outline_dash", r(0.5, 24.0)),    ("cards.details_outline_dash", r(0.5, 24.0)),];/// A token's range, by its `scale.tokens` key.pub fn theme_token_range(key: &str) -> Option<ThemeRange> {    THEME_SCALE_TOKENS.iter().find(|(token, _)| *token == key).map(|(_, range)| *range)}/// One number an authored theme sets outside its range: the key as a path,/// the value it said, and the range it must be in.#[derive(Debug, Clone, PartialEq, Serialize)]pub struct ThemeOutOfRange {    pub key: String,    pub value: Value,    pub range: ThemeRange,}impl std::fmt::Display for ThemeOutOfRange {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        let line = super::automations::said(            "theme_value_outside_its_range",            &[("key", &self.key), ("value", &self.value), ("min", &self.range.min), ("max", &self.range.max)],        );        f.write_str(&line)    }}const SHADOWS: &[&str] = &["soft", "none"];const CAP_TEXTURES: &[&str] = &["enamel", "flat"];/// The largest size a scale knob may say; anything above is not a size.const LARGEST: f64 = 10000.0;/// A skin over one face family: every key but `id` optional.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct ThemeDefinition {    /// The definition format the file is written in ([`super::format`]).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub format_version: Option<u32>,    pub id: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub name: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub family: Option<String>,    /// What the theme is, in a sentence.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub description: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub palette: Option<ThemePalettes>,    /// Type role → face.    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]    pub type_roles: Option<BTreeMap<String, Value>>,    /// The measures: its tokens.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub scale: Option<ThemeScale>,    /// Act class → stock and other shipped act tokens.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub acts: Option<BTreeMap<String, Value>>,    /// Card defaults and appearance tokens.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub cards: Option<BTreeMap<String, Value>>,    /// Column type → the object drawn on its card.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub objects: Option<BTreeMap<String, Value>>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub texture: Option<ThemeTexture>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub cap: Option<ThemeCap>,    /// The content hash of the shipped file a person's row was written    /// against ([`super::format`]); absent on a shipped file.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub base_hash: Option<String>,    #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]    pub unknown: Unknown,    /// The keys [`ThemeDefinition::resolved`] fell back on, by path    /// (`type.title`): a newer build's word this build cannot draw — a    /// family, a face, a shadow, a cap, a stock — read as the family's own    /// ([`super::tolerant`]). Never stored.    #[serde(skip_deserializing, skip_serializing_if = "Vec::is_empty")]    pub fallbacks: Vec<String>,}/// The card stocks a theme's acts and cards can name.const STOCKS: &[&str] = &["cream", "sage", "rose", "slate", "tan", "grey"];/// `path` names a card stock: an act's, or one of the cards'.fn is_stock(path: &str) -> bool {    (path.starts_with("acts.") && path.ends_with(".stock"))        || (path.starts_with("cards.") && (path.ends_with("_stock") || path.contains("_stocks.")))}/// Every stock under `value` (at `path`) this build does not ship, left out/// so the family's own shows through, each path named in `fallbacks`.fn drop_unshipped_stocks(value: &mut Value, path: &str, fallbacks: &mut Vec<String>) {    if let Value::Object(map) = value {        map.retain(|key, inner| {            let at = format!("{path}.{key}");            let unshipped = is_stock(&at) && inner.as_str().is_some_and(|stock| !STOCKS.contains(&stock));            if unshipped {                fallbacks.push(at);            } else {                drop_unshipped_stocks(inner, &at, fallbacks);            }            !unshipped        });    }}/// The colours, for light and for dark; a row with no dark is light-only,/// as Cotton is.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct ThemePalettes {    #[serde(default, skip_serializing_if = "Option::is_none")]    pub light: Option<BTreeMap<String, Value>>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub dark: Option<BTreeMap<String, Value>>,    #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]    pub unknown: Unknown,}/// The theme's measures: its tokens and nothing else.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct ThemeScale {    /// Token ([`THEME_SCALE_TOKENS`]) → number.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub tokens: Option<BTreeMap<String, Value>>,    #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]    pub unknown: Unknown,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct ThemeTexture {    #[serde(default, skip_serializing_if = "Option::is_none")]    pub grain: Option<bool>,    /// `soft` or `none`.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub shadow: Option<String>,    /// Papers lie at a slight angle.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub tilt: Option<bool>,    #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]    pub unknown: Unknown,}/// The bottle cap: one of the enamels ([`CAP_COLOURS`]), or absent for the/// one the database's id assigns; and how it is drawn (`enamel`, `flat`).#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct ThemeCap {    #[serde(default, skip_serializing_if = "Option::is_none")]    pub colour: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub texture: Option<String>,    #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]    pub unknown: Unknown,}fn is_colour(value: &str) -> bool {    if let Some(hex) = value.strip_prefix('#') {        return matches!(hex.len(), 6 | 8) && hex.chars().all(|c| c.is_ascii_hexdigit());    }    // CSS's explicit sRGB form preserves measured decimal inks without    // rounding them to eight-bit hex as they move from a face into data.    let Some(channels) = value.strip_prefix("color(srgb ").and_then(|v| v.strip_suffix(')')) else { return false };    let channels: Vec<_> = channels.split_whitespace().collect();    channels.len() == 3 && channels.iter().all(|v| v.parse::<f64>().is_ok_and(|v| v.is_finite() && (0.0..=1.0).contains(&v)))}fn bad(slot: impl Into<String>, why: &str) -> DefinitionError {    DefinitionError::BadSlot { slot: slot.into(), why: refusal_words(why) }}fn overlay(base: &mut Value, overrides: Value) {    match (base, overrides) {        (Value::Object(base), Value::Object(overrides)) => {            for (key, value) in overrides {                if let Some(existing) = base.get_mut(&key) { overlay(existing, value); }                // Retired and future keys stay in storage for sync, but this build                // only resolves keys its shipped theme names.            }        }        (base, value) => *base = value,    }}fn validate_shipped_types(raw: &Value, shipped: &Value, path: &str, strict: bool) -> Result<(), DefinitionError> {    let same = matches!((raw, shipped),        (Value::Object(_), Value::Object(_)) | (Value::Array(_), Value::Array(_)) |        (Value::Number(_), Value::Number(_)) | (Value::String(_), Value::String(_)) |        (Value::Bool(_), Value::Bool(_)) | (Value::Null, Value::Null));    if !same { return Err(bad(path, "keeps_the_shipped_theme_key_s_json")); }    if let (Some(raw), Some(shipped)) = (raw.as_array(), shipped.as_array()) {        if let Some(default) = shipped.first() {            for (index, value) in raw.iter().enumerate() {                validate_shipped_types(value, default, &format!("{path}.{index}"), strict)?;            }        }    }    if path.starts_with("objects.") && !raw.as_str().is_some_and(|name| name.split('-').all(is_valid_id)) {        return Err(bad(path, "names_an_object_by_lowercase_words_separated"));    }    // A stock this build does not ship is a newer build's word: read as the    // family's own ([`ThemeDefinition::resolved`]), refused only when authored.    if is_stock(path) && !raw.as_str().is_some_and(|stock| STOCKS.contains(&stock) || (!strict && is_valid_id(stock))) {        return Err(bad(path, "names_a_shipped_card_stock"));    }    if let (Some(raw), Some(shipped)) = (raw.as_object(), shipped.as_object()) {        for (key, value) in raw {            if let Some(default) = shipped.get(key) {                let at = if path.is_empty() { key.clone() } else { format!("{path}.{key}") };                validate_shipped_types(value, default, &at, strict)?;            }        }    }    Ok(())}fn authored_keys(raw: &Value, shipped: &Value, path: &str, unknown: &mut Vec<String>) {    if let Some(object) = raw.as_object() {        for (key, value) in object {            let at = format!("{path}.{key}");            if let Some(default) = shipped.get(key) { authored_keys(value, default, &at, unknown); }            else { unknown.push(at); }        }    }}impl ThemeDefinition {    pub fn from_json(json: &str) -> Result<ThemeDefinition, DefinitionError> {        let raw: Value = serde_json::from_str(json).map_err(|error| DefinitionError::Parse(error.to_string()))?;        Self::check_types(&raw, false)?;        serde_json::from_value(raw).map_err(|error| DefinitionError::Parse(error.to_string()))    }    fn check_types(raw: &Value, strict: bool) -> Result<(), DefinitionError> {        let shipped: Value = serde_json::from_str(BUILTIN_THEME_FILES[0].1).expect("the shipped theme parses");        validate_shipped_types(raw, &shipped, "", strict)    }    /// Every built-in theme. A file that does not parse is a build defect    /// the guard test names; here it is a panic.    pub fn builtins() -> Vec<ThemeDefinition> {        BUILTIN_THEME_FILES            .iter()            .map(|(id, json)| {                let file = format!("themes/{id}.json");                serde_json::from_str::<Value>(json)                    .map_err(|error| DefinitionError::Parse(error.to_string()))                    .and_then(|raw| super::format::check_file(&file, &raw))                    .and_then(|_| ThemeDefinition::from_json(json))                    .unwrap_or_else(|error| panic!("built-in theme {file}: {error}"))            })            .collect()    }    pub fn builtin(id: &str) -> Option<ThemeDefinition> {        Self::builtins().into_iter().find(|theme| theme.id == id)    }    /// Fill absent keys from the shipped family, without changing the stored    /// overrides. A word this build cannot draw — a family it does not ship,    /// a face, a shadow, a cap or a stock it does not name — is left out, so    /// the family's own shows through, and named in `fallbacks`.    pub fn resolved(&self) -> Value {        let (theme, fallbacks) = self.drawable();        let mut resolved = theme.shipped_base();        overlay(&mut resolved, serde_json::to_value(&theme).expect("the theme serializes"));        // The cap colour is deliberately absent from shipped themes: it is        // optional database content, rather than a retired look token.        if let Some(colour) = theme.cap.as_ref().and_then(|cap| cap.colour.as_ref()) {            resolved["cap"]["colour"] = Value::from(colour.clone());        }        if !fallbacks.is_empty() {            resolved["fallbacks"] = serde_json::json!(fallbacks);        }        resolved    }    /// The shipped theme of this id; a database-owned theme uses its family.    /// The id is identity, even when its family differs from the shipped one.    fn shipped_base(&self) -> Value {        let id = if BUILTIN_THEME_FILES.iter().any(|(id, _)| *id == self.id) {            self.id.as_str()        } else {            self.family.as_deref().filter(|family| THEME_FAMILIES.contains(family)).unwrap_or(DEFAULT_THEME)        };        let shipped = BUILTIN_THEME_FILES.iter().find(|(key, _)| *key == id).expect("the base ships").1;        let mut base: Value = serde_json::from_str(shipped).expect("the shipped theme parses");        base["id"] = Value::from(self.id.clone());        base    }    /// Store only authored differences. A database theme retains a non-default    /// family as its base selector; named themes already select their own base.    pub fn overrides(&self) -> Value {        fn difference(raw: &Value, base: &Value) -> Option<Value> {            if raw == base { return None; }            if let Value::Object(object) = raw {                let patch: Map<String, Value> = object.iter().filter_map(|(key, value)| {                    difference(value, &base[key]).map(|value| (key.clone(), value))                }).collect();                return (!patch.is_empty()).then_some(Value::Object(patch));            }            Some(raw.clone())        }        let raw = serde_json::to_value(self).expect("the theme serializes");        let mut patch = difference(&raw, &self.shipped_base()).unwrap_or_else(|| serde_json::json!({}));        patch["id"] = Value::from(self.id.clone());        if !BUILTIN_THEME_FILES.iter().any(|(id, _)| *id == self.id) {            if let Some(family) = self.family.as_ref().filter(|family| family.as_str() != DEFAULT_THEME) {                patch["family"] = Value::from(family.clone());            }        }        patch    }    /// This row with every word this build cannot draw left out (a family it    /// does not ship reads as [`DEFAULT_THEME`]), and the paths that went.    fn drawable(&self) -> (ThemeDefinition, Vec<String>) {        let mut theme = self.clone();        let mut fallbacks = Vec::new();        theme.unknown.remove("fallbacks");        theme.fallbacks = Vec::new();        if theme.family.as_deref().is_some_and(|family| !THEME_FAMILIES.contains(&family)) {            theme.family = Some(DEFAULT_THEME.to_string());            fallbacks.push("family".to_string());        }        if let Some(roles) = &mut theme.type_roles {            roles.retain(|role, face| {                let drawn = face.as_str().is_some_and(|face| THEME_FACES.contains(&face));                if !drawn {                    fallbacks.push(format!("type.{role}"));                }                drawn            });        }        if let Some(texture) = &mut theme.texture {            if texture.shadow.as_deref().is_some_and(|shadow| !SHADOWS.contains(&shadow)) {                texture.shadow = None;                fallbacks.push("texture.shadow".to_string());            }        }        if let Some(cap) = &mut theme.cap {            if cap.colour.as_deref().is_some_and(|colour| !CAP_COLOURS.contains(&colour)) {                cap.colour = None;                fallbacks.push("cap.colour".to_string());            }            if cap.texture.as_deref().is_some_and(|texture| !CAP_TEXTURES.contains(&texture)) {                cap.texture = None;                fallbacks.push("cap.texture".to_string());            }        }        for (section, map) in [("acts", &mut theme.acts), ("cards", &mut theme.cards)] {            if let Some(map) = map {                let mut value = Value::Object(map.clone().into_iter().collect());                drop_unshipped_stocks(&mut value, section, &mut fallbacks);                *map = value.as_object().into_iter().flatten().map(|(key, value)| (key.clone(), value.clone())).collect();            }        }        fallbacks.sort();        (theme, fallbacks)    }    /// The row is well formed: every colour a colour, every size a size,    /// every name a lowercase word. A role, face, family or value this build    /// does not draw passes — the app keeps the family's own for it.    pub fn validate(&self) -> Result<(), DefinitionError> {        let raw = serde_json::to_value(self).map_err(|error| DefinitionError::Parse(error.to_string()))?;        Self::check_types(&raw, false)?;        if !is_valid_id(&self.id) {            return Err(DefinitionError::BadId(self.id.clone()));        }        if self.name.as_deref().is_some_and(|name| name.trim().is_empty() || name.chars().any(char::is_control)) {            return Err(DefinitionError::Empty("name"));        }        if self.family.as_deref().is_some_and(|family| !is_valid_id(family)) {            return Err(bad("family", "names_a_face_family_by_its_lowercase"));        }        if let Some(palettes) = &self.palette {            for (appearance, palette) in [("light", &palettes.light), ("dark", &palettes.dark)] {                for (entry, value) in palette.iter().flatten() {                    let at = format!("palette.{appearance}.{entry}");                    match (entry.as_str(), value) {                        ("pencil", value) => {                            // A strength past its range is not one, read or authored.                            let range = THEME_NUMBER_RANGES.iter().find(|(path, _)| *path == at).map_or(r(0.0, 1.0), |(_, range)| *range);                            if !value.as_f64().is_some_and(|strength| strength >= range.min && strength <= range.max) {                                return Err(bad(at, "is_the_pencil_s_strength_0_to"));                            }                        }                        ("tags", Value::Object(tags)) => {                            if let Some((tag, _)) = tags.iter().find(|(_, colour)| !colour.as_str().is_some_and(is_colour)) {                                return Err(bad(format!("{at}.{tag}"), "is_rrggbb_or_rrggbbaa"));                            }                        }                        ("tags", _) => return Err(bad(at, "holds_the_tag_s_colours")),                        ("dyes", Value::Object(dyes)) => {                            if let Some((dye, _)) = dyes.iter().find(|(_, colour)| !colour.as_str().is_some_and(is_colour)) {                                return Err(bad(format!("{at}.{dye}"), "is_rrggbb_or_rrggbbaa"));                            }                        }                        ("dyes", _) => return Err(bad(at, "holds_each_paper_s_colour")),                        ("paces", Value::Object(paces)) => {                            if let Some((pace, _)) = paces.iter().find(|(_, colour)| !colour.as_str().is_some_and(is_colour)) {                                return Err(bad(format!("{at}.{pace}"), "is_rrggbb_or_rrggbbaa"));                            }                        }                        ("paces", _) => return Err(bad(at, "holds_each_pace_band_s_paper_colour")),                        ("pace_rules", Value::Object(rules)) => {                            if let Some((pace, _)) = rules.iter().find(|(_, colour)| !colour.as_str().is_some_and(is_colour)) {                                return Err(bad(format!("{at}.{pace}"), "is_rrggbb_or_rrggbbaa"));                            }                        }                        ("pace_rules", _) => return Err(bad(at, "holds_each_pace_band_s_printed_rule")),                        ("faces", Value::Object(faces)) => {                            if let Some((ink, _)) = faces.iter().find(|(_, colour)| !colour.as_str().is_some_and(is_colour)) {                                return Err(bad(format!("{at}.{ink}"), "is_rrggbb_or_rrggbbaa"));                            }                        }                        ("faces", _) => {                            let words = crate::rules::shell_lines::LineSet::shipped("refusal").and_then(|set| set.say("theme.faces", &[]));                            return Err(bad(at, words.as_deref().unwrap_or("theme.faces")));                        }                        (_, value) => {                            if !value.as_str().is_some_and(is_colour) {                                return Err(bad(at, "is_rrggbb_or_rrggbbaa"));                            }                        }                    }                }            }        }        for (role, face) in self.type_roles.iter().flatten() {            if !face.as_str().is_some_and(is_valid_id) {                return Err(bad(format!("type.{role}"), "names_a_face_by_its_lowercase_word"));            }        }        for (key, size) in self.scale.iter().flat_map(|scale| scale.tokens.iter().flatten()) {            if !size.as_f64().is_some_and(|size| size.is_finite() && (0.0..LARGEST).contains(&size)) {                return Err(bad(format!("scale.tokens.{key}"), "is_a_finite_measure_in_the_shipped"));            }        }        if let Some(texture) = &self.texture {            if texture.shadow.as_deref().is_some_and(|shadow| !is_valid_id(shadow)) {                return Err(bad("texture.shadow", "names_a_shadow_by_its_lowercase_word"));            }        }        if let Some(cap) = &self.cap {            for (key, value) in [("colour", &cap.colour), ("texture", &cap.texture)] {                if value.as_deref().is_some_and(|word| !is_valid_id(word)) {                    return Err(bad(format!("cap.{key}"), "is_a_lowercase_word"));                }            }        }        Ok(())    }    /// An AUTHORED theme: well formed, on a family this build ships, naming    /// only the roles, faces, knobs and values it draws.    pub fn strict(raw: &Value) -> Result<ThemeDefinition, DefinitionError> {        super::format::check_authored(&format!("themes/{}.json", raw["id"].as_str().unwrap_or("theme")), raw)?;        Self::check_types(raw, true)?;        let theme: ThemeDefinition = serde_json::from_value(raw.clone())            .map_err(|error| DefinitionError::Parse(error.to_string()))?;        theme.validate()?;        let mut unknown = tolerant::unknown_keys(raw, &theme, &theme.unknown);        let mut outside = |slot: String, word: &str, known: &[&str]| {            if !known.contains(&word) {                unknown.push(format!("{slot} {word}"));            }        };        if let Some(family) = &theme.family {            outside("family".into(), family, THEME_FAMILIES);        }        if let Some(palettes) = &theme.palette {            for (key, _) in &palettes.unknown {                outside(format!("palette.{key}"), key, &[]);            }            for (appearance, palette) in [("light", &palettes.light), ("dark", &palettes.dark)] {                for (key, value) in palette.iter().flatten() {                    match key.as_str() {                        "pencil" => {}                        "tags" => {                            for tag in value.as_object().into_iter().flat_map(Map::keys) {                                outside(format!("palette.{appearance}.tags"), tag, THEME_TAG_KEYS);                            }                        }                        "dyes" => {                            for dye in value.as_object().into_iter().flat_map(Map::keys) {                                outside(format!("palette.{appearance}.dyes"), dye, THEME_DYES);                            }                        }                        "paces" | "pace_rules" => {                            for pace in value.as_object().into_iter().flat_map(Map::keys) {                                outside(format!("palette.{appearance}.{key}"), pace, THEME_PACES);                            }                        }                        "faces" => {                            for ink in value.as_object().into_iter().flat_map(Map::keys) {                                outside(format!("palette.{appearance}.faces"), ink, THEME_FACE_INKS);                            }                        }                        role => outside(format!("palette.{appearance}"), role, THEME_COLOUR_ROLES),                    }                }            }        }        for (role, face) in theme.type_roles.iter().flatten() {            outside("type".into(), role, THEME_TYPE_ROLES);            outside(format!("type.{role}"), face.as_str().unwrap_or_default(), THEME_FACES);        }        let shipped: Value = serde_json::from_str(BUILTIN_THEME_FILES[0].1).expect("the shipped theme parses");        if let Some(scale) = &theme.scale {            for key in scale.unknown.keys() {                outside("scale".into(), key, &[]);            }            for key in scale.tokens.iter().flatten().map(|(key, _)| key) {                outside("scale.tokens".into(), key, &THEME_SCALE_TOKENS.iter().map(|(token, _)| *token).collect::<Vec<_>>());            }        }        if let Some(texture) = &theme.texture {            for key in texture.unknown.keys() {                outside("texture".into(), key, &[]);            }            if let Some(shadow) = &texture.shadow {                outside("texture.shadow".into(), shadow, SHADOWS);            }        }        if let Some(cap) = &theme.cap {            for key in cap.unknown.keys() {                outside("cap".into(), key, &[]);            }            if let Some(colour) = &cap.colour {                outside("cap.colour".into(), colour, &CAP_COLOURS);            }            if let Some(texture) = &cap.texture {                outside("cap.texture".into(), texture, CAP_TEXTURES);            }        }        for section in ["acts", "cards", "objects"] {            if let Some(value) = raw.get(section) {                authored_keys(value, &shipped[section], section, &mut unknown);            }        }        if !unknown.is_empty() {            unknown.sort();            unknown.dedup();            return Err(DefinitionError::UnknownKeys(unknown));        }        let outside = Self::out_of_range(raw);        if !outside.is_empty() {            return Err(DefinitionError::OutOfRange(outside.iter().map(ToString::to_string).collect()));        }        Ok(theme)    }    /// Every number an authored row sets outside its range    /// ([`THEME_SCALE_TOKENS`], [`THEME_NUMBER_RANGES`]), in key order, each    /// with its value and range; a ranged key holding something other than a    /// number is outside too. Empty when every number is in range. Only an    /// authored theme is held to it: a row read from the file is drawn as it    /// came, so a newer build's wider range relays unchanged.    pub fn out_of_range(raw: &Value) -> Vec<ThemeOutOfRange> {        fn within(value: &Value, range: ThemeRange) -> bool {            value.as_f64().is_some_and(|number| number.is_finite() && number >= range.min && number <= range.max)        }        let mut found = Vec::new();        let mut check = |key: String, value: &Value, range: ThemeRange| match value.as_array() {            Some(values) => {                for (index, value) in values.iter().enumerate() {                    if !within(value, range) {                        found.push(ThemeOutOfRange { key: format!("{key}.{index}"), value: value.clone(), range });                    }                }            }            None if !within(value, range) => found.push(ThemeOutOfRange { key, value: value.clone(), range }),            None => {}        };        for (key, value) in raw.pointer("/scale/tokens").and_then(Value::as_object).into_iter().flatten() {            if let Some(range) = theme_token_range(key) {                check(format!("scale.tokens.{key}"), value, range);            }        }        for (path, range) in THEME_NUMBER_RANGES {            if let Some(value) = raw.pointer(&format!("/{}", path.replace('.', "/"))) {                check(path.to_string(), value, *range);            }        }        found.sort_by(|a, b| a.key.cmp(&b.key));        found    }}#[cfg(test)]#[path = "theme_tests.rs"]mod tests;