Cotton code
288 lines · 13.7 KB · RustRaw
//! `look { app, light?, dark?, ink?, face?, size?, reset? }` (assets/design/shared/DECISIONS.md "Look"): one app's//! paper, ink and type, read; with any choice given, that choice written first (`reset` puts every one back to the//! app's default). The choices sync as `face_settings` rows (cotton_core::look's `rows`), so both phones agree: Words//! keeps its own rows (`notes`, `notes_dark`), so what a person chose before Look carries over.use cotton_core::look::{self, AppLook};use cotton_core::rules::shell_lines::LineSet;use serde_json::{json, Map, Value};use crate::methods::MethodError;use crate::CottonHandle;fn bad(why: impl Into<String>) -> MethodError {    MethodError::new("bad_request", why.into())}/// Words' `font` column before Look (sans, serif, mono, system), read as a face choice; and the face written back/// there so a build before Look draws the nearest.pub(crate) fn words_face_of_font(font: &str) -> Option<&'static str> {    match font {        "sans" | "system" => Some("own"),        "serif" => Some("serif"),        "mono" | "typewriter" => Some("typewriter"),        "hyperlegible" => Some("hyperlegible"),        "dyslexic" => Some("dyslexic"),        _ => None,    }}/// What the `font` column keeps for a face: its own choices (publisher, serif, sans, dyslexic, mono, system), the/// nearest where it has none, so a build before Look draws close to it.pub(crate) fn words_font_of_face(face: &str) -> &'static str {    match face {        "serif" => "serif",        "typewriter" => "mono",        "dyslexic" => "dyslexic",        _ => "sans",    }}fn row(handle: &CottonHandle, key: &str) -> Result<Map<String, Value>, MethodError> {    super::notes::settings_row(handle, key)}/// Whether the `face_settings` this copy's object serves has Look's `type_face`. A server deployed before Look (the/// owner's live server on 23 Nov 2026, Words 26, Days 23, Story 26, Comms 25: "choosing a font changes nothing")/// serves the table of before, and the copy refused the whole write over the column ("no column type_face"), while/// the size, the papers and the inks, in columns of before, went.fn serves_type_face(handle: &CottonHandle) -> bool {    super::cotton_chat::read(&handle.client(), "look.served", |ctx| {        let rows = cotton_tools::definitions::definition_rows(ctx, Some("face_settings")).map_err(|e| e.to_string())?;        Ok(json!(rows.is_empty()            || rows.iter().any(|row| {                let definition: Value = serde_json::from_str(&row.definition).unwrap_or(Value::Null);                definition["columns"].as_array().into_iter().flatten().any(|c| c["key"] == "type_face")            })))    })    .map(|served| served.as_bool().unwrap_or(true))    .unwrap_or(true)}/// The faces chosen on this phone while its server has no `type_face` (`look-faces.json` beside the copy, by row):/// read back here until the server has the column, when the next choice is written into the synced row.fn kept_faces_path(handle: &CottonHandle) -> std::path::PathBuf {    handle.client().layout().client_dir().join("look-faces.json")}fn kept_faces(handle: &CottonHandle) -> Map<String, Value> {    std::fs::read(kept_faces_path(handle)).ok().and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok()).and_then(|v| v.as_object().cloned()).unwrap_or_default()}fn keep_face(handle: &CottonHandle, key: &str, face: Option<&Value>) -> Result<(), MethodError> {    let mut faces = kept_faces(handle);    match face {        Some(face) => faces.insert(key.to_string(), face.clone()),        None => faces.remove(key),    };    // not a copy: the kept faces list.    std::fs::write(kept_faces_path(handle), Value::Object(faces).to_string()).map_err(|e| MethodError::new("unwritable", e.to_string()))}/// A write's `type_face` fitted to the server: kept in the row where the served table has the column (and no longer/// beside the copy), else beside the copy and out of the write. Every writer of `face_settings`' face goes through it/// (Look, and Words' `notes.settings`).pub(crate) fn fit_face(handle: &CottonHandle, key: &str, patch: &mut Map<String, Value>) -> Result<(), MethodError> {    let Some(face) = patch.get("type_face").cloned() else { return Ok(()) };    if serves_type_face(handle) {        keep_face(handle, key, None)    } else {        patch.remove("type_face");        keep_face(handle, key, Some(&face))    }}fn write_row(handle: &CottonHandle, key: &str, paper: &str, mut patch: Map<String, Value>) -> Result<(), MethodError> {    fit_face(handle, key, &mut patch)?;    if patch.is_empty() {        return Ok(());    }    let mut row = super::notes::rewritable(row(handle, key)?);    row.insert("table".into(), json!(key));    row.entry("face").or_insert(json!(paper));    row.extend(patch);    super::records::call(&handle.client(), "records.create", &json!({ "table": "face_settings", "data": Value::Object(row) }))?;    Ok(())}/// The choices as they stand: (light paper, dark paper, ink, face, size).pub(crate) struct Chosen {    pub light: String,    pub dark: String,    pub ink: String,    pub face: String,    pub size: f64,}/// Comms' text size before Look, kept beside the copy (`chat-theme.json`'s `text`).fn comms_kept_scale(handle: &CottonHandle) -> Option<f64> {    let path = handle.client().layout().client_dir().join("chat-theme.json");    let file: Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;    let id = file.get("text")?.as_str()?;    look::kit().scale.iter().find(|s| s.id == id).map(|s| s.value)}pub(crate) fn chosen(handle: &CottonHandle, app: &str, look: &AppLook) -> Result<Chosen, MethodError> {    let d = look.defaults();    let held = row(handle, &look.rows[0])?;    let held_dark = row(handle, &look.rows[1])?;    let said = |row: &Map<String, Value>, column: &str| row.get(column).and_then(Value::as_str).map(str::to_string);    let paper = |id: Option<String>, default: &str| {        let id = id.map(|id| cotton_core::rules::notes_writing::writing().renamed.get(&id).cloned().filter(|_| app == "notes").unwrap_or(id));        id.filter(|id| look.paper(id).is_some()).unwrap_or_else(|| default.to_string())    };    let face = said(&held, "type_face")        .or_else(|| kept_faces(handle).get(&look.rows[0]).and_then(Value::as_str).map(str::to_string))        .or_else(|| if app == "notes" { said(&held, "font").and_then(|f| words_face_of_font(&f)).map(str::to_string) } else { None })        .filter(|f| look.face(f).is_some())        .unwrap_or_else(|| d.face.clone());    let size = held.get("font_size").and_then(Value::as_f64).or_else(|| if app == "messages" && held.is_empty() { comms_kept_scale(handle) } else { None });    Ok(Chosen {        light: paper(said(&held, "face"), &d.light),        dark: paper(said(&held_dark, "face"), &d.dark),        ink: said(&held, "ink").filter(|i| look.ink(i).is_some()).unwrap_or_else(|| d.ink.clone()),        face,        size: size.filter(|s| look.offers_size(*s)).unwrap_or(d.size),    })}pub(crate) fn call(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let app = request.get("app").and_then(Value::as_str).ok_or_else(|| bad("look names its `app`: notes, days, messages, story, keys, mail or sites"))?;    let look = look::app(app).ok_or_else(|| bad(format!("no app {app} has a look")))?;    let d = look.defaults();    let text = |key: &str| request.get(key).and_then(Value::as_str);    let mut patch = Map::new();    let mut dark_paper = None;    if request.get("reset").and_then(Value::as_bool) == Some(true) {        patch.insert("face".into(), json!(d.light));        patch.insert("ink".into(), json!(d.ink));        patch.insert("type_face".into(), json!(d.face));        patch.insert("font_size".into(), json!(d.size));        if app == "notes" {            patch.insert("font".into(), json!(words_font_of_face(&d.face)));        }        dark_paper = Some(d.dark.clone());    }    // `light_paper`/`dark_paper` as the iPhone first asked for them (look-ios, 23 Nov 2026), `light`/`dark` as answered.    if let Some(id) = text("light").or(text("light_paper")) {        look.paper(id).ok_or_else(|| bad(format!("{app} has no paper {id}")))?;        patch.insert("face".into(), json!(id));    }    if let Some(id) = text("dark").or(text("dark_paper")) {        look.paper(id).ok_or_else(|| bad(format!("{app} has no paper {id}")))?;        dark_paper = Some(id.to_string());    }    if let Some(id) = text("ink") {        look.ink(id).ok_or_else(|| bad(format!("{app} has no ink {id}")))?;        patch.insert("ink".into(), json!(id));    }    if let Some(id) = text("face") {        look.face(id).ok_or_else(|| bad(format!("{app} has no face {id}")))?;        patch.insert("type_face".into(), json!(id));        if app == "notes" {            patch.insert("font".into(), json!(words_font_of_face(id)));        }    }    if let Some(size) = request.get("size").and_then(Value::as_f64) {        if !look.offers_size(size) {            return Err(bad(format!("{app} offers no size {size}")));        }        patch.insert("font_size".into(), json!(size));    }    if !patch.is_empty() {        write_row(handle, &look.rows[0], &d.light, patch)?;    }    if let Some(paper) = dark_paper {        write_row(handle, &look.rows[1], &d.dark, Map::from_iter([("face".to_string(), json!(paper))]))?;    }    answer(handle, app, look)}fn answer(handle: &CottonHandle, app: &str, look: &AppLook) -> Result<Value, MethodError> {    let lines = LineSet::shipped("look").ok_or_else(|| MethodError::new("unreadable", "no look lines"))?;    let say = |id: &str| lines.say(id, &[]).unwrap_or_default();    let app_name = say(&format!("apps.{app}"));    let notes = LineSet::shipped("notes");    let paper_name = |id: &str| match app {        "notes" => notes.as_ref().and_then(|l| l.say(&format!("theme.names.{id}"), &[])).unwrap_or_default(),        _ => say(&format!("papers.{app}.{id}")),    };    let c = chosen(handle, app, look)?;    let d = look.defaults();    let ink = look.ink(&c.ink).expect("a chosen ink is the app's");    let light = look.paper(&c.light).expect("a chosen paper is the app's");    let dark = look.paper(&c.dark).expect("a chosen paper is the app's");    let papers: Vec<Value> = look        .papers        .iter()        .map(|p| json!({ "id": p.id, "name": paper_name(&p.id), "light": look.inked(p, ink, false), "dark": look.inked(p, ink, true) }))        .collect();    let inks: Vec<Value> = look        .inks        .iter()        .map(|i| {            json!({                "id": i.id, "name": say(&format!("inks.{}", i.id)),                "light": look.inked(light, i, false)[&look.accent], "dark": look.inked(dark, i, true)[&look.accent],            })        })        .collect();    let faces: Vec<Value> = look::kit()        .choices        .iter()        .filter_map(|choice| {            let face = look.face(choice)?;            let name = if choice == "own" { face.family.clone() } else { say(&format!("faces.{choice}")) };            Some(json!({ "id": choice, "name": name, "family": face.family, "files": face.files }))        })        .collect();    let sizes: Vec<Value> = look        .size_steps()        .into_iter()        .map(|(value, id)| json!({ "value": value, "label": id.map(|id| say(&format!("sizes.{id}"))).unwrap_or_else(|| format!("{value}")) }))        .collect();    let is_default = c.light == d.light && c.dark == d.dark && c.ink == d.ink && c.face == d.face && (c.size - d.size).abs() < 1e-6;    let fill = |id: &str| lines.say(id, &[("app", app_name.as_str())]).unwrap_or_default();    let face_name = faces.iter().find(|f| f["id"] == c.face.as_str()).and_then(|f| f["name"].as_str()).unwrap_or_default().to_string();    // The row as the screen stands: the paper on it first, and when the other comes (it follows the phone's    // appearance). Post on his phone, 26 Nov 2026: "Sage · Night" on a light screen read as if Night were on.    let papers_named = [("light", paper_name(&c.light)), ("dark", paper_name(&c.dark))];    let named: Vec<(&str, &str)> = papers_named.iter().map(|(k, v)| (*k, v.as_str())).collect();    let row_lines = json!({        "light": lines.say("row_light", &named).unwrap_or_default(),        "dark": lines.say("row_dark", &named).unwrap_or_default(),    });    let mut answer = json!({        "app": app,        "light": c.light,        "dark": c.dark,        "ink": c.ink,        "face": c.face,        "size": c.size,        "sizes_are": look.sizes,        "defaults": d,        "default": is_default,        "papers": papers,        "inks": inks,        "faces": faces,        "sizes": sizes,        "colours": { "light": look.inked(light, ink, false), "dark": look.inked(dark, ink, true) },        "line": lines.say("row", &[("light", &paper_name(&c.light)), ("dark", &paper_name(&c.dark))]).unwrap_or_default(),        "face_name": face_name,        "preview": lines.value(&format!("preview.{app}")).unwrap_or(Value::Null),        "words": {            "title": say("title"), "paper": say("paper"), "ink": say("ink"), "text": say("text"), "face": say("face"),            "size": say("size"), "light": say("light"), "dark": say("dark"), "for_light": say("for_light"), "for_dark": say("for_dark"),            "when_light": say("when_light"), "when_dark": say("when_dark"),            "smaller": say("smaller"), "larger": say("larger"), "chosen": say("chosen"), "more": say("more"), "sample": say("sample"),            "reset": say("reset.title"), "reset_title": say("reset.ask_title"), "reset_ask": fill("reset.ask"), "reset_yes": say("reset.yes"), "reset_no": say("reset.no"),            "reset_done": fill("reset.done"),        },    });    answer["lines"] = row_lines;    Ok(answer)}#[cfg(test)]#[path = "look_tests.rs"]mod tests;