Cotton code
374 lines · 18.5 KB · RustRaw
//! THE SHELL'S LINES ARE ROWS (architect, 21 Oct 2026, lane shelllines)://! every sentence the app says in its own voice — `kits/shell/lines/*.json`://! `sync`, `gate`, `refusal`, `pairing`, `bin`, `backup`, `empty`, `money`,//! `activity`, `home`, `filing`, `reminders`, `news`, `memory`, `email`, `people`, `albums`… — is//! written into the database at creation as rows of the `lines` shell//! table, one row per line, so a rewording is a row a person//! (or an assistant) changes and every device says from the next sync.//!//! A row is `(set, line, words)`: `set` the file's id, `line` the dotted path//! of one string in that file (`lines.up_to_date`, `ages.now`), `words` the//! template. Its id is `set.line`, so a database holds at most one of each.//!//! The core resolves a set from the database's rows FIRST and falls back to//! the compiled kit copy only for a line the database has no row for (a//! database made before its lines were written, or a line a later build//! added). A row whose path the kit copy does not have is ignored, and so is//! a row holding words the kit once said there and has since changed//! (`kits/shell/reworded.json`): the database was written with them, nobody//! chose them, and the kit's present words are said.use serde_json::Value;/// The shell table the rows live in.pub const TABLE: &str = "lines";/// The kit's line files, `(set, json)`, compiled in.pub const SHIPPED: &[(&str, &str)] = &[    ("sync", super::sync_status::SHIPPED),    ("gate", include_str!("../../kits/shell/lines/gate.json")),    ("refusal", include_str!("../../kits/shell/lines/refusal.json")),    ("bin", include_str!("../../kits/shell/lines/bin.json")),    ("backup", include_str!("../../kits/shell/lines/backup.json")),    ("empty", include_str!("../../kits/shell/lines/empty.json")),    ("money", include_str!("../../kits/shell/lines/money.json")),    ("activity", include_str!("../../kits/shell/lines/activity.json")),    ("home", include_str!("../../kits/shell/lines/home.json")),    ("reminders", include_str!("../../kits/shell/lines/reminders.json")),    ("dates", include_str!("../../kits/shell/lines/dates.json")),    ("dispatch", include_str!("../../kits/shell/lines/dispatch.json")),    ("documents", include_str!("../../kits/shell/lines/documents.json")),    ("reading", include_str!("../../kits/shell/lines/reading.json")),    ("memory", include_str!("../../kits/shell/lines/memory.json")),    ("email", include_str!("../../kits/shell/lines/email.json")),    ("people", include_str!("../../kits/shell/lines/people.json")),    ("albums", include_str!("../../kits/shell/lines/albums.json")),    ("music", include_str!("../../kits/shell/lines/music.json")),    ("writer", include_str!("../../kits/shell/lines/writer.json")),    ("calling", include_str!("../../kits/shell/lines/calling.json")),    ("story", include_str!("../../kits/shell/lines/story.json")),    ("days", include_str!("../../kits/shell/lines/days.json")),    ("notes", include_str!("../../kits/shell/lines/notes.json")),    ("look", include_str!("../../kits/shell/lines/look.json")),    ("chat", include_str!("../../kits/shell/lines/chat.json")),    ("contacts", include_str!("../../kits/shell/lines/contacts.json")),    ("circle", include_str!("../../kits/shell/lines/circle.json")),    ("share", include_str!("../../kits/shell/lines/share.json")),    ("cinemas", include_str!("../../kits/shell/lines/cinemas.json")),    ("code", include_str!("../../kits/shell/lines/code.json")),    ("ci", include_str!("../../kits/shell/lines/ci.json")),    ("cards", include_str!("../../kits/shell/lines/cards.json")),    ("editing", include_str!("../../kits/shell/lines/editing.json")),    ("ident", include_str!("../../kits/shell/lines/ident.json")),    ("connections", include_str!("../../kits/shell/lines/connections.json")),    ("boot", include_str!("../../kits/shell/lines/boot.json")),    ("diagnostics", include_str!("../../kits/shell/lines/diagnostics.json")),    ("search", include_str!("../../kits/shell/lines/search.json")),    ("voice", include_str!("../../kits/shell/lines/voice.json")),    ("feedback", include_str!("../../kits/shell/lines/feedback.json")),    ("settings", include_str!("../../kits/shell/lines/settings.json")),    ("developer", include_str!("../../kits/shell/lines/developer.json")),    ("record", include_str!("../../kits/shell/lines/record.json")),    ("lists", include_str!("../../kits/shell/lines/lists.json")),    ("faces", include_str!("../../kits/shell/lines/faces.json")),    ("definitions", include_str!("../../kits/shell/lines/definitions.json")),    ("board", include_str!("../../kits/shell/lines/board.json")),    ("input", include_str!("../../kits/shell/lines/input.json")),    ("capture", include_str!("../../kits/shell/lines/capture.json")),    ("conversation", include_str!("../../kits/shell/lines/conversation.json")),    ("machines", include_str!("../../kits/shell/lines/machines.json")),    ("receipts", include_str!("../../kits/shell/lines/receipts.json")),    ("devices", include_str!("../../kits/shell/lines/devices.json")),    ("projects", include_str!("../../kits/shell/lines/projects.json")),    ("history", include_str!("../../kits/shell/lines/history.json")),    ("words", include_str!("../../kits/shell/lines/words.json")),    ("databases", include_str!("../../kits/shell/lines/databases.json")),    ("chrome", include_str!("../../kits/shell/lines/chrome.json")),    ("format", include_str!("../../kits/shell/lines/format.json")),    ("legal", include_str!("../../kits/shell/lines/legal.json")),    ("samples", include_str!("../../kits/shell/lines/samples.json")),    ("host", include_str!("../../kits/shell/lines/host.json")),    ("passwords", include_str!("../../kits/shell/lines/passwords.json")),    ("vault", include_str!("../../kits/shell/lines/vault.json")),    // Cotton Secrets' own words around the vault's answers (assets/design/keys, 25 Nov 2026).    ("post", include_str!("../../kits/shell/lines/post.json")),    ("secrets", include_str!("../../kits/shell/lines/secrets.json")),    // Cotton Data: what is inside the database, read only (assets/design/data, 25 Nov 2026).    ("data", include_str!("../../kits/shell/lines/data.json")),    // RESTORE 2, the owner's own restore of an earlier day (crates/cotton-ffi/src/phone/restore.rs, 28 Nov 2026).    ("restore", include_str!("../../kits/shell/lines/restore.json")),    // Cotton Sites' own words (assets/design/sites, 25 Nov 2026).    ("sites", include_str!("../../kits/shell/lines/sites.json")),    ("health", include_str!("../../kits/shell/lines/health.json")),    ("members", include_str!("../../kits/shell/lines/members.json")),    ("unlock", include_str!("../../kits/shell/lines/unlock.json")),    ("send", include_str!("../../kits/shell/lines/send.json")),    ("meetings", include_str!("../../kits/shell/lines/meetings.json")),    // Comms' words the phone shows before the app runs (its Downloads share target's label): `system` only.    ("messages", include_str!("../../kits/shell/lines/messages.json")),    ("signin", include_str!("../../kits/shell/lines/signin.json")),    // The Mac menu bar app's panel (crates/cotton-mac/src/panel.rs).    ("macpanel", include_str!("../../kits/shell/lines/macpanel.json")),];/// One line, as a row of the `lines` table.#[derive(Debug, Clone, PartialEq, Eq)]pub struct LineRow {    pub set: String,    pub line: String,    pub words: String,}impl LineRow {    /// The row's id: `set.line`.    pub fn id(&self) -> String {        format!("{}.{}", self.set, self.line)    }}/// Keys of a line file that are the file's own, never a line. `maps` names/// the objects of the file that are MAPS (a currency's symbol by its code)/// rather than fixed lines: a database row may add a key the kit lacks to a/// map, where a row naming a line the kit lacks anywhere else is ignored.const FILE_KEYS: [&str; 3] = ["format_version", "id", "maps"];/// Every line the kit ships, as the rows a new database is written with.pub fn shipped_rows() -> Vec<LineRow> {    shipped_lines().to_vec()}/// [`shipped_rows`], decoded from the kit's line files once a process and/// shared: every new database writes all of them (`presentation::write_lines`).pub fn shipped_lines() -> &'static [LineRow] {    static ROWS: std::sync::OnceLock<Vec<LineRow>> = std::sync::OnceLock::new();    ROWS.get_or_init(decode_shipped)}fn decode_shipped() -> Vec<LineRow> {    let mut rows = Vec::new();    for (set, json) in SHIPPED {        let file: Value = serde_json::from_str(json).expect("a kit line file parses");        let Value::Object(file) = file else { continue };        for (key, value) in file.iter().filter(|(key, _)| !FILE_KEYS.contains(&key.as_str())) {            leaves(set, key, value, &mut rows);        }    }    rows}fn leaves(set: &str, path: &str, value: &Value, rows: &mut Vec<LineRow>) {    match value {        Value::String(words) => rows.push(LineRow { set: set.into(), line: path.into(), words: words.clone() }),        Value::Object(map) => {            for (segment, value) in map {                leaves(set, &format!("{path}.{segment}"), value, rows);            }        }        _ => {}    }}/// The set `set` as its kit file's JSON with every one of `rows` that names a/// line of it laid over; `None` when the kit ships no such set.pub fn resolved(set: &str, rows: &[LineRow]) -> Option<Value> {    let mut file = shipped_file(set)?.clone();    let maps: Vec<String> = file        .get("maps")        .and_then(Value::as_array)        .map(|maps| maps.iter().filter_map(Value::as_str).map(str::to_string).collect())        .unwrap_or_default();    for row in rows.iter().filter(|row| row.set == set && !earlier_kit_words(row)) {        let pointer = format!("/{}", row.line.replace('.', "/"));        if let Some(Value::String(words)) = file.pointer_mut(&pointer) {            words.clone_from(&row.words);            continue;        }        // A new key in a map: `symbols.KES` where the kit's map lacks KES.        let Some((map, key)) = row.line.split_once('.') else { continue };        if key.contains('.') || !maps.iter().any(|name| name == map) { continue }        if let Some(Value::Object(entries)) = file.get_mut(map) {            entries.entry(key.to_string()).or_insert_with(|| Value::String(row.words.clone()));        }    }    Some(file)}/// The kit's own earlier words for its lines (`kits/shell/reworded.json`).pub const REWORDED: &str = include_str!("../../kits/shell/reworded.json");/// Whether `row` holds words the kit once shipped for its line and has since/// changed: a row written when the database was made, before the rewording,/// never a person's. It is passed over, so the kit's present words are said.pub fn earlier_kit_words(row: &LineRow) -> bool {    static EARLIER: std::sync::OnceLock<std::collections::HashMap<String, Vec<String>>> = std::sync::OnceLock::new();    EARLIER        .get_or_init(|| {            let file: Value = serde_json::from_str(REWORDED).expect("reworded.json parses");            file["lines"]                .as_object()                .map(|lines| {                    lines                        .iter()                        .map(|(id, words)| (id.clone(), words.as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect()))                        .collect()                })                .unwrap_or_default()        })        .get(&row.id())        .is_some_and(|earlier| earlier.iter().any(|words| *words == row.words))}/// The kit's file for `set`, parsed once per process: a list's page says/// hundreds of lines, and each parsed the whole file afresh.fn shipped_file(set: &str) -> Option<&'static Value> {    static PARSED: std::sync::OnceLock<Vec<(&'static str, Value)>> = std::sync::OnceLock::new();    PARSED        .get_or_init(|| SHIPPED.iter().map(|(id, json)| (*id, serde_json::from_str(json).expect("a kit line file parses"))).collect())        .iter()        .find(|(id, _)| *id == set)        .map(|(_, file)| file)}/// One line of `set` — the database's row first, the kit's words for one it/// has none of — with each `{name}` in it replaced by the typed value `fills`/// gives for `name`. No composition: the template is the sentence, and a/// placeholder no fill names is left as written. `None` when the kit ships no/// such line.////// THE PICKER (contract 5): a line that has plural forms — an object of/// `one` / `other` (and any other CLDR category a language needs) — is chosen/// by the count in the `{n}` fill through CLDR plural rules. The caller may/// name the object (`late.days`) or any one of its forms (`late.days.other`);/// either way the form the count calls for is said, and `other` when the set/// has no row for that form. Without an `n` fill a named form is said as named.pub fn resolve(set: &str, line: &str, rows: &[LineRow], fills: &[(&str, &str)]) -> Option<String> {    LineSet::of_rows(set, rows)?.say(line, fills)}/// One set resolved once — the database's rows laid over the kit's file — so/// a reading that says many lines (a list of slips) reads the rows once.#[derive(Debug, Clone, PartialEq)]pub struct LineSet {    /// Shared: a shipped set is resolved once a process and each `shipped` hands out the same file.    file: std::sync::Arc<Value>,}impl LineSet {    /// The set as the kit ships it; `None` when the kit ships no such set. Resolved once a process: a reading says    /// a line per row (Story's scene list four a scene, Words' look dozens), and resolving the set for each line    /// copied the whole file every time (Story's and Words' launches, 23 Nov 2026).    pub fn shipped(set: &str) -> Option<Self> {        type Sets = std::collections::HashMap<String, Option<std::sync::Arc<Value>>>;        static SETS: std::sync::OnceLock<std::sync::Mutex<Sets>> = std::sync::OnceLock::new();        let mut sets = SETS.get_or_init(Default::default).lock().unwrap_or_else(std::sync::PoisonError::into_inner);        let file = sets.entry(set.to_string()).or_insert_with(|| resolved(set, &[]).map(std::sync::Arc::new)).clone()?;        Some(Self { file })    }    /// The set as a database says it: its rows first, the kit for the rest.    pub fn of_rows(set: &str, rows: &[LineRow]) -> Option<Self> {        if !rows.iter().any(|row| row.set == set) {            return Self::shipped(set);        }        resolved(set, rows).map(|file| Self { file: std::sync::Arc::new(file) })    }    /// A part of the set as it stands (a line, or a group of lines as an object): what a phone draws whole, as    /// Look's previews.    pub fn value(&self, path: &str) -> Option<Value> {        self.file.pointer(&format!("/{}", path.replace('.', "/"))).cloned()    }    /// One line, filled, with its plural form picked by `{n}` (see    /// [`resolve`]); `None` when the set has no such line.    pub fn say(&self, line: &str, fills: &[(&str, &str)]) -> Option<String> {        let file = &self.file;        let pointer = format!("/{}", line.replace('.', "/"));        let count = fills.iter().find(|(name, _)| *name == "n").map(|(_, value)| *value);        let words = match (file.pointer(&pointer)?, count) {            (Value::Object(forms), Some(n)) => pick(forms, n)?,            (Value::String(words), Some(n)) => match pointer.rsplit_once('/') {                Some((parent, last)) if PLURAL_FORMS.contains(&last) => match file.pointer(parent) {                    Some(Value::Object(forms)) => pick(forms, n)?,                    _ => words.as_str(),                },                _ => words.as_str(),            },            (Value::String(words), None) => words.as_str(),            _ => return None,        };        let mut words = words.to_string();        for (name, value) in fills {            words = words.replace(&format!("{{{name}}}"), value);        }        Some(words)    }}/// The CLDR plural categories, as the last segment of a line's path.const PLURAL_FORMS: [&str; 6] = ["zero", "one", "two", "few", "many", "other"];/// The form of `forms` the count `n` calls for, `other` when that one is/// missing, then `many`: the line files and tool definitions written before/// the picker (bin, empty, the figures) say their plural as `one`/`many`,/// and that data format stays — new lines write `one`/`other`.fn pick<'a>(forms: &'a serde_json::Map<String, Value>, n: &str) -> Option<&'a str> {    // An explicit `zero` form says nought in words ("No addresses yet"), where English's rule would call it `other`.    if n.trim() == "0" {        if let Some(Value::String(words)) = forms.get("zero") {            return Some(words.as_str());        }    }    let form = plural_form(n);    forms.get(form).or_else(|| forms.get("other")).or_else(|| forms.get("many"))?.as_str()}/// English cardinal rules, compiled CLDR data (English only for now).fn english() -> icu_locale_core::Locale {    icu_locale_core::locale!("en")}/// The CLDR cardinal category of the count `n` as written (`1`, `21`, `1.5`,/// `1,204` — grouping separators are read past); `other` for anything that is/// not a number.pub fn plural_form(n: &str) -> &'static str {    use icu_decimal::input::Decimal;    use icu_plurals::{PluralCategory, PluralRules};    let digits: String = n.chars().filter(|c| *c != ',').collect();    let Ok(count) = digits.trim().parse::<Decimal>() else { return "other" };    let Ok(rules) = PluralRules::try_new_cardinal(english().into()) else { return "other" };    match rules.category_for(&count) {        PluralCategory::Zero => "zero",        PluralCategory::One => "one",        PluralCategory::Two => "two",        PluralCategory::Few => "few",        PluralCategory::Many => "many",        PluralCategory::Other => "other",    }}/// A whole number as a person reads it, grouped by CLDR's decimal symbols/// (`1,204`, `-12,000`).pub fn number(n: i64) -> String {    number_in(n, english())}/// A whole number grouped as the named CLDR locale groups it — `en-IN` says/// `12,34,567` — where the data names the locale (the money set's/// `grouping`, by currency), never the device's. A locale that does not parse/// is grouped as English.pub fn number_grouped(n: i64, locale: &str) -> String {    number_in(n, locale.parse().unwrap_or_else(|_| english()))}fn number_in(n: i64, locale: icu_locale_core::Locale) -> String {    use icu_decimal::{DecimalFormatter, input::Decimal};    match DecimalFormatter::try_new(locale.into(), Default::default()) {        Ok(formatter) => formatter.format_to_string(&Decimal::from(n)),        Err(_) => n.to_string(),    }}#[cfg(test)]#[path = "shell_lines_tests.rs"]mod tests;