//! The generic verbs over the ENGINE VIEWS the app's screens open//! (`cotton_core::definitions::VIEW_TABLES`): eight built-in tables whose//! records are rows an engine already keeps in a supporting table, answered in//! the keys the app's faces read — which are not that table's column names, so//! [`super::builtin`]'s stored-column read cannot answer them.//!//! - **`face`** — `cotton_media_faces`: a face the Mac thinks it recognises and//! the owner has not answered yet (a suggestion, no person named, not//! dismissed); `get` reads any face. `question` is "Is this <name>?", `crop`//! the picture it was found in (no cut of the face itself is stored),//! `likelihood` the hedge the suggestion's distance earns (`likely` at 0.3 or//! closer, else `maybe`), and `decision` the answer: `yes` once a person is//! named, `no` once the suggestion was dismissed. Answered through//! `update_face`, which has no inverse.//! - **`person_suggestion`** — `cotton_person_suggestions`, open ones first://! "Same as <candidate>?", and a note when the person came from the Photos//! library. `state` is answered through `decide_person_suggestion` — once.//! - **`news_topic`** — `cotton_news_topics` in their own order: `position` is//! the sort key, `pause_reason` the sentence an automatic pause says,//! `last_covered_at` when it last had news, `meta` Followed or Paused.//! Written through the news topic tools.//! - **`news_settings`** — ONE record, id the workspace's: the schedule's two//! times, its zone and its two switches, read with the defaults a database//! that never saved any holds (07:00 and 19:00, both switches on) and//! written through `update_news_settings`.//! - **`news_story`** — `cotton_news_stories`, newest edition first and in//! rank order: `body` the bullets, `why_it_matters`, the sources that link//! somewhere (each with the `label` a chip says), the first address and the//! body a saved note carries. Read only; its commands are their own tools.//! - **`thread_member`** — `cotton_msg_thread_participants` with the contact's//! person. Read only.//! - **`member`** — who is in this database, off the membership facts.//!//! Every view belongs to no project. A `where` on a plain stored key is also//! pushed into the SQL; every clause is then held in memory, with the query,//! and the page is cut from what is left.use cotton_core::definitions::TableDefinition;use cotton_core::records::receipt::no_longer_here;use cotton_core::records::{holds, matches_query, Condition, Data, WhereClause};use rusqlite::types::ValueasSqlValue;use serde_json::{Map, Value};usesuper::ai_usage;usesuper::builtin::{self, cannot_clear, set_by_cotton};usesuper::{sql_err, sql_value, Page, Stored};usecrate::mcp::dispatch::Ctx;usecrate::mcp::handlers::common::Valid;usecrate::mcp::handlers::media_analysis;usecrate::mcp::protocol::ToolFailure;#[path = "settings_catalogue.rs"]mod settings_catalogue;#[path = "storage_view.rs"]mod storage_view;/// The engine views this module answers — its share of `VIEW_TABLES`.pubconst ENGINE_VIEWS: [&str; 11] = ["ai_daily","ai_budget","face","thread_member","member","import","board","theme","storage","settings","camera",];/// The distance at or under which a face's suggestion reads "Very likely".const LIKELY_DISTANCE: f64 = 0.3;pubfn handles(definition: &TableDefinition) -> bool { definition.has_engine() && ENGINE_VIEWS.contains(&definition.rows_table())}// ── reading rows ────────────────────────────────────────────────────────────fn stored( id: String, data: Data, created_at: Option<String>, updated_at: Option<String>,) -> Stored {Stored { id, data, created_at, updated_at, deleted_at: None, byline: None, }}fn put(data: &mutData, key: &str, value: Option<Value>) {ifletSome(value) = value.filter(|value| !value.is_null()) { data.insert(key.to_string(), value); }}fn words(row: &cotton_store::Row, column: &str) -> Option<String> { row.text(column) .map(str::trim) .filter(|text| !text.is_empty()) .map(str::to_string)}fn text_value(row: &cotton_store::Row, column: &str) -> Option<Value> { words(row, column).map(Value::from)}/// One view's SELECT: its base (ending in a `WHERE … = ?` on the workspace),/// the conditions added to it, and its order.structSelect { sql: String, params: Vec<SqlValue>,}implSelect {fn on(ctx: &Ctx<'_>, base: &str) -> Self {Select { sql: base.to_string(), params: vec![SqlValue::Text(ctx.workspace_id.to_string())], } }fn and(mutself, condition: &str, params: implIntoIterator<Item = SqlValue>) -> Self {self.sql.push_str(" AND ");self.sql.push_str(condition);self.params.extend(params);self }fn only(self, expr: &str, id: Option<&str>) -> Self {match id {Some(id) => self.and(&format!("{expr} = ?"), [SqlValue::Text(id.to_string())]),None => self, } }/// Every clause on one of `keys` (`(column key, SQL expression)`) whose/// condition is one text value or several, added to the SQL. The clause is/// still held in memory afterwards, so this only narrows the read.fn pushed(mutself, clauses: &[WhereClause], keys: &[(&str, &str)]) -> Self {for clause in clauses {letSome((_, expr)) = keys.iter().find(|(key, _)| *key == clause.column) else {continue; };match &clause.condition {Condition::Is(value) if value.is_string() => {self = self.and(&format!("{expr} = ?"), [sql_value(value)]); }Condition::OneOf(values)if !values.is_empty() && values.iter().all(Value::is_string) => {let marks = vec!["?"; values.len()].join(", ");self = self.and( &format!("{expr} IN ({marks})"), values.iter().map(sql_value).collect::<Vec<_>>(), ); } _ => {} } }self }fn rows(mutself, ctx: &Ctx<'_>, order: &str) -> Valid<Vec<cotton_store::Row>> {self.sql.push(' ');self.sql.push_str(order); ctx.read .driver() .all(&self.sql, &self.params) .map_err(sql_err) }}/// Every record of `definition` (one, with `id`), narrowed by what the SQL can/// take of `clauses`.fn read( ctx: &Ctx<'_>, definition: &TableDefinition, id: Option<&str>, clauses: &[WhereClause],) -> Valid<Vec<Stored>> {match definition.id.as_str() {"ai_daily" => ai_usage::daily(ctx, id, clauses),"ai_budget" => ai_usage::budget(ctx, id),"face" => faces(ctx, id, clauses),"thread_member" => members(ctx, id, clauses),"member" => database_members(ctx, id),"import" => imports(ctx, id),"board" => boards(ctx, id),"theme" => themes(ctx, id),"storage" => storage_view::read(ctx, id),"settings" => settings_catalogue::read(ctx, id),// Camera keeps no records: each shot is saved in Photos, as its definition declares."camera" => Ok(Vec::new()), other => Err(ToolFailure::new(format!("{other} is not an engine view"))), }}pub(super) fn read_one( ctx: &Ctx<'_>, definition: &TableDefinition, id: &str,) -> Valid<Option<Stored>> {Ok(read(ctx, definition, Some(id), &[])? .into_iter() .find(|record| record.id == id))}pub(super) fn storage_facts(ctx: &Ctx<'_>) -> Valid<Stored> { storage_view::facts(ctx)}pub(super) fn storage_update( ctx: &mutCtx<'_>, definition: &TableDefinition, id: &str, patch: &Data,) -> Valid<()> { storage_view::update(ctx, definition, id, patch)}pub(super) fn list( ctx: &Ctx<'_>, definition: &TableDefinition, project: Option<&str>, query_text: Option<&str>, clauses: &[WhereClause], offset: i64, limit: i64,) -> Valid<Page> {let zone = crate::mcp::handlers::common::where_zone(ctx)?;if project.is_some() {returnErr(ToolFailure::new(format!("{} do not belong to projects", definition.plural ))); }let listed: Vec<Stored> = read(ctx, definition, None, clauses)? .into_iter() .filter(|record| { query_text.is_none_or(|words| matches_query(definition, &record.data, words)) && clauses.iter().all(|clause| holds(&record.data, clause, &zone)) }) .collect();let total = listed.len() as i64;letmut records: Vec<Stored> = listed .into_iter() .skip(usize::try_from(offset).unwrap_or(usize::MAX)) .take(usize::try_from(limit + 1).unwrap_or(usize::MAX)) .collect();let more = records.len() as i64 > limit; records.truncate(usize::try_from(limit).unwrap_or(0));Ok(Page { records, more, total, })}// ── face ────────────────────────────────────────────────────────────────────/// A face on a picture in the bin waits with it: no face here is read off one.const FACE_SQL: &str ="SELECT f.id AS id, f.record_kind AS record_kind, f.record_id AS record_id, \ f.person_id AS person_id, f.suggested_person_id AS suggested_person_id, \ f.suggested_distance AS suggested_distance, f.suggestion_dismissed_at AS dismissed_at, \ f.created_at AS created_at, f.updated_at AS updated_at, ph.key AS photo_key, \ sp.full_name AS suggested_name, pp.full_name AS person_name \ FROM cotton_media_faces f \ LEFT JOIN cotton_photos ph ON f.record_kind = 'photo' AND ph.id = f.record_id \ LEFT JOIN cotton_people sp ON sp.id = f.suggested_person_id \ LEFT JOIN cotton_people pp ON pp.id = f.person_id \ WHERE f.workspace_id = ? AND f.record_id NOT IN (SELECT id FROM cotton_photos WHERE trashed_at IS NOT NULL UNION ALL SELECT id FROM cotton_videos WHERE trashed_at IS NOT NULL)";/// A face still waiting for the owner: suggested, nobody named, not dismissed.const FACE_OPEN: &str = "f.suggested_person_id IS NOT NULL AND f.person_id IS NULL \ AND f.suggestion_dismissed_at IS NULL";/// The hedge a suggestion's distance earns.fn likelihood(distance: Option<f64>) -> &'static str {match distance {Some(distance) if distance <= LIKELY_DISTANCE => "likely", _ => "maybe", }}fn faces(ctx: &Ctx<'_>, id: Option<&str>, clauses: &[WhereClause]) -> Valid<Vec<Stored>> {letmut select = Select::on(ctx, FACE_SQL).only("f.id", id);if id.is_none() { select = select.and(FACE_OPEN, []).pushed( clauses, &[ ("photo_id", "f.record_id"), ("suggested_person_id", "f.suggested_person_id"), ], ); }let rows = select.rows( ctx,"ORDER BY f.suggested_distance IS NULL, f.suggested_distance ASC, f.created_at DESC, \ f.id ASC", )?;Ok(rows .iter() .map(|row| {let suggested = words(row, "suggested_person_id");let person = words(row, "person_id");let name = words(row, "suggested_name").or_else(|| words(row, "person_name"));letmut data = Data::new(); data.insert("question".into(),Value::from(match &name {Some(name) => format!("Is this {name}?"),None => "Is this them?".to_string(), }), ); put(&mut data, "crop", text_value(row, "photo_key"));if suggested.is_some() { data.insert("likelihood".into(),Value::from(likelihood(row.real("suggested_distance"))), ); }let decision = if person.is_some() {Some("yes") } elseif words(row, "dismissed_at").is_some() {Some("no") } else {None }; put(&mut data, "decision", decision.map(Value::from));if row.text("record_kind") == Some("photo") { put(&mut data, "photo_id", text_value(row, "record_id")); } put( &mut data,"suggested_person_id", suggested.or(person).map(Value::from), ); stored( row.text("id").unwrap_or_default().to_string(), data, words(row, "created_at"), words(row, "updated_at"), ) }) .collect())}/// `{decision: "yes"}` names the suggested person in the face, `{decision:/// "no"}` dismisses the suggestion — both `update_face`.pub(super) fn face_update( ctx: &mutCtx<'_>, definition: &TableDefinition, id: &str, patch: &Data,) -> Valid<()> {letmut args = Map::new(); args.insert("id".into(), Value::from(id));for (key, value) in patch {match (key.as_str(), value.as_str()) { ("decision", Some("yes")) => {let face = read_one(ctx, definition, id)? .ok_or_else(|| ToolFailure::new(no_longer_here(definition)))?;let person = face .data .get("suggested_person_id") .cloned() .filter(|_| face.data.get("decision").is_none()) .ok_or_else(|| {ToolFailure::new("this face carries no suggestion to say yes to") })?; args.insert("personId".into(), person); } ("decision", Some(_)) => { args.insert("dismissSuggestion".into(), Value::Bool(true)); } ("decision", None) => returnErr(cannot_clear(definition, key)), (other, _) => returnErr(set_by_cotton(definition, other)), } } builtin::call( ctx, definition,"update_face", media_analysis::update_face,Value::Object(args), ) .map(|_| ())}// ── person_suggestion ───────────────────────────────────────────────────────// ── news_topic ──────────────────────────────────────────────────────────────// ── news_settings ───────────────────────────────────────────────────────────// ── news_story ──────────────────────────────────────────────────────────────// ── thread_member ───────────────────────────────────────────────────────────/// A seat's person is its contact's, derived by who(handle) (PEOPLE BUILD 1), over this copy (`shared`: whether it/// holds the kit's `shared_handle`).fn member_person(shared: bool) -> String { cotton_store::protocol::who::contact_person_sql(shared, "c")}fn member_sql(person: &str) -> String { format!("SELECT tp.id AS id, tp.thread_id AS thread_id, \ tp.display_name AS display_name, tp.role AS role, tp.left_at AS left_at, \ tp.is_self AS is_self, tp.created_at AS created_at, c.display_name AS contact_name, \ {person} AS person_id \ FROM cotton_msg_thread_participants tp \ LEFT JOIN cotton_msg_contacts c ON c.id = tp.contact_id \ WHERE tp.workspace_id = ?" )}/// The id of the owner's row in a group that holds no seat for them.const OWNER_SEAT: &str = ":you";fn members(ctx: &Ctx<'_>, id: Option<&str>, clauses: &[WhereClause]) -> Valid<Vec<Stored>> {// The owner's row in a group with no seat for them, asked by its own id.ifletSome(thread) = id.and_then(|id| id.strip_suffix(OWNER_SEAT)) {returnOk(owner_without_seat(ctx, thread)?.into_iter().collect()); }let person = member_person(cotton_store::protocol::who::shared_held(ctx.db()));let sql = member_sql(&person);let rows = Select::on(ctx, &sql) .only("tp.id", id) .pushed( clauses, &[("thread_id", "tp.thread_id"), ("person_id", person.as_str())], ) .rows(ctx, "ORDER BY tp.created_at ASC, tp.id ASC")?;letmut listed: Vec<(bool, Stored)> = rows .iter() .map(|row| {letmut data = Data::new();let own = row.int("is_self").is_some_and(|own| own != 0);let name = words(row, "display_name") .or_else(|| words(row, "contact_name")) .unwrap_or_else(|| if own { "You" } else { "Someone" }.to_string()); data.insert("name".into(), Value::from(name));for key in ["thread_id", "person_id", "left_at"] { put(&mut data, key, text_value(row, key)); }// Only a role worth saying is said: an admin is "Admin"; being a// member of a chat one is a member of is not a line under a name.if words(row, "role").as_deref() == Some("admin") { data.insert("role".into(), Value::from("Admin")); }let member = stored( row.text("id").unwrap_or_default().to_string(), data, words(row, "created_at"),None, ); (own, member) }) .collect();// One chat's members: the owner is one of them even where the import// wrote no seat for them (walk 5 Oct: 'Weekend plans' listed no You).let asked = clauses.iter().find_map(|clause| match &clause.condition {Condition::Is(Value::String(thread)) if clause.column == "thread_id" => {Some(thread.clone()) } _ => None, });iflet (None, Some(thread)) = (id, asked) {if !listed.iter().any(|(own, _)| *own) {ifletSome(owner) = owner_without_seat(ctx, &thread)? { listed.push((true, owner)); } } }// You first, then everyone in the order they joined. listed.sort_by_key(|(own, _)| !*own);Ok(listed.into_iter().map(|(_, member)| member).collect())}/// The owner's row in `thread` when it is a group holding no seat for them:/// in their own archive they are in every group their seat does not say/// they left. `None` for a direct chat, or where a seat of theirs exists.fn owner_without_seat(ctx: &Ctx<'_>, thread: &str) -> Valid<Option<Stored>> {let group = Select::on( ctx,"SELECT t.created_at AS created_at FROM cotton_msg_threads t WHERE t.workspace_id = ? \ AND t.kind = 'group' AND NOT EXISTS (SELECT 1 FROM cotton_msg_thread_participants tp \ WHERE tp.thread_id = t.id AND tp.is_self = 1)", ) .only("t.id", Some(thread)) .rows(ctx, "")?;Ok(group.first().map(|row| {letmut data = Data::new(); data.insert("name".into(), Value::from("You")); data.insert("thread_id".into(), Value::from(thread)); stored( format!("{thread}{OWNER_SEAT}"), data, words(row, "created_at"),None, ) }))}// ── member ──────────────────────────────────────────────────────────────────/// Who is in this database, by the membership facts as they stand/// (`cotton_store::membership`): each person whose latest admission makes/// them a member now, keyed by their person key, owner first, then by name./// The reader is not listed: a device stated as a member's is that person,/// and a device of the household reading its own database is the owner's./// An assistant (no device) reads everyone. A person still asking to join/// is the serving Mac's pending claim, which the device answers.fn database_members(ctx: &Ctx<'_>, id: Option<&str>) -> Valid<Vec<Stored>> {use cotton_store::membership::{self, Rights};let driver = ctx.read.driver();let owner = membership::owner(driver).map_err(sql_err)?;let reader = match ctx.caller_device {Some(device) => membership::device(driver, device) .map_err(sql_err)? .map(|(person, _)| person) .or_else(|| owner.clone()),None => None, };let rows = driver .all("SELECT person_key, person_name, rights, admitted_at, _hlc FROM cotton_admissions a \ WHERE id = (SELECT id FROM cotton_admissions b WHERE b.person_key = a.person_key ORDER BY _hlc DESC, id DESC LIMIT 1) \ ORDER BY person_name, person_key", &[], ) .map_err(sql_err)?;letmut listed = Vec::new();for row in &rows {let key = row.text("person_key").unwrap_or_default().to_string();if id.is_some_and(|id| id != key) || reader.as_deref() == Some(key.as_str()) {continue; }letSome(rights) = membership::of(driver, &key).map_err(sql_err)? else {continue; };let word = match rights {Rights::Owner => "owner",Rights::Admin => "admin",Rights::Member => "member", };letmut data = Data::new(); put(&mut data, "name", text_value(row, "person_name")); data.insert("role".into(), Value::from(word)); data.insert("state".into(),Value::from(word), ); data.insert("status".into(),Value::from("in"), ); data.insert("database".into(), Value::from(ctx.workspace_id));if rights == Rights::Owner {ifletSome(ownership) = membership::resolved_ownership(driver).map_err(sql_err)? { data.insert("owner_since".into(), Value::from(ownership.admitted_at)); } } data.insert("fingerprint".into(), Value::from(member_fingerprint(&key)));// What their page says: the devices they use and since when — a// person's screen never draws a key (architect, 16 Oct 2026).let devices = membership::device_names(driver, &key).map_err(sql_err)?;if !devices.is_empty() { data.insert("devices".into(), Value::from(devices.join(", "))); } put(&mut data, "joined", text_value(row, "admitted_at")); listed.push(( rights != Rights::Owner, stored(key, data, words(row, "admitted_at"), None), )); } listed.sort_by_key(|(not_owner, _)| *not_owner);Ok(listed.into_iter().map(|(_, member)| member).collect())}/// A person key as Members reads it: its first eight characters in two/// groups of four (`Fingerprint.of` in the app), else the key itself.fn member_fingerprint(key: &str) -> String {let head: Vec<char> = key.trim().chars().take(8).collect();if head.len() < 8 {return key.trim().to_string(); } format!("{} {}", head[..4].iter().collect::<String>(), head[4..].iter().collect::<String>() )}// ── imports ────────────────────────────────────────────────────────────────/// The author stamp identifies the device that ran the import. `device_id`/// on the run is a file author id, not a key in `cotton_devices`.fn imports(ctx: &Ctx<'_>, id: Option<&str>) -> Valid<Vec<Stored>> {let rows = Select::on(ctx,"SELECT i.id, i.source, i.title, i.added, i.skipped, i.finished_at, i.created_at, \ COALESCE(a.device_name, \ (SELECT d.name FROM cotton_devices d \ WHERE d.device_id = a.device_id AND d.workspace_id = i.workspace_id LIMIT 1)) AS device_name \ FROM cotton_imports i \ LEFT JOIN cotton_authors a ON a.id = substr(i._hlc, 20) AND a.workspace_id = i.workspace_id \ WHERE i.workspace_id = ?") .only("i.id", id) .rows(ctx, "ORDER BY i.finished_at DESC, i.id DESC")?;Ok(rows .iter() .map(|row| {let added = row.int("added").unwrap_or(0);let skipped = row.int("skipped").unwrap_or(0);let source = match row.text("source").unwrap_or_default() {"contacts" => "Contacts","chat_export" => "Chat export","recording" => "Recording","passwords" => "Passwords","messages" => "Messages","call_history" => "Call history","whatsapp_backup" => "WhatsApp backup","photos" => "Photos","instagram_export" => "Instagram export", source => source, };let result = if added > 0 { format!("{added} added") } elseif skipped > 0 {"all already here".to_string() } else {"nothing new".to_string() };letmut data = Data::new(); data.insert("source".into(), Value::from(source)); data.insert("added".into(), Value::from(added)); data.insert("skipped".into(), Value::from(skipped)); data.insert("result".into(), Value::from(result)); put(&mut data, "title", text_value(row, "title")); put(&mut data, "device", text_value(row, "device_name")); put(&mut data, "finished_at", text_value(row, "finished_at")); stored( row.text("id").unwrap_or_default().to_string(), data, words(row, "created_at"),None, ) }) .collect())}#[cfg(test)]mod tests {usesuper::*; #[test]fn a_suggestions_distance_is_a_hedge() { assert_eq!(likelihood(Some(0.1)), "likely"); assert_eq!(likelihood(Some(0.3)), "likely"); assert_eq!(likelihood(Some(0.31)), "maybe"); assert_eq!(likelihood(None), "maybe"); }}// ── board ───────────────────────────────────────────────────────────────────/// What each screen that draws a board is called on its record.fn screen_name(id: &str) -> &'static str {match id {"home" => "Home","tools" => "Tools","database" => "Database page", _ => "A screen", }}/// One record per screen that draws a board: the board this database draws/// there (its own row, else the shipped default), as the JSON a writer sends/// back whole.fn boards(ctx: &Ctx<'_>, id: Option<&str>) -> Valid<Vec<Stored>> {letmut records = Vec::new();for board incrate::presentation::board_ids() {if id.is_some_and(|id| id != board) {continue; }letSome(resolved) = crate::presentation::board(ctx.read.driver(), ctx.workspace_id, board) .map_err(ToolFailure::new)?else {continue; };let definition = serde_json::to_string_pretty(&resolved.definition) .map_err(|error| ToolFailure::new(error.to_string()))?;letmut data = Data::new(); data.insert("name".into(), Value::from(screen_name(board))); data.insert("definition".into(), Value::from(definition));let drawn = match resolved.drawn {crate::presentation::Drawn::Row => "yours",crate::presentation::Drawn::Default => "default", }; data.insert("drawn".into(), Value::from(drawn)); records.push(stored(board.to_string(), data, None, None)); }Ok(records)}/// A screen's board is written whole: its `definition`, held by/// `presentation::save_board` to exactly what this build draws. Every other/// column is Cotton's to say.pub(super) fn board_update( ctx: &mutCtx<'_>, definition: &TableDefinition, id: &str, patch: &Data,) -> Valid<()> {if !crate::presentation::board_ids().any(|board| board == id) {returnErr(unknown_board(id)); }letmut written = None;for (key, value) in patch {match key.as_str() {"definition"if value.is_null() => returnErr(cannot_clear(definition, key)),"definition" => written = Some(board_json(value)?), other => returnErr(set_by_cotton(definition, other)), } }letSome(board) = written else { returnOk(()) };if board.get("id").and_then(Value::as_str) != Some(id) {returnErr(ToolFailure::new(format!("That board cannot be saved: the {id} board's definition must say \"id\": {id:?}" ))); }crate::presentation::save_board(ctx, &board)?;// Committed as an engine tool's write is (`builtin::call`), so the// record read back after it is the board just saved. ctx.commit()?;Ok(())}/// A delete puts the shipped board back (`presentation::reset_board`): the/// person's row becomes the default again, so `drawn` reads `default`. A/// screen already drawing the default has nothing to put back, and that is/// the one board a delete refuses.pub(super) fn board_reset(ctx: &mutCtx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> {let current = read_one(ctx, definition, id)?.ok_or_else(|| unknown_board(id))?;if current.data.get("drawn").and_then(Value::as_str) != Some("yours") {returnErr(ToolFailure::new(format!("The {id} board is already the one this build ships; there is nothing to put back" ))); }crate::presentation::reset_board(ctx, id)?; ctx.commit()?;Ok(())}fn unknown_board(id: &str) -> ToolFailure {ToolFailure::new(format!("There is no board {id:?}: the screens that draw one are {}.",crate::presentation::board_ids() .collect::<Vec<_>>() .join(", ") ))}/// The definition as sent: the board's JSON in text (the column's type), or/// the object itself from a caller that sent one.fn board_json(value: &Value) -> Valid<Value> {match value {Value::String(text) => serde_json::from_str(text).map_err(|error| {ToolFailure::new(format!("That board cannot be saved: it is not JSON ({error})" )) }),Value::Object(_) => Ok(value.clone()), _ => Err(ToolFailure::new("That board cannot be saved: send the board's JSON as its definition", )), }}// ── theme ───────────────────────────────────────────────────────────────────/// What each theme id is called on its record.fn theme_name(id: &str) -> &'static str {match id {"paper" => "Paper","plain" => "Plain","database" => "This database's own", _ => "A theme", }}/// One record per theme the database can hold (`presentation::themes`): its/// own row for it, else the default, and whether it is the one worn.fn themes(ctx: &Ctx<'_>, id: Option<&str>) -> Valid<Vec<Stored>> {letmut records = Vec::new();for theme incrate::presentation::themes(ctx.read.driver(), ctx.workspace_id) .map_err(ToolFailure::new)? {if id.is_some_and(|id| id != theme.id) {continue; }let definition = theme.definition.to_string();letmut data = Data::new(); data.insert("name".into(), Value::from(theme_name(theme.id))); data.insert("definition".into(), Value::from(definition));let drawn = match theme.drawn {crate::presentation::Drawn::Row => "yours",crate::presentation::Drawn::Default => "default", }; data.insert("drawn".into(), Value::from(drawn)); data.insert("worn".into(), Value::Bool(theme.worn)); records.push(stored(theme.id.to_string(), data, None, None)); }Ok(records)}fn unknown_theme(id: &str) -> ToolFailure {ToolFailure::new(format!("There is no theme {id:?}: the themes are {}.",crate::presentation::theme_ids() .collect::<Vec<_>>() .join(", ") ))}/// A theme is written whole: its `definition`, held by/// `presentation::save_theme` to exactly what this build draws. Saved, it is/// the newest theme the database wrote, so the one it wears.pub(super) fn theme_update( ctx: &mutCtx<'_>, definition: &TableDefinition, id: &str, patch: &Data,) -> Valid<()> {if !crate::presentation::theme_ids().any(|theme| theme == id) {returnErr(unknown_theme(id)); }letmut written = None;for (key, value) in patch {match key.as_str() {"definition"if value.is_null() => returnErr(cannot_clear(definition, key)),"definition" => { written =Some(match value {Value::String(text) => { serde_json::from_str::<Value>(text).map_err(|error| {ToolFailure::new(format!("That theme cannot be saved: it is not JSON ({error})" )) })? }Value::Object(_) => value.clone(), _ => returnErr(ToolFailure::new("That theme cannot be saved: send the theme's JSON as its definition", )), }) } other => returnErr(set_by_cotton(definition, other)), } }letSome(theme) = written else { returnOk(()) };if theme.get("id").and_then(Value::as_str) != Some(id) {returnErr(ToolFailure::new(format!("That theme cannot be saved: the {id} theme's definition must say \"id\": {id:?}" ))); }crate::presentation::save_theme(ctx, &theme)?; ctx.commit()?;Ok(())}/// A delete puts a theme back on its default (`presentation::reset_theme`);/// a theme already at its default is never deleted.pub(super) fn theme_reset(ctx: &mutCtx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> {let current = read_one(ctx, definition, id)?.ok_or_else(|| unknown_theme(id))?;if current.data.get("drawn").and_then(Value::as_str) != Some("yours") {returnErr(ToolFailure::new(format!("The {id} theme is already its default; there is nothing to put back" ))); }crate::presentation::reset_theme(ctx, id)?; ctx.commit()?;Ok(())}