Cotton code
453 lines · 25.8 KB · RustRaw
//! `definitions.theme` and `definitions.saveTheme` — the theme a database//! wears, read and chosen (design note 26203e21 §6, §9).//!//! THE READ SAYS A FAMILY IT CANNOT DRAW ONCE, AS FEEDBACK (§9). A row//! written by a newer build may name a family this one does not ship; the//! read is tolerant and the app draws `paper` for it, which is right and//! silent. So the first read that meets it writes ONE Feedback row naming the//! family and the database — the row the walk lane reads — and every later//! read finds that row (its id is derived from the database and the family,//! `feedback_note::file_once`) and writes nothing.//!//! The save: the brand kit applied in one act, or a family picked.//!//! The row written is the database's OWN theme (`presentation::OWN_THEME`,//! `builtin = 0`), the same row `presentation::set_cap_colour` writes the cap's colour//! on, so a theme and a cap colour are one row and the newest write wins. An//! authored theme is held to what this build draws (`ThemeDefinition::strict`)://! a family it does not ship, a face it does not carry or a colour that is not//! one is refused here rather than passed over at every read. Undo uses//! records undo with the exact prior row, including an absent override.use cotton_core::definitions::theme::{ThemeDefinition, THEME_FAMILIES};use cotton_tools::presentation::{OWN_THEME, THEME_DEFINITIONS};use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use crate::methods::MethodError;use crate::phone::feedback_note::file_once;use crate::phone::feedback_send::PLATFORM;use crate::shell::client::ClientController;/// The theme the shown database wears, as `presentation::theme` answers it;/// a family this build does not ship is drawn as `paper` by the app and said/// once in Feedback.pub fn read(client: &ClientController) -> Result<Value, MethodError> {    let (mut answer, unshipped) = client        .read_rows("definitions.theme", &mut |ctx| {            let drawn = cotton_tools::presentation::theme(ctx.read.driver(), ctx.workspace_id)?;            // The resolved theme draws a family this build ships and names            // `family` in its fallbacks; the word it fell back from is the row's.            let fell_back = drawn.definition["fallbacks"].as_array().is_some_and(|paths| paths.iter().any(|path| path == "family"));            let row = if fell_back { cotton_tools::presentation::theme_overrides(ctx.read.driver(), ctx.workspace_id)? } else { None };            let family = row.as_ref().and_then(|row| row["family"].as_str()).filter(|family| !THEME_FAMILIES.contains(family));            let unshipped = family.map(|family| {                (drawn.definition["id"].as_str().unwrap_or_default().to_string(), family.to_string(), ctx.workspace_id.to_string())            });            Ok(json!({ "drawn": drawn, "unshipped": unshipped }))        })        .map(|mut read| {            (read["drawn"].take(), serde_json::from_value::<Option<(String, String, String)>>(read["unshipped"].take()).ok().flatten())        })        .map_err(|reason| MethodError::new("unreadable", reason))?;    if let Some((theme, family, database)) = unshipped {        let said = format!("the theme {theme:?} names the family {family:?}, which this build does not ship; it is drawn as paper");        // The read stands whatever the note does: a database this device may        // not write (a guest's) still draws, and says why it wrote nothing.        let noted = say_unshipped(client, &theme, &family, &database).err().map(|why| format!("; the Feedback note was not written: {why}"));        if answer.get("passed_over").and_then(Value::as_str).is_none() {            answer["passed_over"] = Value::from(said + noted.as_deref().unwrap_or(""));        }    }    Ok(answer)}/// The one Feedback row for a family this build does not ship, unless this/// database already has it. The sentence names the database as the owner/// knows it — the name the list of databases draws — and its id is kept only/// in the row's detail (`context.themeFallback.databaseId`).fn say_unshipped(client: &ClientController, theme: &str, family: &str, database_id: &str) -> Result<(), String> {    // Read before the write: the name comes off the list of databases, which    // opens each file on its own, not inside this database's write.    let name = crate::phone::databases::name_of(client, database_id)?;    client        .write_rows("definitions.theme", &mut |ctx| {            let mut context = Map::new();            context.insert("platform".into(), Value::from(PLATFORM));            context.insert(                "themeFallback".into(),                json!({ "family": family, "theme": theme, "database": name, "databaseId": ctx.workspace_id }),            );            let place = name.as_ref().map_or_else(|| "this database".to_string(), |name| format!("the database {name:?}"));            let note = format!(                "The theme {theme:?} in {place} names the family {family:?}, \                 which this build does not ship, so it is drawn as paper."            );            let key = format!("theme-fallback:{}:{family}", ctx.workspace_id);            file_once(ctx, &key, &note, context).map(Value::from)        })        .map(|_| ())}pub fn save(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let definition = own_definition(request, "definitions.saveTheme")?;    if request.get("dry_run").and_then(Value::as_bool) == Some(true) {        return client.read_rows("definitions.saveTheme", &mut |ctx| {            cotton_tools::presentation::preview_theme(ctx, &definition).map_err(|why| why.to_string())        }).map_err(|why| MethodError::new("bad_theme", why));    }    cotton_tools::presentation::validate_theme(&definition).map_err(|why| MethodError::new("bad_theme", why.to_string()))?;    let mut answer = client.write_rows("definitions.saveTheme", &mut |ctx| {        cotton_tools::presentation::save_theme_tool(ctx, json!({"definition":definition}).as_object().unwrap()).map_err(|why| why.to_string())    }).map(crate::authoring::own_answer).map_err(|why| MethodError::new("theme_failed", why))?;    answer["theme"] = definition;    answer["receipt"] = json!("Theme changed");    answer["undo"] = json!({"method":"records.undo","args":{"change_id":answer["change"]["id"]}});    Ok(answer)}/// This owner-device act uses the same undo as every record page.pub fn undo(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    client.write_rows("definitions.undoTheme", &mut |ctx| {        if !matches!(ctx.writer_actor(), Some(cotton_store::actor::Actor::Owner(_))) {            return Err("Only the owner can undo a theme from the device page".into());        }        let last = cotton_tools::presentation::last_theme_change(ctx.read.driver(), ctx.workspace_id)?            .ok_or_else(|| "There is no theme change to undo".to_string())?;        if request.get("change_id").and_then(Value::as_str) != Some(last.id.as_str()) {            return Err("The theme changed after this page was read; open the device page again".into());        }        cotton_tools::mcp::handlers::tables::undo(ctx, json!({"change_id":last.id}).as_object().unwrap()).map_err(|why| why.to_string())    }).map(crate::authoring::own_answer).map_err(|why| MethodError::new("theme_failed", why))}/// `developer.wearThemeRow {definition}` — COTTON DEV ONLY: the database's own/// theme row written as a NEWER build would sync it in, held only to the/// tolerant read's check (`ThemeDefinition::validate`), not to what this build/// draws — so a walk can make a database wear a family this build does not/// ship and see it drawn as `paper` and said once in Feedback (§9). The real/// Cotton refuses it by name.pub fn wear_row(handle: &crate::handle::CottonHandle, request: &Value) -> Result<Value, MethodError> {    if handle.flavor() != cotton_core::flavor::Flavor::Dev {        return Err(MethodError::new("not_dev", "developer.wearThemeRow answers only in Cotton Dev"));    }    let definition = own_definition(request, "developer.wearThemeRow")?;    serde_json::from_value::<ThemeDefinition>(definition.clone())        .map_err(|error| error.to_string())        .and_then(|theme| theme.validate().map_err(|error| error.to_string()))        .map_err(|why| MethodError::new("bad_theme", why))?;    write_own(&handle.client(), definition, "developer.wearThemeRow")}/// The request's definition, as the database's own row.fn own_definition(request: &Value, method: &str) -> Result<Value, MethodError> {    let mut definition = request        .get("definition")        .filter(|value| value.is_object())        .cloned()        .ok_or_else(|| MethodError::new("bad_request", format!("{method} takes the theme's definition")))?;    definition["id"] = Value::from(OWN_THEME);    Ok(definition)}/// Write `definition` as the database's own theme row; the answer carries/// the receipt and the undo that puts back what was worn.fn write_own(client: &ClientController, definition: Value, method: &str) -> Result<Value, MethodError> {    let mut answer = client        .write_rows(method, &mut |ctx| {            let before = cotton_tools::presentation::theme_overrides(ctx.read.driver(), ctx.workspace_id)?                .unwrap_or_else(|| json!({ "id": OWN_THEME }));            let exists = !ctx                .read                .driver()                .all(                    &format!("SELECT id FROM {THEME_DEFINITIONS} WHERE workspace_id = ? AND id = ?"),                    &[SqlValue::Text(ctx.workspace_id.into()), SqlValue::Text(OWN_THEME.into())],                )                .map_err(|error| error.to_string())?                .is_empty();            let mut patch = Map::new();            patch.insert("id".into(), Value::from(OWN_THEME));            patch.insert("definition".into(), definition.clone());            patch.insert("builtin".into(), Value::Bool(false));            if exists {                patch.insert("updated_at".into(), Value::from(cotton_tools::mcp::handlers::common::now_iso(ctx)));                cotton_tools::mcp::handlers::common::update_row(ctx, THEME_DEFINITIONS, OWN_THEME, patch)            } else {                cotton_tools::mcp::handlers::common::insert_row(ctx, THEME_DEFINITIONS, OWN_THEME, patch)            }            .map_err(|error| error.to_string())?;            Ok(json!({ "theme": definition, "before": before }))        })        .map(crate::authoring::own_answer)        .map_err(|error| MethodError::new("theme_failed", error))?;    // THE SHARED RULES' RECEIPT AND UNDO, as recolour's: what happened in    // words, and the save with what was worn before.    let before = answer.as_object_mut().and_then(|answer| answer.remove("before")).unwrap_or(json!({ "id": OWN_THEME }));    answer["receipt"] = json!("Theme changed");    answer["undo"] = json!({ "method": "definitions.saveTheme", "args": { "definition": before } });    Ok(answer)}#[cfg(test)]mod tests {    use super::*;    use crate::handle::CottonHandle;    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};    fn open(path: &std::path::Path) -> CottonHandle {        open_as(path, cotton_core::flavor::Flavor::Dev)    }    fn open_as(path: &std::path::Path, flavor: cotton_core::flavor::Flavor) -> CottonHandle {        CottonHandle::open(crate::handle::OpenConfig {            mode: crate::handle::OpenMode::Phone { container_path: path.to_string_lossy().into(), previous_container_path: None },            app_version: None,            time_zone: Some("Etc/UTC".into()),            device_secret: Some(URL_SAFE_NO_PAD.encode([23u8; 32])),            vault_secret: None,            flavor,            manifest: None,        })        .unwrap()    }    fn started(dir: &std::path::Path) -> CottonHandle {        let handle = open(dir);        crate::methods::dispatch(&handle, "workspace.startLocal", &json!({})).unwrap();        handle    }    extern "C" fn collect(ctx: *mut std::ffi::c_void, line: *const std::ffi::c_char) {        let seen = unsafe { &*(ctx as *const std::sync::Mutex<Vec<String>>) };        seen.lock().expect("the event record").push(unsafe { std::ffi::CStr::from_ptr(line) }.to_string_lossy().to_string());    }    /// RULE: The device's theme Undo uses the last record change and rejects a stale page, so a tap cannot undo a newer assistant edit the owner has not seen.    #[test]    fn device_undo_rejects_a_stale_change_and_restores_the_last_row() {        let dir = tempfile::tempdir().unwrap();        let handle = started(dir.path());        let save = |name: &str| crate::methods::dispatch(&handle, "definitions.saveTheme", &json!({"definition":{"name":name}})).unwrap();        let first = save("First");        let preview = crate::methods::dispatch(&handle, "definitions.saveTheme", &json!({"definition":{"name":"Preview"},"dry_run":true})).unwrap();        assert_eq!(preview["valid"], true);        let last = || handle.client().read_rows("test.themeLast", &mut |ctx| Ok(json!(cotton_tools::presentation::last_theme_change(ctx.read.driver(), ctx.workspace_id)?.map(|change| change.id)))).unwrap();        assert_eq!(last(), first["change"]["id"]);        let second = save("Second");        assert!(crate::methods::dispatch(&handle, "definitions.undoTheme", &json!({"change_id":first["change"]["id"]})).is_err());        crate::methods::dispatch(&handle, "definitions.undoTheme", &json!({"change_id":second["change"]["id"]})).unwrap();        let worn = crate::methods::dispatch(&handle, "definitions.theme", &json!({})).unwrap();        assert_eq!(worn["definition"]["name"], "First");        assert_eq!(last(), first["change"]["id"]);    }    /// RULE: The device page's Undo puts back the previous theme row byte for byte and fires the data event naming the theme table, so every open screen redraws in the theme the database wore before.    #[test]    fn device_undo_restores_the_row_bytes_and_redraws() {        let dir = tempfile::tempdir().unwrap();        let handle = started(dir.path());        let save = |definition: Value| crate::methods::dispatch(&handle, "definitions.saveTheme", &json!({"definition": definition})).unwrap();        let row = || handle.client().with_file(|file| {            Ok(file.driver.get("SELECT definition, builtin, builtin_hash, builtin_stamp, created_at, updated_at FROM cotton_theme_definitions WHERE id = 'database'", &[])                .map_err(|e| e.to_string())?                .map(|row| format!("{row:?}")))        }).unwrap();        save(json!({"name": "First", "family": "plain", "palette": {"light": {"accent": "#112233"}}}));        let middle = row();        let second = save(json!({"name": "Second", "family": "paper", "scale": {"tokens": {"radius": 20}}}));        assert_ne!(row(), middle);        let seen = Box::new(std::sync::Mutex::new(Vec::<String>::new()));        handle.events().subscribe(&*seen as *const _ as *mut std::ffi::c_void, Some(collect));        crate::methods::dispatch(&handle, "definitions.undoTheme", &json!({"change_id": second["change"]["id"]})).unwrap();        handle.events().subscribe(std::ptr::null_mut(), None);        assert_eq!(row(), middle, "the previous row, byte for byte");        let events: Vec<Value> = seen.lock().expect("the event record").iter().filter_map(|line| serde_json::from_str(line).ok()).collect();        assert!(            events.iter().any(|event| event["kind"] == "data"                && event["payload"]["tables"].as_array().is_some_and(|tables| tables.contains(&json!(THEME_DEFINITIONS)))),            "an undo only redraws if the theme table reaches the readers: {events:?}"        );    }    /// RULE: Theme saves write `database`, refuse unshipped families, and undo to the raw prior override so later shipped keys are never baked into authoring data.    #[test]    fn a_saved_theme_is_worn_a_strange_one_refused_and_the_undo_puts_paper_back() {        let dir = tempfile::tempdir().unwrap();        let handle = started(dir.path());        // What creation gave the database: its own theme, its cap colour.        let created = crate::methods::dispatch(&handle, "definitions.theme", &json!({})).unwrap();        let seen = Box::new(std::sync::Mutex::new(Vec::<String>::new()));        handle.events().subscribe(&*seen as *const _ as *mut std::ffi::c_void, Some(collect));        let refused = crate::methods::dispatch(&handle, "definitions.saveTheme", &json!({"definition": {"family": "neon"}}))            .expect_err("an unshipped family is refused");        assert_eq!(refused.code, "bad_theme");        let saved = crate::methods::dispatch(            &handle,            "definitions.saveTheme",            &json!({"definition": {"id": "anything", "name": "Brand", "family": "plain", "palette": {"light": {"accent": "#112233FF"}}}}),        )        .unwrap();        assert_eq!(saved["receipt"], "Theme changed");        assert_eq!(saved["undo"], json!({"method": "records.undo", "args": {"change_id": saved["change"]["id"]}}));        let worn = crate::methods::dispatch(&handle, "definitions.theme", &json!({})).unwrap();        assert_eq!(worn["drawn"], "row");        assert_eq!(worn["definition"]["id"], "database", "the database's own row, whatever id was sent");        assert_eq!(worn["definition"]["family"], "plain");        let stored_override = || handle.client().with_file(|file| {            Ok(file.driver.get("SELECT definition FROM cotton_theme_definitions WHERE id = 'database'", &[])                .map_err(|error| error.to_string())?.unwrap().text("definition").unwrap().to_string())        }).unwrap();        let first_override = stored_override();        let mut authored: Value = serde_json::from_str(&first_override).unwrap();        authored.as_object_mut().unwrap().remove("base_hash");        assert_eq!(authored, json!({"id": "database", "name": "Brand", "family": "plain", "palette": {"light": {"accent": "#112233FF"}}}));        seen.lock().expect("the event record").clear();        let changed = crate::methods::dispatch(            &handle,            "definitions.saveTheme",            &json!({"definition": {"family": "plain", "acts": {"destroys": {"stock": "tan"}}}}),        )        .unwrap();        assert_eq!(            serde_json::from_str::<Value>(changed["change"]["before"]["definition"].as_str().unwrap()).unwrap(),            json!({"id": "database", "name": "Brand", "family": "plain", "palette": {"light": {"accent": "#112233FF"}}}),            "undo keeps the raw override, not the reader's resolved theme"        );        let changed_read = crate::methods::dispatch(&handle, "definitions.theme", &json!({})).unwrap();        assert_eq!(changed_read["definition"]["acts"]["destroys"]["stock"], "tan");        handle.events().subscribe(std::ptr::null_mut(), None);        let events: Vec<Value> = seen.lock().expect("the event record").iter().filter_map(|line| serde_json::from_str(line).ok()).collect();        // RULE: Saving a stock invalidates cotton_theme_definitions through the data event path, so the subscribed reader redraws the changed theme.        assert!(            events.iter().any(|event| event["kind"] == "data"                && event["payload"]["tables"].as_array().is_some_and(|tables| tables.contains(&json!(THEME_DEFINITIONS)))),            "a reader only redraws the saved stock if the theme table reaches it: {events:?}"        );        let reversed = crate::methods::dispatch(&handle, "records.undo", &changed["undo"]["args"]).unwrap();        assert_eq!(stored_override(), first_override, "undo restores exactly the first sparse override, with no shipped keys");        assert_eq!(            serde_json::from_str::<Value>(reversed["change"]["before"]["definition"].as_str().unwrap()).unwrap(),            json!({"id": "database", "family": "plain", "acts": {"destroys": {"stock": "tan"}}}),            "undo's own before-image also keeps only authored keys"        );        crate::methods::dispatch(&handle, "records.undo", &saved["undo"]["args"]).unwrap();        let undone = crate::methods::dispatch(&handle, "definitions.theme", &json!({})).unwrap();        assert_eq!(            undone["definition"], created["definition"],            "undo of the first save draws what creation wrote"        );        handle            .client()            .with_file(|file| {                let rows = file                    .driver                    .all("SELECT builtin FROM cotton_theme_definitions WHERE id = 'database'", &[])                    .map_err(|e| e.to_string())?;                assert_eq!(rows.len(), 1, "undo puts back the row creation wrote");                Ok(())            })            .unwrap();    }    /// RULE: Saving the database's own theme undoes to the raw theme that was worn, even when that row belongs to a shipped theme id.    #[test]    fn a_theme_save_undo_keeps_the_raw_previously_worn_theme() {        let dir = tempfile::tempdir().unwrap();        let handle = started(dir.path());        let plain = json!({"id": "plain", "family": "plain", "acts": {"destroys": {"stock": "tan"}}});        handle            .client()            .write_rows("test.plantTheme", &mut |ctx| {                cotton_tools::presentation::save_theme(ctx, &plain)                    .map(|_| Value::Null)                    .map_err(|error| error.to_string())            })            .unwrap();        let saved = crate::methods::dispatch(            &handle,            "definitions.saveTheme",            &json!({"definition": {"family": "paper", "acts": {"destroys": {"stock": "rose"}}}}),        )        .unwrap();        crate::methods::dispatch(&handle, "records.undo", &saved["undo"]["args"]).unwrap();        let worn = crate::methods::dispatch(&handle, "definitions.theme", &json!({})).unwrap();        assert_eq!(worn["definition"], ThemeDefinition::strict(&plain).unwrap().resolved());    }    /// RULE: An unshipped family stays visible for fallback and writes one Feedback row naming the family and database; repeated reads do not write more.    #[test]    fn an_unshipped_family_is_said_once_in_feedback() {        let dir = tempfile::tempdir().unwrap();        let handle = started(dir.path());        let id = crate::methods::dispatch(&handle, "read.databases", &json!({})).unwrap()["databases"][0]["databaseId"]            .as_str()            .unwrap()            .to_string();        // Named as MCP names it — the workspace row's `name`; the app never        // renames a database (owner, 16 Oct 2026).        let client = handle.client();        let scope = client.name_database(Some(id.as_str())).unwrap();        client            .write_rows("database name fixture", &mut |ctx| {                let workspace = ctx.workspace_id.to_string();                cotton_tools::mcp::handlers::common::update_row(                    ctx,                    "cotton_workspaces",                    &workspace,                    json!({ "name": "Example Garden" }).as_object().unwrap().clone(),                )                .map_err(|e| e.to_string())?;                Ok(json!({}))            })            .unwrap();        drop(scope);        // A newer build's row, as the walk makes one: the save refuses the        // family this build does not ship; the Dev-only method writes it.        let refused = crate::methods::dispatch(&handle, "definitions.saveTheme", &json!({"definition": {"family": "neon"}}))            .expect_err("strict");        assert_eq!(refused.code, "bad_theme");        crate::methods::dispatch(&handle, "developer.wearThemeRow", &json!({"definition": {"family": "neon"}})).unwrap();        for _ in 0..2 {            let worn = crate::methods::dispatch(&handle, "definitions.theme", &json!({})).unwrap();            assert_eq!(worn["definition"]["family"], "paper", "drawn as the family this build ships");            assert_eq!(worn["definition"]["fallbacks"], json!(["family"]));            assert!(worn["passed_over"].as_str().unwrap().contains("\"neon\""));        }        handle            .client()            .with_file(|file| {                let rows = file                    .driver                    .all("SELECT body, context FROM cotton_feedback", &[])                    .map_err(|e| e.to_string())?;                assert_eq!(rows.len(), 1, "said once, not at every read");                let body = rows[0].text("body").unwrap();                assert!(body.contains("\"neon\""));                assert!(body.contains("\"Example Garden\""), "named as the owner knows it: {body}");                assert!(!body.contains(file.workspace_id), "the id is detail, not the sentence: {body}");                let context: Value = serde_json::from_str(rows[0].text("context").unwrap()).unwrap();                assert_eq!(context["themeFallback"]["family"], "neon");                assert_eq!(context["themeFallback"]["databaseId"], file.workspace_id);                assert_eq!(context["themeFallback"]["database"], "Example Garden");                Ok(())            })            .unwrap();    }    /// RULE: developer.wearThemeRow — the walk's way to plant a theme row a newer build would sync in — answers only in Cotton Dev; the real Cotton refuses it by name and writes nothing.    #[test]    fn the_real_cotton_refuses_the_developer_theme_row() {        let dir = tempfile::tempdir().unwrap();        let handle = open_as(dir.path(), cotton_core::flavor::Flavor::Real);        crate::methods::dispatch(&handle, "workspace.startLocal", &json!({})).unwrap();        let before = crate::methods::dispatch(&handle, "definitions.theme", &json!({})).unwrap();        let refused = crate::methods::dispatch(&handle, "developer.wearThemeRow", &json!({"definition": {"family": "neon"}}))            .expect_err("the real Cotton");        assert_eq!(refused.code, "not_dev");        let worn = crate::methods::dispatch(&handle, "definitions.theme", &json!({})).unwrap();        assert_eq!(worn, before, "nothing was written");    }}