//! `shell.deck {table, view?, where?, cursor?, limit?, ink?, visitor?,//! holding?, timezone?, today?}` — A PAGE OF THE DECK, ANSWERED WHOLE (move 2//! of the shell boundary, 5 Nov 2026: the core answers what to show, a//! platform shell only draws), and `shell.plus {table, view?}` — what the//! deck's "+" does (move 4); a card not yet made is `shell.draft`'s//! (`methods::shell_input`).//!//! ```json//! { "table", "view", "landed"?,//! "cards": [{ "id", "face", "corner"?, "pressing", "pace"?, "plate"?, "slots",//! "thread"?, "pages", "stars"?, "stored", "reach", "file"?,//! "delivery"?, "prints"?, "position", "tap": { slot: act }, "from"?,//! "acts": [id], "parts"?, "related"?, "record" }],//! "acts": { id: { "label", "kind", "red", "primary"?, "icon"? } },//! "labels": { "by_slot", "by_column" }, "viewer"?: { <viewer.words> },//! "count", "head"?, "empty"?, "hand": [face], "worn"?,//! "plus": <shell.plus's answer>, "visitor"?, "next" }//! ```//!//! - `cards`: the view's records in its order, `limit` (≈50) from `cursor`,//! each the card the core resolved (`@card`) worn in the face the person//! chose for its table (`face_settings`), its places (`slots`) holding//! what the deck read beyond them — a sleeve's `songs`,//! a radio's `episode` (the one the player `holding` holds when it is the//! show's), an album's prints — and its readings: the pages it turns to,//! a rating's stars, the value stored under each place, how a person is//! reached, its own file, a delivery's states. Its `position` is said//! ("3 / 14"); its `tap` says what a tap on the card (`card`) and on its//! check (`check`) does; its `acts` are the ids of the acts it offers, in//! the held card's order — `shell.opened`'s own rule (`card_actions::opened`)//! — and `acts` names each once per page, as the held card says it. A card//! whose tap opens a whole (`open.whole`: a series into its seasons, a season//! into its episodes) says the deck its parts are (`parts`: `{table, where}`,//! the deck the shell asks next), so no shell reads `card.opens`, and its//! related lists counted (`related`: `[{id, said, count}]`, each table's//! count said in its `opened.related.<table>` line: a series' seasons and//! episodes, which its one-sheet fans and its marquee says). `record` is//! the row itself, which the shell's routes (an opening, the editor in//! place) still take until they are answered too.//! - `ink`: the letters written over the deck narrow it to the records some//! word of whose columns starts with them (`rules::ink_match`), counted//! and paged over what they keep; `empty` then says nothing starts so.//! - `visitor`: a record the deck is asked to stand on, answered as its own//! card with whether the view holds it (`held`).//! - A list's deck (`<tool>/group:<id>`) whose tool stands its lists in a//! face of their own (`ToolDefinition::lists`, Music's cassette) leads//! with the LIST'S OWN CARD (`rules::list_card`): first in the deck and//! counted in it, its `list` the list it stands for, its `record` the//! list's row, its tap `open.play` (the list plays from its first), no//! acts of a member's. The cursor still counts the members; ink narrows//! the members alone, with no list card.//! - `lands` (with `chosen`): a record's or a blank's deck names no view of//! its own; the core names it (`landing`), reads that view, and says it//! under `view` and whole under `landed`, as the fan says a view.//! - `playing` (Listening, its first page): the song the music player holds//! dealt in front on the player's face, the album it plays from moved there//! (`shell_deck_player`).//! - `next`: the cursor of the page after, or null at the end. The shell//! asks for it as the deck nears its end — never per frame — and asks//! again from 0 on a data event, a definitions change, a face choice, ink.//! - `count` is every card the deck holds; `head` the view's own head line//! ("12 of 24 this year"), while no ink narrows it; `empty` the empty//! deck's words `{title, message}`; `hand` the faces the deck's hand//! cycles (two or more) and `worn` the one worn.usecrate::methods::MethodError;usecrate::shell::client::ClientController;use cotton_core::definitions::card::CardSlot;use cotton_core::definitions::tool_views::ToolView;use cotton_core::definitions::{TableDefinition, ToolDefinition};use cotton_core::rules::card_actions::{self, CardAction};use cotton_core::flavor::FanCards;use cotton_core::rules::ink_match;use cotton_core::rules::shell_lines::{self, LineRow};use serde_json::{json, Map, Value};const METHOD: &str = "shell.deck";/// A page of the deck.pubconst PAGE: usize = 50;/// The most an album's card reads of its prints.const MOST_PRINTS: usize = 60;/// The most songs one list's cassette or one sleeve reads.const MOST_SONGS: usize = 200;/// The opening a tap on a card makes, each the deck's own act.const OPENS: [&str; 8] = ["writer", "reader", "whole", "group", "conversation", "viewer", "reading", "opened"];/// The command whose presence on a table opens its card in the writer/// (Cotton Story's scene, 17 Nov 2026): `story.write` on the record itself.const WRITE: &str = "story.write";typeNative<'a> = &'a dynFn(&Value) -> Result<Value, MethodError>;pubfn call(handle: &crate::handle::CottonHandle, request: &Value) -> Result<Value, MethodError> {let client = handle.client();let native = |args: &Value| crate::methods::dispatch(handle, "records.list", &crate::phone::records::in_named_database(args.clone()));// A landing is the deck of the view it lands on, said beside its page.let (asked, landed) = landing(&client, request, &native)?;let request = asked.as_ref().unwrap_or(request);let said = |mut answer: Value| -> Result<Value, MethodError> {ifletSome(view) = &landed { answer["landed"] = view.clone(); }// Listening with a song playing: the player in front (`shell_deck_player`).crate::methods::shell_deck_player::deal(&mut answer, request)?;Ok(answer) };// Asked again while nothing it reads has moved, the kept answer.let at = client.moved();ifletSome(answer) = crate::methods::shell_kept::answer(&client, METHOD, request) { return said((*answer).clone()); }let (answer, aside) = read_answer(&client, handle.fan(), request, &native)?;ifletSome(aside) = aside { crate::methods::shell_kept::keep(&client, METHOD, request, at, aside, &answer); } said(answer)}/// `lands: true` (with `chosen`, `{tool: view}`, as `shell.fan` takes it): the/// deck of a record opened from anywhere, or of a blank one, stands on a view/// the core names (Calendar after Plus, #294: the shell's guess left it on no/// view, a deck of every event). Of the views of the tool that lists the/// table that read the table itself, the one chosen, else the default, else/// the first; a list's view is no landing. None such, the deck stays/// view-less. Answers the request as the deck reads it and the view as the fan says it.fn landing(client: &ClientController, request: &Value, native: Native) -> Result<(Option<Value>, Option<Value>), MethodError> {if request["lands"] != true { returnOk((None, None)); }letmut asked = request.clone();ifletSome(fields) = asked.as_object_mut() { fields.remove("lands"); fields.remove("chosen"); }if named(request, "view").is_some() { returnOk((Some(asked), None)); }let table = named(request, "table").ok_or_else(|| bad("shell.deck takes a table"))?;let tables = definitions(client)?;let definition = tables.iter().find(|found| found.id == table).ok_or_else(|| bad(&format!("No table {table}")))?;let tools = crate::phone::tool_acts::read_tools(client, METHOD)?;let owned = definition.tool.as_ref().map(|block| (block.key.clone().unwrap_or_else(|| definition.id.clone()), &block.views));let listing = || tools.iter().find(|tool| tool.tables.first().is_some_and(|first| first == table)) .or_else(|| tools.iter().find(|tool| tool.tables.iter().any(|held| held == table))) .map(|tool| (tool.id.clone(), &tool.views));letSome((tool, views)) = owned.or_else(listing) else { returnOk((Some(asked), None)) };let reading: Vec<_> = views.iter().filter(|view| view.partition.is_none() && view.read.get("table").and_then(Value::as_str) == Some(table)).collect();letmut chosen = crate::methods::shell_fan::kept_chosen(client);ifletSome(Value::Object(given)) = request.get("chosen") { chosen.extend(given.clone()); }let standing = chosen.get(&tool).and_then(Value::as_str);letSome(view) = reading.iter().find(|view| Some(view.id.as_str()) == standing) .or_else(|| reading.iter().find(|view| view.is_default)) .or_else(|| reading.first()) else { returnOk((Some(asked), None)) };let name = format!("{tool}/{}", view.id);let zone = request["timezone"].as_str().unwrap_or(client.time_zone().unwrap_or("UTC")).to_string();let said = crate::methods::shell_fan::named_default(read_view(client, request, &name, &zone, native)?); asked["view"] = json!(name);Ok((Some(asked), Some(said)))}/// The viewer's own lines (`viewer.words`) where the table's cards open into the viewer (Photos' prints): the/// words a shell's full-screen viewer says, its Close, its position "{n} of {count}", what an absent picture/// says. Null for a table that carries none./// The deck's answer with them as `viewer`, where the table carries them (left out otherwise).fn with_viewer(mut answer: Value, definition: &TableDefinition) -> Value {ifletSome(words) = definition.viewer.as_ref().and_then(|viewer| viewer.words.as_ref()) { answer["viewer"] = json!(words); } answer}pubfn plus(handle: &crate::handle::CottonHandle, request: &Value) -> Result<Value, MethodError> {let table = named(request, "table").ok_or_else(|| bad("shell.plus takes a table"))?;let tables = definitions(&handle.client())?;let definition = tables.iter().find(|found| found.id == table).ok_or_else(|| bad(&format!("No table {table}")))?;letmut answer = plus_of(definition);let tile = crate::phone::fan_tile::of_table(&handle.client(), definition, "shell.plus")?;crate::phone::fan_tile::dress_doors(tile.as_ref(), &mut answer);Ok(answer)}/// What a table's "+" does, wherever it stands — the deck's Plus, the list/// page's Add, the empty deck's held acts: its doors' choice tier where its/// create names doors; its act at the object where it names one; its route/// where it names one; else a new record written by hand (the coordinator,/// 4 Nov 2026: a create naming doors or an act never makes a blank record).pubfn plus_of(definition: &TableDefinition) -> Value {let create = definition.create.as_ref();let doors: Vec<Value> = create.into_iter().flat_map(|create| create.doors.iter()).map(|door| {let accepts = match (&door.act, &door.files) {// A new record written in the shell's inputs: `shell.input {op: ask, kind: door}` begins it and asks each part. (None, None) if door.draft.is_some() => json!({"draft": {"door": door.id}}),// What this device keeps read in (Read Apple Health): the shell asks the system at this tap. (None, None) if door.reads.is_some() => json!({"reads": door.reads}), (None, None) if door.pick.is_some() => {let pick = door.pick.as_ref().expect("a picture door"); json!({"pick": {"source": pick.source, "kinds": pick.kinds, "many": pick.many}}) } (Some(act), _) => json!({"words": {"act": act.name, "argument": act.argument, "lands": act.lands, "signed_out": act.signed_out}}), (None, Some(files)) => {// Each type's media types beside it, in the door's order, once// each: what a picker that takes media types is handed.letmut mimes: Vec<&str> = Vec::new();for mime in files.types.iter().filter_map(|kind| cotton_core::definitions::file_type_mimes(kind)).flatten() {if !mimes.contains(mime) { mimes.push(mime); } } json!({"files": {"types": files.types, "mimes": mimes, "many": files.many}}) } (None, None) => Value::Null, }; json!({"id": door.id, "label": door.label, "picture": door.object.as_ref().map(|object| format!("act-{object}")), "accepts": accepts}) }).collect();let label = create.map(|create| create.label.clone());if !doors.is_empty() {return json!({"does": "doors", "label": label, "doors": doors}); }ifletSome(act) = create.and_then(|create| create.act.as_ref()) {return json!({"does": "act", "label": label, "doors": [],"act": {"act": act.name, "argument": act.argument, "lands": act.lands, "signed_out": act.signed_out}}); }ifletSome(method) = create.and_then(|create| create.method.as_ref()) {// Called at once, nothing asked; its answer's platform action is followed (Story's New scene opens the writer).return json!({"does": "call", "label": label, "doors": [], "method": method}); }ifletSome(path) = create.and_then(|create| create.path.as_ref()) {// A shell that draws no hand-built screen (Android) makes the card blank instead, where the card has a title// to ask (`or: blank`): Calendar's New event is its title in the line, then its When, Time and Repeat steps.let or = crate::methods::shell_input::title_column(definition).map(|_| "blank");return json!({"does": "route", "label": label, "doors": [], "route": path, "or": or}); } json!({"does": if create.is_some() { "blank" } else { "none" }, "label": label, "doors": []})}/// What the deck reads beside its rows, once per page.structHeld { tables: Vec<TableDefinition>, lines: Vec<LineRow>,/// Each table's chosen face (`face_settings`), by table; None where the/// database keeps no face choices. chosen: Option<Map<String, Value>>,/// The tool acts standing on the deck's table under its view/// (`tool_acts::standing`), read once a page. tools: Vec<CardAction>,/// Whether the deck's view names a card of its own (Owed's receipt over/// a table naming none): then every row comes with its card, and one/// without is refused, never drawn plain. view_card: bool,}/// The deck's page, and what it leaves aside where it may be kept/// (`shell_kept`): None for a table that moves with no event (polled, or/// dressed by a live read).fn read_answer(client: &ClientController, fan: &FanCards, request: &Value, native: Native) -> Result<(Value, Option<std::collections::HashSet<String>>), MethodError> {let table = named(request, "table").ok_or_else(|| bad("shell.deck takes a table"))?.to_string();let cursor = match request.get("cursor") {None | Some(Value::Null) => 0,Some(value) => value.as_u64().ok_or_else(|| bad("cursor is the next answer's own cursor"))? as usize, };let limit = match request.get("limit") {None | Some(Value::Null) => PAGE,Some(value) => value.as_u64().filter(|limit| *limit > 0).ok_or_else(|| bad("limit is a count of cards"))? as usize, } .min(cotton_tools::mcp::handlers::tables::MAX_PAGE_SIZE as usize);let ink = named(request, "ink").unwrap_or_default().to_string();let filter = match request.get("where") {None | Some(Value::Null) => Map::new(),Some(Value::Object(filter)) => filter.clone(),Some(_) => returnErr(bad("where is {column: value}")), };let zone = request["timezone"].as_str().unwrap_or(client.time_zone().unwrap_or("UTC")).to_string();letmut held = read_held(client, native)?;let definition = held.tables.iter().find(|found| found.id == table).ok_or_else(|| bad(&format!("No table {table}")))?.clone(); held.tools = crate::phone::tool_acts::standing(client, &definition, request["view"].as_str(), METHOD)?.iter().filter_map(CardAction::tool).collect();// The view: its read, head and empty words, as the fan counts it.let view_name = named(request, "view").map(str::to_string);let view = match &view_name {Some(name) => Some(read_view(client, request, name, &zone, native)?),None => None, }; held.view_card = view.as_ref().is_some_and(|view| view["card"].is_object());letmut args = Map::new(); args.insert("table".into(), json!(table)); args.insert("timezone".into(), json!(zone));ifletSome(today) = request.get("today").filter(|today| !today.is_null()) { args.insert("today".into(), today.clone()); }letmut narrowing = filter.clone();match &view {Some(view) => {let read = view["read"].as_object().cloned().unwrap_or_default();ifletSome(section) = read.get("section").filter(|section| !section.is_null()) { args.insert("section".into(), section.clone()); }if view["id"].as_str().is_some_and(|id| id.starts_with("group:")) {// A list's deck: its members.ifletSome(Value::Object(own)) = read.get("where") {for (key, value) in own { narrowing.entry(key.clone()).or_insert_with(|| value.clone()); } } } else { args.insert("view".into(), json!(view_name));// A column this device answers (Downloaded's `on_phone`) is// never stored: the view leaves it to the caller's read// (`ToolView::narrow`), which narrows it to the rows this// device keeps (`records.list`'s `narrow_where`), as the// fan's count does. Unsaid, the deck dealt every row// (the Android Podcasts walk, 12 Nov 2026).ifletSome(Value::Object(own)) = read.get("where") {for (key, value) in own.iter().filter(|(key, _)| cotton_core::definitions::is_device_answered_column(&table, key)) { narrowing.entry(key.clone()).or_insert_with(|| value.clone()); } } } }// A deck of no view over a planned table, unnarrowed, reads its plan:// a day-split table today and after, a table of work still to do today.Noneif filter.is_empty() && definition.upcoming.is_some() && definition.day_grouping.is_none() => { args.insert("section".into(), json!("today")); }Noneif filter.is_empty() && definition.day_grouping.is_some() => { args.insert("section".into(), json!("coming")); }None => {} }if !narrowing.is_empty() { args.insert("where".into(), Value::Object(narrowing)); }// A deck says no group's heads: never summed over every row (Owed's// page was 2.98M steps of heads to 6.7k of its own rows). args.insert("heads".into(), json!(false));// Letters written in an app of one tool search its whole kit.if !ink.is_empty() && !fan.home && !fan.tools {let asked = Asked { request, definition: &definition, view: view.as_ref(), view_name: view_name.as_deref(), args: &args, ink: &ink, cursor, limit, zone: &zone };return universal(client, fan, &asked, &mut held, native); }// The rows: one page, or every row the ink keeps and then its page.// A plain deck pages off its table's kept order (`shell_order`): a// write re-reads only the rows it named, and a page reads its own rows.let ordered = ink.is_empty() && view.is_none() && !args.contains_key("section") && definition.polled != Some(true) && definition.live_read.is_none()// A table another engine reads (Email's) refuses `among`: its deck is read as a page. && cotton_tools::mcp::handlers::tables::builtin::reads_among(&definition) && crate::methods::shell_order::row_local(&definition, args.get("where").and_then(Value::as_object).into_iter().flat_map(|filter| filter.keys()));let paged = match ordered {true => {let own = crate::methods::shell_kept::stores(&definition);let aside = std::sync::Arc::new(crate::methods::shell_kept::aside(&held.tables, &definition));let ids = crate::methods::shell_order::ids(client, &own, &aside, &args, native)?;let page: Vec<&str> = ids.iter().skip(cursor).take(limit).filter_map(Value::as_str).collect();let rows = match page.is_empty() {true => Vec::new(),false => crate::methods::shell_order::read_among(native, &args, &page)?["records"].as_array().cloned().unwrap_or_default(), };// A page the store answers otherwise than the order said is read as a page.let read: Vec<&str> = rows.iter().filter_map(|row| row["id"].as_str()).collect(); (read == page).then(|| {let next = (cursor + rows.len() < ids.len()).then_some(cursor + rows.len()); (rows, ids.len(), next) }) }false => None, };let (mut rows, count, next) = ifletSome(paged) = paged { paged } elseif ink.is_empty() {letmut asked = Value::Object(args.clone()); asked["page"] = json!(cursor); asked["limit"] = json!(limit);// A deck of work still to do reads today off the kept plan (`shell_plan`).let planned = match view.is_none() && filter.is_empty() && definition.upcoming.is_some() && definition.day_grouping.is_none() && definition.polled != Some(true) && definition.live_read.is_none() {true => {let own = crate::methods::shell_kept::stores(&definition);let aside = std::sync::Arc::new(crate::methods::shell_kept::aside(&held.tables, &definition));let bus = client.bus();let at = crate::methods::shell_plan::At { bus: &bus, moved: client.moved(), own: &own, aside: &aside };let today = match request.get("today").and_then(Value::as_str) {Some(today) => today.to_string(),None => cotton_core::records::page::Moment::now(client.clock().now(), &zone) .map(|moment| { let (year, month, day) = cotton_core::transforms::zoned_clock::civil_from_days(moment.day); format!("{year:04}-{month:02}-{day:02}") }) .unwrap_or_default(), }; asked.as_object().map(|ask| crate::methods::shell_plan::page(at, ask, &today, native)).transpose()?.flatten() }false => None, };letmut answer = match planned { Some(answer) => answer, None => native(&asked)? };// A day-split deck with nothing coming opens on its past.if cursor == 0 && asked["section"] == "coming" && answer["records"].as_array().is_some_and(Vec::is_empty) { asked["section"] = json!("earlier"); answer = native(&asked)?; }let rows = answer["records"].as_array().cloned().unwrap_or_default();let count = answer["total"].as_u64().map(|total| total as usize).unwrap_or(cursor + rows.len());let next = answer["next_page"].as_u64().map(|next| next as usize); (rows, count, next) } else {let stops = ink_match::stop_words();let columns = ink_match::columns(&definition);let kept: Vec<Value> = every_row(&args, native)? .into_iter() .filter(|row| columns.iter().any(|column| ink_match::holds(ink_text(row, column, &definition).as_deref(), &ink, &stops))) .collect();let count = kept.len();let page: Vec<Value> = kept.into_iter().skip(cursor).take(limit).collect();let next = (cursor + page.len() < count).then_some(cursor + page.len()); (page, count, next) };// A list's deck whose tool stands its lists in a face of their own// (`ToolDefinition::lists`: Music's cassette) leads with the list's card,// counted as the deck's first; ink narrows the members alone.let list = match (&view, view_name.as_deref()) { (Some(view), Some(name)) if ink.is_empty() && view["id"].as_str().is_some_and(|id| id.starts_with("group:")) => listed(client, name)?, _ => None, };let lead = usize::from(list.is_some());let count = count + lead;letmut acts: Map<String, Value> = Map::new();letmut cards = Vec::with_capacity(rows.len() + lead);for (at, row) in rows.iter_mut().enumerate() {letmut card = card_of(&held, &definition, row, request, native, &mut acts)?; card["position"] = position(&held.lines, lead + cursor + at + 1, count); cards.push(card); }let visitor = match named(request, "visitor") {Some(id) if !cards.iter().any(|card| card["id"] == id) => visiting(&held, &definition, &args, id, request, native, &mut acts)?, _ => Value::Null, };// The face the deck's cards wear, and the hand that cycles it.let family_face = cards.first().map(|card| card["drawn"].as_str().unwrap_or_default().to_string()) .or_else(|| definition.card.as_ref().map(|card| card.face.as_str().to_string()));let hand = match (&held.chosen, &family_face) { (Some(_), Some(face)) => {let offers = offers(&definition);if offers.len() > 1 && family(&definition).contains(face) { offers } else { Vec::new() } } _ => Vec::new(), };let worn = (!hand.is_empty()).then(|| selected(&definition, held.chosen.as_ref())).flatten();let cycles = worn.as_deref().map(|worn| hand_next(&table, &hand, worn, &held.lines));// A group card says where it opens; the tools are read only for a page dealing one.letmut visitor = visitor;if cards.iter().chain(std::iter::once(&visitor)).any(opens_group) {let tools = crate::phone::tool_acts::read_tools(client, METHOD)?;for card in cards.iter_mut().chain(std::iter::once(&mut visitor)).filter(|card| opens_group(card)) {let data = card["record"]["data"].as_object().cloned().unwrap_or_default();ifletSome(route) = group_route(&held.tables, &tools, &definition, view.as_ref(), &data, card["slots"]["title"].as_str()) { card["group"] = route; } } }for card in &mut cards { card.as_object_mut().map(|card| card.remove("drawn")); }iflet (Some((face, group)), 0) = (&list, cursor) {letmut card = list_card(client, &held, face, group, native, &mut acts)?; card["position"] = position(&held.lines, 1, count); cards.insert(0, card); }let empty = if count == 0 && visitor.is_null() {Some(empty_words(client, request, &definition, view.as_ref(), view_name.as_deref(), &ink, &held.lines, &zone, native)?) } else {None };let head = if ink.is_empty() { view.as_ref().and_then(|view| view["head"].as_str().map(str::to_string)) } else { None };ifletSome(visitor) = visitor.as_object_mut() { visitor.remove("drawn"); }letmut plus = plus_of(&definition);crate::phone::fan_tile::dress_doors(crate::phone::fan_tile::of_table(client, &definition, METHOD)?.as_ref(), &mut plus);let keeps = definition.polled != Some(true) && definition.live_read.is_none();let aside = keeps.then(|| crate::methods::shell_kept::aside(&held.tables, &definition));Ok((with_viewer(json!({"table": table, "view": view_name,"cards": cards, "acts": acts, "labels": labels(&definition, &held.lines),"count": count, "head": head, "empty": empty,"hand": hand, "worn": worn, "hand_next": cycles,"plus": plus,"visitor": visitor, "next": next, }), &definition), aside))}/// Whether a dealt card's tap opens a group's view.fn opens_group(card: &Value) -> bool { card["tap"]["card"] == "open.group"}/// The cards of `rows` of `table`, each worn as the deck wears it — the one/// card builder, for a page that deals records of several tables/// (`shell.today`). A table the database does not hold has none.pub(crate) fn cards_of( client: &ClientController, table: &str, rows: Vec<Value>, request: &Value, native: Native, acts: &mutMap<String, Value>,) -> Result<Vec<Value>, MethodError> {letmut held = read_held(client, native)?;letSome(definition) = held.tables.iter().find(|found| found.id == table).cloned() else { returnOk(Vec::new()) }; held.tools = crate::phone::tool_acts::standing(client, &definition, None, METHOD)?.iter().filter_map(CardAction::tool).collect();letmut cards = Vec::with_capacity(rows.len());formut row in rows {letmut card = card_of(&held, &definition, &mut row, request, native, acts)?;ifletSome(card) = card.as_object_mut() { card.remove("drawn"); } card["table"] = json!(table); cards.push(card); }Ok(cards)}fn read_held(client: &ClientController, native: Native) -> Result<Held, MethodError> {let kit = crate::phone::tool_acts::app_kit(client)?;letmut tables = Vec::new();letmut lines = Vec::new(); client.read_rows(METHOD, &mut |ctx| { tables = cotton_tools::definitions::table_definitions(ctx).map_err(|e| e.to_string())?.definitions;crate::phone::tool_acts::folded_tables(kit.as_ref(), ctx, &mut tables)?; lines = cotton_tools::presentation::line_rows(ctx.read.driver(), ctx.workspace_id);Ok(Value::Null) }).map_err(|reason| MethodError::new("unreadable", reason))?;let chosen = matchcrate::phone::catalogue::FaceChoiceTable::of(&tables) {Some(choices) => {letmut chosen = Map::new();for row in every_row(json!({"table": choices.table}).as_object().unwrap(), native)? {iflet (Some(table), Some(face)) = (row["data"][&choices.row_key].as_str(), row["data"]["face"].as_str()) { chosen.insert(table.to_string(), json!(face)); } }Some(chosen) }None => None, };Ok(Held { tables, lines, chosen, tools: Vec::new(), view_card: false })}pub(crate) fn definitions(client: &ClientController) -> Result<Vec<TableDefinition>, MethodError> {let kit = crate::phone::tool_acts::app_kit(client)?;letmut tables = Vec::new(); client.read_rows("shell.plus", &mut |ctx| { tables = cotton_tools::definitions::table_definitions(ctx).map_err(|e| e.to_string())?.definitions;crate::phone::tool_acts::folded_tables(kit.as_ref(), ctx, &mut tables)?;Ok(Value::Null) }).map_err(|reason| MethodError::new("unreadable", reason))?;Ok(tables)}/// The view `name` (`<tool>/<id>`, a list's `<tool>/group:<id>`) as the fan/// counts it: its read, head and empty words.pub(super) fn read_view(client: &ClientController, request: &Value, name: &str, zone: &str, native: Native) -> Result<Value, MethodError> {let (tool, id) = name.split_once('/').ok_or_else(|| bad("view is <tool>/<id>"))?;letmut asked = json!({"tool": tool, "only": id, "timezone": zone});ifletSome(today) = request.get("today").filter(|today| !today.is_null()) { asked["today"] = today.clone(); }let answer = crate::phone::tool_views::read_with(client, &asked, native)?; answer["views"].as_array().and_then(|views| views.iter().find(|view| view["id"] == id)).cloned() .ok_or_else(|| bad(&format!("{tool} has no view {id}")))}/// Every row `args` reads, page after page.fn every_row(args: &Map<String, Value>, native: Native) -> Result<Vec<Value>, MethodError> {letmut asked = Value::Object(args.clone()); asked["limit"] = json!(cotton_tools::mcp::handlers::tables::MAX_PAGE_SIZE);letmut page = 0u64;letmut rows = Vec::new();loop { asked["page"] = json!(page);let answer = native(&asked)?; rows.extend(answer["records"].as_array().cloned().unwrap_or_default());match answer["next_page"].as_u64() {Some(next) if next > page => page = next,Some(_) => returnErr(MethodError::new("unreadable", format!("{METHOD}: a page did not advance"))),None => returnOk(rows), } }}/// A column as the deck shows it, for the ink: the core's words for it where/// it said them, else its value.fn ink_text(row: &Value, column: &str, definition: &TableDefinition) -> Option<String> {let data = &row["data"];ifletSome(words) = data["@column_words"][column].as_str() { returnSome(words.to_string()); }if definition.slip.figure.as_deref() == Some(column) {ifletSome(words) = data["@slip_figure"].as_str() { returnSome(words.to_string()); } } text_of(&data[column])}fn text_of(value: &Value) -> Option<String> {match value {Value::String(text) => Some(text.clone()),Value::Number(number) => Some(number.to_string()),Value::Array(items) => Some(items.iter().filter_map(text_of).collect::<Vec<_>>().join(" ")), _ => None, }}fn position(lines: &[LineRow], at: usize, of: usize) -> Value { json!(shell_lines::resolve("cards", "deck.position", lines, &[("at", &at.to_string()), ("of", &of.to_string())]))}/// The record the deck stands on that its page does not hold: its own card,/// and whether the view holds it at all.#[allow(clippy::too_many_arguments)]fn visiting( held: &Held, definition: &TableDefinition, args: &Map<String, Value>, id: &str, request: &Value, native: Native, acts: &mutMap<String, Value>,) -> Result<Value, MethodError> {letmut asked = json!({"table": definition.id, "ids": [id]});ifletSome(zone) = args.get("timezone") { asked["timezone"] = zone.clone(); }let answer = native(&asked)?;letSome(mut row) = answer["records"].as_array().and_then(|rows| rows.first()).cloned() else { returnOk(Value::Null) };// Rare (a search's pick, a card brought from Home): the view read whole.let held_by_view = every_row(args, native)?.iter().any(|row| row["id"] == id);letmut card = card_of(held, definition, &mut row, request, native, acts)?; card["held"] = json!(held_by_view);Ok(card)}/// One record's card, whole.fn card_of( held: &Held, definition: &TableDefinition, row: &mutValue, request: &Value, native: Native, acts: &mutMap<String, Value>,) -> Result<Value, MethodError> {let id = row["id"].as_str().unwrap_or_default().to_string();let resolved = row["data"].as_object_mut().and_then(|data| data.remove(cotton_core::records::card::CARD_KEY));let data = row["data"].as_object().cloned().unwrap_or_default();letmut card = match resolved {Some(Value::Object(card)) => card,Some(_) => returnErr(MethodError::new("unreadable", format!("{METHOD}: {id}'s card is not a card"))),// A table naming no card, under a view naming none: the plain face,// headed by the record's name.Noneif definition.card.is_none() && !held.view_card => {let title = text_of(&data[&definition.title]).filter(|title| !title.trim().is_empty()).unwrap_or_default(); json!({"face": "plain", "fields": {"title": title}}).as_object().cloned().unwrap() }None => returnErr(MethodError::new("unreadable", format!("{METHOD}: {id} came without its card"))), };let drawn = card.get("face").and_then(Value::as_str).unwrap_or("plain").to_string();let face = wear(definition, held.chosen.as_ref(), &drawn, &data);letmut slots = card.remove("fields").and_then(|fields| fields.as_object().cloned()).unwrap_or_default();// An absent picture stays absent all the way to the face.if slots.get("photo").and_then(Value::as_str).is_some_and(|key| key.trim().is_empty()) { slots.remove("photo"); }let opens = definition.card.as_ref().and_then(|card| card.opens.as_ref());match face.as_str() {"album.sleeve" | "album.tray" => {ifletSome(opens) = opens { slots.insert("songs".into(), songs(held, opens, &id, native)?); } }"podcast.radio" => {ifletSome(opens) = opens { slots.insert("episode".into(), episode(held, opens, &id, request["holding"].as_str(), native)?); } }"album.board" | "album.carousel" => {ifletSome(prints) = prints(held, &id, native)? { card.insert("prints".into(), json!(prints)); } } _ => {} }let (tap, offered) = taps(held, definition, &face, &data, &slots, acts)?;let parts = parts_deck(definition, &tap, &id);let related = if parts.is_null() { Value::Null } else { related_counts(held, definition, &id, native)? };letmut answer = json!({"id": id, "face": face, "drawn": drawn,"corner": card.get("corner"), "pressing": card.get("pressing").cloned().unwrap_or(json!(false)),"pace": card.get("pace"), "plate": card.get("plate"), "thread": card.get("thread"),"slots": slots,"pages": pages(definition, &data),"stars": stars(definition, &data), "stored": stored(definition, &data), "reach": reach(&data),"file": file(&data),"delivery": (face == "nancy.delivery").then(|| delivery(&data)),"prints": card.get("prints"),"tap": tap, "acts": offered, "toggle": toggled(definition, &data),"parts": parts, "related": related,// A record a send brought says whom from and when (its provenance columns)."from": crate::phone::cotton_send::from_line(&data, request["timezone"].as_str().unwrap_or("UTC"), &held.lines),"record": row, });ifletSome(answer) = answer.as_object_mut() { answer.retain(|_, value| !value.is_null()); }Ok(answer)}/// What a tap on the card's check writes (`slip.toggle`), `{column: value}`:/// a yes/no flips; a choice that is off goes to its first `toggle_on` value/// (else its second choice), one that is on back to its first — and only/// along its `moves`, so a check that would move a value back writes/// nothing. Null where the card's check writes nothing.pub(crate) fn toggled(definition: &TableDefinition, data: &Map<String, Value>) -> Value {use cotton_core::definitions::ColumnType;letSome(column) = definition.slip.toggle.as_ref().and_then(|key| definition.column(key)) else { returnValue::Null };let key = column.key.clone();match column.column_type {ColumnType::Bool => json!({key.clone(): !data.get(&key).and_then(Value::as_bool).unwrap_or(false)}),ColumnType::Choice => {let choices = column.choices.clone().unwrap_or_default();if choices.len() < 2 { returnValue::Null }let value = data.get(&key).and_then(Value::as_str);let on = match (value, &definition.slip.toggle_on) { (None, _) => false, (Some(value), Some(on)) => on.iter().any(|held| held == value), (Some(value), None) => value != choices[0], };let next = if on { choices[0].clone() } else { definition.slip.toggle_on.as_ref().and_then(|on| on.first().cloned()).unwrap_or_else(|| choices[1].clone()) };iflet (Some(value), Some(moves)) = (value, &column.moves) {if moves.get(value).is_some_and(|allowed| !allowed.contains(&next)) { returnValue::Null } } json!({key: next}) } _ => Value::Null, }}// MARK: Ink over the whole kit/// The deck as asked, for the ink's search over the whole kit.structAsked<'a> { request: &'a Value, definition: &'a TableDefinition, view: Option<&'a Value>, view_name: Option<&'a str>,/// The view in view's read, as the deck reads it unnarrowed. args: &'a Map<String, Value>, ink: &'a str, cursor: usize, limit: usize, zone: &'a str,}/// One thing the letters keep, in the results' order.enumFound {/// A record of `table`, read by its id when its page is dealt; `under`/// the view in view's. `row` its whole row where the matching read it/// whole already (a view dealing a card of its own).Record { table: String, id: String, under: bool, row: Option<Value> },/// A first-tier tile of the fan (a view, a list), as the fan says it.View { tool: String, view: Value, tile: Value },}/// INK SEARCHES THE APP'S WHOLE KIT (owner, 11 Nov 2026: "it's one person's/// data … they should not have to go into each screen and search"). In an/// app of one tool (its fan holds no Home and no Tools card: Books, Music,/// Cinemas, Money, Todos, Downloads, Keys) the letters keep, in this order:////// 1. the records of the view in view they keep, as they narrowed it alone;/// 2. the rest of its table (every other view of the same kind), where the/// table draws a card of its own;/// 3. every other table of the kit that draws a card and that one of the/// tool's views reads (a whole's parts — a series' seasons, a todo's/// repeat — stand under their whole, never alone), in the tool's/// `search` order where it names one, else its `tables` order;/// 4. the fan's first-tier tiles (its views and lists) whose name has a word/// starting with them, each a card that opens its view.////// The match is the deck's (`rules::ink_match`). Each record is its own/// table's card and says its table; `labels_of` gives each table's labels./// The all-in-one Cotton (parked, 11 Nov 2026) narrows its deck alone.fn universal( client: &ClientController, fan: &FanCards, asked: &Asked, held: &mutHeld, native: Native,) -> Result<(Value, Option<std::collections::HashSet<String>>), MethodError> {let definition = asked.definition;let stops = ink_match::stop_words();letmut found: Vec<Found> = Vec::new();letmut seen: std::collections::HashSet<(String, String)> = std::collections::HashSet::new();letmut keep = |found: &mutVec<Found>, table: &str, id: String, under: bool, row: Option<Value>| {if seen.insert((table.to_string(), id.clone())) { found.push(Found::Record { table: table.to_string(), id, under, row }); } };// 1. The view in view, exactly as the letters narrowed it alone: by its// ink columns alone, its cards made only for the page dealt; a view that// deals a card of its own (Owed's receipt, By person's card per person)// is read whole, as it deals.if held.view_card {let columns = ink_match::columns(definition);for row in every_row(asked.args, native)? {if columns.iter().any(|column| ink_match::holds(ink_text(&row, column, definition).as_deref(), asked.ink, &stops)) {let id = row["id"].as_str().unwrap_or_default().to_string(); keep(&mut found, &definition.id, id, true, Some(row)); } } } else {let kept: std::collections::HashSet<String> = matched(&ink_index(client, definition, asked, &held.lines, native)?, asked.ink, &stops).into_iter().collect();for id in view_ids(client, asked.args, native)?.iter().filter(|id| kept.contains(*id)) { keep(&mut found, &definition.id, id.clone(), true, None); } }// 2 and 3. The rest of its table, then the kit's other tables.letmut fan_ask = json!({"timezone": asked.zone});ifletSome(today) = asked.request.get("today").filter(|today| !today.is_null()) { fan_ask["today"] = today.clone(); }let dealt = crate::methods::shell_fan::read_with(client, fan, &fan_ask, native)?;let tools = crate::phone::tool_acts::read_tools(client, METHOD)?;let searched = searched_tables(&held.tables, &tools, &dealt, definition);letmut read: Vec<&TableDefinition> = vec![definition];for table in &searched {letSome(other) = held.tables.iter().find(|found| &found.id == table) else { continue };if other.id != definition.id { read.push(other); }for id in matched(&ink_index(client, other, asked, &held.lines, native)?, asked.ink, &stops) { keep(&mut found, &other.id, id, false, None); } }// 4. The fan's first tier: a single tool's views and lists, by name.ifletSome(tile) = dealt["tiles"].as_array().and_then(|tiles| tiles.first()).filter(|_| dealt["root"]["id"].as_str().is_some_and(|id| id.starts_with("views-"))) {let tool = tile["key"].as_str().unwrap_or_default().to_string();for view in tile["views"].as_array().into_iter().flatten() {if ink_match::holds(view["label"].as_str(), asked.ink, &stops) { found.push(Found::View { tool: tool.clone(), view: view.clone(), tile: tile["tile"].clone() }); } } }// The page: counted over everything kept, its records read by id.let count = found.len();let page: Vec<Found> = found.into_iter().skip(asked.cursor).take(asked.limit).collect();let next = (asked.cursor + page.len() < count).then_some(asked.cursor + page.len());letmut wanted: Vec<(String, bool, Vec<String>)> = Vec::new();for item in &page {ifletFound::Record { table, id, under, row: None } = item {match wanted.iter_mut().find(|(held, beneath, _)| held == table && beneath == under) {Some((_, _, ids)) => ids.push(id.clone()),None => wanted.push((table.clone(), *under, vec![id.clone()])), } } }letmut rows: std::collections::HashMap<(String, String), Value> = std::collections::HashMap::new();for (table, _under, ids) in wanted {letmut ask = json!({"table": table, "ids": ids, "timezone": asked.zone});ifletSome(today) = asked.request.get("today").filter(|today| !today.is_null()) { ask["today"] = today.clone(); }for row in native(&ask)?["records"].as_array().cloned().unwrap_or_default() { rows.insert((table.clone(), row["id"].as_str().unwrap_or_default().to_string()), row); } }let own_tools = std::mem::take(&mut held.tools);let own_view_card = held.view_card;letmut standing: std::collections::HashMap<String, Vec<CardAction>> = std::collections::HashMap::new(); standing.insert(definition.id.clone(), own_tools.clone());letmut acts: Map<String, Value> = Map::new();letmut cards: Vec<Value> = Vec::with_capacity(page.len());letmut family_face: Option<String> = None;letmut labels_of = Map::new(); labels_of.insert(definition.id.clone(), labels(definition, &held.lines));for (at, item) in page.into_iter().enumerate() {letmut card = match item {Found::Record { table, id, under, row } => {letSome(mut row) = row.or_else(|| rows.remove(&(table.clone(), id))) else { continue };letSome(own) = held.tables.iter().find(|found| found.id == table).cloned() else { continue };let in_view = own.id == definition.id;if !standing.contains_key(&own.id) {let acts = crate::phone::tool_acts::standing(client, &own, None, METHOD)?.iter().filter_map(CardAction::tool).collect(); standing.insert(own.id.clone(), acts); } held.tools = standing[&own.id].clone();// A view's own card (Owed's receipt) dresses only its own rows. held.view_card = under && own_view_card && rows_of_view(&row);letmut card = card_of(held, &own, &mut row, asked.request, native, &mut acts)?;if in_view && family_face.is_none() { family_face = card["drawn"].as_str().map(str::to_string); }if opens_group(&card) {let data = card["record"]["data"].as_object().cloned().unwrap_or_default();let view = if under { asked.view } else { None };ifletSome(route) = group_route(&held.tables, &tools, &own, view, &data, card["slots"]["title"].as_str()) { card["group"] = route; } }ifletSome(card) = card.as_object_mut() { card.remove("drawn"); } labels_of.entry(own.id.clone()).or_insert_with(|| labels(&own, &held.lines)); card["table"] = json!(own.id); card }Found::View { tool, view, tile } => view_card(&tool, view, tile, &held.lines, &mut acts), }; card["position"] = position(&held.lines, asked.cursor + at + 1, count); cards.push(card); } held.tools = own_tools; held.view_card = own_view_card;let visitor = match named(asked.request, "visitor") {Some(id) if !cards.iter().any(|card| card["id"] == id) => visiting(held, definition, asked.args, id, asked.request, native, &mut acts)?, _ => Value::Null, };let family_face = family_face.or_else(|| definition.card.as_ref().map(|card| card.face.as_str().to_string()));let hand = match (&held.chosen, &family_face) { (Some(_), Some(face)) => {let offers = offers(definition);if offers.len() > 1 && family(definition).contains(face) { offers } else { Vec::new() } } _ => Vec::new(), };let worn = (!hand.is_empty()).then(|| selected(definition, held.chosen.as_ref())).flatten();let cycles = worn.as_deref().map(|worn| hand_next(&definition.id, &hand, worn, &held.lines));letmut visitor = visitor;if opens_group(&visitor) {let data = visitor["record"]["data"].as_object().cloned().unwrap_or_default();ifletSome(route) = group_route(&held.tables, &tools, definition, asked.view, &data, visitor["slots"]["title"].as_str()) { visitor["group"] = route; } }ifletSome(visitor) = visitor.as_object_mut() { visitor.remove("drawn"); }let empty = (count == 0 && visitor.is_null()).then(|| { json!({"title": shell_lines::resolve("cards", "deck.nothing_starts", &held.lines, &[("letters", asked.ink)]).unwrap_or_default(), "message": ""}) });letmut plus = plus_of(definition);crate::phone::fan_tile::dress_doors(crate::phone::fan_tile::of_table(client, definition, METHOD)?.as_ref(), &mut plus);// Kept while nothing any table it read has moved.let keeps = read.iter().all(|table| table.polled != Some(true) && table.live_read.is_none());let aside = keeps.then(|| {letmut sets = read.iter().map(|table| crate::methods::shell_kept::aside(&held.tables, table));let first = sets.next().unwrap_or_default(); sets.fold(first, |kept, set| kept.intersection(&set).cloned().collect()) });Ok((with_viewer(json!({"table": definition.id, "view": asked.view_name,"cards": cards, "acts": acts, "labels": labels(definition, &held.lines), "labels_of": labels_of,"count": count, "head": Value::Null, "empty": empty,"hand": hand, "worn": worn, "hand_next": cycles,"plus": plus,"visitor": visitor, "next": next, }), definition), aside))}/// Whether a row came under its view's own card (it carries one).fn rows_of_view(row: &Value) -> bool { row["data"].get(cotton_core::records::card::CARD_KEY).is_some()}/// The tables the ink searches after the view in view, in order: the deck's/// own table again (its rest) where it draws a card, then each other table/// of the fan's tools that draws a card and that one of the tool's views/// reads, by the tool's `search` order, else its `tables` order.fn searched_tables(tables: &[TableDefinition], tools: &[ToolDefinition], dealt: &Value, own: &TableDefinition) -> Vec<String> {letmut order: Vec<String> = Vec::new();if own.card.is_some() { order.push(own.id.clone()); }let keys = dealt["tiles"].as_array().into_iter().flatten().filter(|tile| tile["kind"] == "tool").filter_map(|tile| tile["key"].as_str());for key in keys {let (listed, views): (Vec<String>, Vec<&ToolView>) = match tools.iter().find(|tool| tool.id == key) {Some(tool) => (if tool.search.is_empty() { tool.tables.clone() } else { tool.search.clone() }, tool.views.iter().collect()),None => match tables.iter().find(|table| table.tool.as_ref().is_some_and(|tool| tool.key.as_deref().unwrap_or(&table.id) == key)) {Some(home) => (vec![home.id.clone()], home.tool.iter().flat_map(|tool| tool.views.iter()).collect()),None => continue, }, };for table in listed {let drawn = tables.iter().any(|found| found.id == table && found.card.is_some());let viewed = views.iter().any(|view| view.partition.is_none() && view.read.get("table").and_then(Value::as_str) == Some(table.as_str()));if drawn && viewed && !order.contains(&table) { order.push(table); } } } order}/// A table's records as the ink reads them: each id, in the table's order,/// with the words of its ink columns.typeInkIndex = std::sync::Arc<Vec<(String, Vec<Option<String>>)>>;/// What the ink last read, kept while nothing has moved: a table's index,/// a view's ids in its order. A letter after the first matches in memory.structInkKept { at: ((u64, u64), Option<String>, String), index: Option<InkIndex>, ids: Option<std::sync::Arc<Vec<String>>>,}static INK_KEPT: std::sync::Mutex<Vec<InkKept>> = std::sync::Mutex::new(Vec::new());/// The most reads the ink keeps.const INK_KEPT_MOST: usize = 16;fn ink_kept<T: Clone>(key: &((u64, u64), Option<String>, String), take: implFn(&InkKept) -> Option<T>) -> Option<T> { INK_KEPT.lock().ok()?.iter().find(|kept| &kept.at == key).and_then(take)}fn ink_keep(kept: InkKept) {ifletOk(mut all) = INK_KEPT.lock() { all.retain(|held| held.at != kept.at); all.push(kept);let over = all.len().saturating_sub(INK_KEPT_MOST); all.drain(..over); }}/// `definition`'s records by their ink columns alone (a light cut: no card,/// no slip), read once while nothing moves. A column the core says in words/// (a date, an amount: `@column_words`, the slip's figure) is said as a/// whole read says it, from the stored columns it reads.fn ink_index(client: &ClientController, definition: &TableDefinition, asked: &Asked, lines: &[LineRow], native: Native) -> Result<InkIndex, MethodError> {use cotton_core::records::page::{column_words, resolve_slip_figure, Words};let today = asked.request["today"].as_str().unwrap_or_default();let key = (client.moved(), client.attached_database(), format!("index {} {} {today}", definition.id, asked.zone));ifletSome(index) = ink_kept(&key, |kept| kept.index.clone()) { returnOk(index) }let columns = ink_match::columns(definition);let zone = client.time_zone().map(str::to_string);let now = Some(client.clock().now());let words = Words::of_rows(lines);let worded: Vec<String> = column_words(definition, &Map::new(), zone.as_deref(), now, &words).keys().cloned().collect();// Words said for the ink's own columns alone, never every column per row.letmut saying = definition.clone(); saying.columns.retain(|column| columns.contains(&column.key));let figure = definition.slip.figure.clone().filter(|figure| columns.contains(figure));let says = figure.is_some() || columns.iter().any(|column| worded.contains(column));// A worded column reads the columns it names (its currency, its signs).letmut read = columns.clone();if says {for column in definition.columns.iter().filter(|column| columns.contains(&column.key)) {let named = serde_json::to_string(column).unwrap_or_default();let more: Vec<String> = definition.columns.iter() .filter(|other| other.secret != Some(true) && !read.contains(&other.key) && named.contains(&["\"", other.key.as_str(), "\""].concat())) .map(|other| other.key.clone()).collect(); read.extend(more); } }letmut ask = json!({"table": definition.id, "light": true, "cut": true, "columns": read, "timezone": asked.zone,"limit": cotton_tools::mcp::handlers::tables::MAX_LIGHT_PAGE});if !today.is_empty() { ask["today"] = json!(today); }letmut index = Vec::new();letmut page = 0u64;loop { ask["page"] = json!(page);let answer = native(&ask)?;let named: Vec<String> = answer["columns"].as_array().into_iter().flatten().filter_map(|key| key.as_str().map(str::to_string)).collect();for row in answer["rows"].as_array().into_iter().flatten() {letSome(cells) = row.as_array() else { continue };let data: Map<String, Value> = named.iter().cloned().zip(cells.iter().cloned()).collect();let said = says.then(|| column_words(&saying, &data, zone.as_deref(), now, &words));let figured = figure.as_ref().and_then(|_| resolve_slip_figure(definition, &data, zone.as_deref(), now, &words));let texts = columns.iter().map(|column| { said.as_ref().and_then(|said| said.get(column)).and_then(Value::as_str).map(str::to_string) .or_else(|| (figure.as_deref() == Some(column.as_str())).then(|| figured.clone()).flatten()) .or_else(|| text_of(data.get(column).unwrap_or(&Value::Null))) }).collect();ifletSome(id) = data.get("id").and_then(Value::as_str) { index.push((id.to_string(), texts)); } }match answer["next_page"].as_u64() {Some(next) if next > page => page = next,Some(_) => returnErr(MethodError::new("unreadable", format!("{METHOD}: a page did not advance"))),None => break, } }let index: InkIndex = std::sync::Arc::new(index); ink_keep(InkKept { at: key, index: Some(index.clone()), ids: None });Ok(index)}/// The ids an index holds that some word of whose ink columns starts with the letters, in order.fn matched(index: &InkIndex, ink: &str, stops: &[String]) -> Vec<String> { index.iter().filter(|(_, texts)| texts.iter().any(|text| ink_match::holds(text.as_deref(), ink, stops))).map(|(id, _)| id.clone()).collect()}/// The ids `args` reads (the view in view), in its order: a cut of its ids alone, kept while nothing moves.fn view_ids(client: &ClientController, args: &Map<String, Value>, native: Native) -> Result<std::sync::Arc<Vec<String>>, MethodError> {let key = (client.moved(), client.attached_database(), format!("ids {}", Value::Object(args.clone())));ifletSome(ids) = ink_kept(&key, |kept| kept.ids.clone()) { returnOk(ids) }letmut ask = Value::Object(args.clone()); ask["light"] = json!(true); ask["cut"] = json!(true); ask["columns"] = json!([]); ask["limit"] = json!(cotton_tools::mcp::handlers::tables::MAX_LIGHT_PAGE);letmut ids = Vec::new();letmut page = 0u64;loop { ask["page"] = json!(page);let answer = native(&ask)?; ids.extend(answer["rows"].as_array().into_iter().flatten().filter_map(|row| row[0].as_str().map(str::to_string)));match answer["next_page"].as_u64() {Some(next) if next > page => page = next,Some(_) => returnErr(MethodError::new("unreadable", format!("{METHOD}: a page did not advance"))),None => break, } }let ids = std::sync::Arc::new(ids); ink_keep(InkKept { at: key, index: None, ids: Some(ids.clone()) });Ok(ids)}/// A first-tier tile of the fan standing in the results: drawn by the fan's/// own tile look (`tile`, the tool's fan tile), its `view` as the fan says/// it; a tap opens that view (`open.view`) and it offers no act.fn view_card(tool: &str, view: Value, tile: Value, lines: &[LineRow], acts: &mutMap<String, Value>) -> Value { acts.entry("open.view".to_string()).or_insert_with(|| json!({"label": shell_lines::resolve("cards", "deck.open.view", lines, &[]), "kind": "open", "red": false}));let id = view["id"].as_str().unwrap_or_default().to_string();let label = view["label"].clone();let table = view["read"]["table"].clone(); json!({"id": format!("view:{tool}/{id}"), "kind": "view", "face": "fan.view", "tool": tool, "view": view, "tile": tile,"table": table, "pressing": false,"slots": {"title": label}, "pages": [], "stored": {}, "reach": reach(&Map::new()),"tap": {"card": "open.view"}, "acts": [],"record": {"id": format!("view:{tool}/{id}"), "table": table, "data": {"name": label}}, })}// MARK: The face wornpub(crate) fn offers(definition: &TableDefinition) -> Vec<String> {letSome(card) = &definition.card else { returnVec::new() };if card.offers.is_empty() { vec![card.face.as_str().to_string()] } else { card.offers.iter().map(|face| face.as_str().to_string()).collect() }}fn family(definition: &TableDefinition) -> Vec<String> {letmut faces = offers(definition); faces.extend(definition.card.iter().flat_map(|card| card.faces.iter()).map(|rule| rule.face.as_str().to_string())); faces}/// The face the person chose for `definition`, when one of its offers; else its first offer.pub(crate) fn selected(definition: &TableDefinition, chosen: Option<&Map<String, Value>>) -> Option<String> {let offers = offers(definition);match chosen.and_then(|chosen| chosen.get(&definition.id)).and_then(Value::as_str) {Some(face) if offers.iter().any(|offer| offer == face) => Some(face.to_string()), _ => offers.first().cloned(), }}/// The face `drawn` worn as the person chose for its table: only a card drawn/// in the table's family wears the choice (a view naming another face —/// Birthdays over People — keeps it), and the table's base face chosen takes/// its by-value rule where one holds of the record.pub(crate) fn wear(definition: &TableDefinition, chosen: Option<&Map<String, Value>>, drawn: &str, data: &Map<String, Value>) -> String {letSome(base) = &definition.card else { return drawn.to_string() };letSome(chosen_map) = chosen else { return drawn.to_string() };if base.offers.is_empty() && !chosen_map.contains_key(&definition.id) { return drawn.to_string() }if !family(definition).iter().any(|face| face == drawn) { return drawn.to_string() }letSome(face) = selected(definition, chosen) else { return drawn.to_string() };if face == base.face.as_str() {ifletSome(rule) = base.faces.iter().find(|rule| data.get(&rule.when.column).and_then(Value::as_str).is_some_and(|value| rule.when.values.iter().any(|held| held == value))) {return rule.face.as_str().to_string(); } } face}/// A face in the person's words: its kit title (`cards` `faces.titles.*`).pub(crate) fn face_title(face: &str, lines: &[LineRow]) -> String { shell_lines::resolve("cards", &format!("faces.titles.{}", face.replace('.', "_")), lines, &[]).unwrap_or_default()}/// What the hand's tap does: the face after the one worn, wrapping, what/// VoiceOver says of it, and what `shell.input` commits to wear it.fn hand_next(table: &str, hand: &[String], worn: &str, lines: &[LineRow]) -> Value {let next = &hand[hand.iter().position(|face| face == worn).map_or(0, |at| at + 1) % hand.len()];let label = shell_lines::resolve("cards", "deck.face", lines, &[("face", &face_title(worn, lines)), ("next", &face_title(next, lines))]); json!({"face": next, "label": label, "writes": {"kind": "face", "table": table, "face": next}})}// MARK: Where a group card opens/// Every declared view with the name it goes by (`<tool>/<id>`): each home/// table's tool (keyed by its key, else the table's id), then each installed tool's.fn views<'a>(tables: &'a [TableDefinition], tools: &'a [ToolDefinition]) -> implIterator<Item = (String, &'a ToolView)> {let homes = tables.iter().flat_map(|table| { table.tool.iter().flat_map(move |tool| {let name = tool.key.clone().unwrap_or_else(|| table.id.clone()); tool.views.iter().map(move |view| (name.clone(), view)) }) }); homes.chain(tools.iter().flat_map(|tool| tool.views.iter().map(move |view| (tool.id.clone(), view))))}/// Where a tap on a group card goes: the view its tool partitions the table/// by the card's people column, scoped to the person, headed by the view's/// label and the card's name. None for a row naming no one, and where no/// tool partitions the table by that column.fn group_route( tables: &[TableDefinition], tools: &[ToolDefinition], definition: &TableDefinition, view: Option<&Value>, data: &Map<String, Value>, title: Option<&str>,) -> Option<Value> {// A view dealing its own card (Money's By person) names its people there.let viewed = view.and_then(|view| view["card"]["fields"].as_array()).and_then(|fields| fields.iter().find(|field| field["slot"] == "people")).and_then(|field| field["column"].as_str()).map(str::to_string);let column = viewed.or_else(|| definition.card.as_ref()?.fields.iter().find(|field| field.slot == CardSlot::People)?.column.clone())?;let value = data.get(&column).and_then(Value::as_str).filter(|value| !value.is_empty())?;let (tool, view) = views(tables, tools) .find(|(_, view)| view.partition.as_deref() == Some(column.as_str()) && view.read.get("table").and_then(Value::as_str) == Some(definition.id.as_str()))?;let title = match title.map(str::trim).filter(|name| !name.is_empty()) {Some(name) => format!("{} \u{00B7} {name}", view.label),None => view.label.clone(), };Some(json!({"table": definition.id, "column": column, "value": value, "view": format!("{tool}/{}", view.id), "title": title}))}// MARK: The readingsfn slot_name(slot: CardSlot) -> String { serde_json::to_value(slot).ok().and_then(|value| value.as_str().map(str::to_string)).unwrap_or_default()}/// The labels the card's places and its table's columns stand under: each/// place under its card label (a `cards` line) or the first column filling/// it, each column under its own. Once per page, never per card.fn labels(definition: &TableDefinition, lines: &[LineRow]) -> Value {letmut by_slot = Map::new();for field in definition.card.iter().flat_map(|card| card.fields.iter()) {let label = field.label.as_ref().and_then(|line| shell_lines::resolve("cards", line, lines, &[])) .or_else(|| field.column.as_ref().and_then(|column| definition.column(column)).map(|column| column.label()));ifletSome(label) = label { by_slot.entry(slot_name(field.slot)).or_insert(json!(label)); } }let by_column: Map<String, Value> = definition.columns.iter().map(|column| (column.key.clone(), json!(column.label()))).collect(); json!({"by_slot": by_slot, "by_column": by_column})}/// The columns the card turns to after its face (`card.pages`) that hold/// words, in order, each under its column's label.fn pages(definition: &TableDefinition, data: &Map<String, Value>) -> Vec<Value> { definition.card.iter().flat_map(|card| card.pages.iter()).filter_map(|key| {let text = data.get(key).and_then(Value::as_str).map(str::trim).filter(|text| !text.is_empty())?;let column = definition.column(key);let markdown = column.and_then(|column| column.markdown) == Some(true) || definition.card.iter().flat_map(|card| card.fields.iter()).any(|field| field.column.as_deref() == Some(key) && field.markdown);Some(json!({"label": column.map(|column| column.label()).unwrap_or_else(|| key.clone()), "text": text, "markdown": markdown})) }).collect()}/// The rating the facts place names in the rating column, out of five.fn stars(definition: &TableDefinition, data: &Map<String, Value>) -> Option<f64> {let facts = definition.card.as_ref()?.fields.iter().find(|field| field.slot == CardSlot::Facts)?;let named = facts.column.iter().chain(facts.also.iter()).any(|column| column == "rating");let value = data.get("rating").and_then(Value::as_f64)?; (named && (0.0..=5.0).contains(&value)).then_some(value)}/// The value stored in the column filling each place, as kept, by slot; the/// state place's set yes/no flag (`also`) first, by its key.fn stored(definition: &TableDefinition, data: &Map<String, Value>) -> Map<String, Value> {letmut stored = Map::new();for field in definition.card.iter().flat_map(|card| card.fields.iter()) {let slot = slot_name(field.slot);if field.slot == CardSlot::State {ifletSome(flag) = field.also.iter().find(|key| matches!(data.get(*key), Some(Value::Bool(true))) || data.get(*key).and_then(Value::as_f64) == Some(1.0)) { stored.insert(slot, json!(flag));continue; } }if stored.contains_key(&slot) { continue }ifletSome(text) = field.column.as_ref().and_then(|column| data.get(column)).and_then(Value::as_str) { stored.insert(slot, json!(text)); } } stored}/// The numbers and addresses a person's record holds, their thread's channel,/// and which handoffs they reach.fn reach(data: &Map<String, Value>) -> Value {let list = |key: &str| -> Vec<String> {match data.get(key) {Some(Value::Array(items)) => items.iter().filter_map(|item| item.as_str().map(str::to_string)).collect(),Some(Value::String(text)) => vec![text.clone()], _ => Vec::new(), } };let phones = list("phones");let emails: Vec<String> = list("emails").into_iter().filter(|email| email.contains('@')).collect();let dialable = phones.iter().any(|phone| phone.chars().any(|ch| ch.is_ascii_digit())); json!({"phones": phones, "emails": emails, "channel": data.get("thread_channel"),"call": dialable, "message": dialable, "email": !emails.is_empty()})}/// The record's own file (`storage_path`): a document's first page.fn file(data: &Map<String, Value>) -> Value {match data.get("storage_path") {Some(Value::String(key)) if !key.is_empty() => json!(key),Some(Value::Object(file)) => file.get("ref").filter(|key| key.as_str().is_some_and(|key| !key.is_empty())).cloned().unwrap_or(Value::Null), _ => Value::Null, }}/// A delivery as its columns hold it.fn delivery(data: &Map<String, Value>) -> Value {let plan = match data.get("subscription") {None | Some(Value::Null) => false,Some(Value::String(text)) => !text.trim().is_empty(),Some(Value::Array(items)) => !items.is_empty(),Some(Value::Object(fields)) => !fields.is_empty(),Some(_) => true, }; json!({"delivered": data.get("delivered") == Some(&json!(true)), "paid": data.get("paid") == Some(&json!(true)), "on_plan": plan})}// MARK: What a whole's card holds/// The parts a whole opens into, in the card's order (`card.opens`).fn parts(opens: &cotton_core::definitions::card::CardOpens, whole: &str, native: Native) -> Result<Vec<Value>, MethodError> {letmut rows = every_row(json!({"table": opens.table, "where": {opens.by.clone(): whole}}).as_object().unwrap(), native)?;if !opens.order.is_empty() { rows.sort_by(|a, b| {for key in &opens.order {let (x, y) = (&a["data"][key], &b["data"][key]);let ordering = match (blank(x), blank(y)) { (false, true) => std::cmp::Ordering::Less, (true, false) => std::cmp::Ordering::Greater, (true, true) => std::cmp::Ordering::Equal, (false, false) => match (x.as_f64(), y.as_f64()) { (Some(x), Some(y)) => x.partial_cmp(&y).unwrap_or(std::cmp::Ordering::Equal), _ => text_of(x).cmp(&text_of(y)), }, };if ordering != std::cmp::Ordering::Equal { return ordering; } } std::cmp::Ordering::Equal }); }Ok(rows)}fn blank(value: &Value) -> bool {match value {Value::Null => true,Value::String(text) => text.trim().is_empty(),Value::Array(items) => items.is_empty(), _ => false, }}/// The parts as the records they stand for (`through`), in their order.fn standing(held: &Held, opens: &cotton_core::definitions::card::CardOpens, parts: Vec<Value>, native: Native) -> Result<(String, Vec<Value>), MethodError> {letSome(through) = &opens.through else { returnOk((opens.table.clone(), parts)) };let linked = held.tables.iter().find(|table| table.id == opens.table).and_then(|table| table.column(through)).and_then(|column| column.link_to.clone()) .ok_or_else(|| MethodError::new("unreadable", format!("{METHOD}: {}'s {through} links nowhere", opens.table)))?;let ids: Vec<String> = parts.iter().filter_map(|part| match &part["data"][through] {Value::String(id) => Some(id.clone()),Value::Array(ids) => ids.first().and_then(Value::as_str).map(str::to_string), _ => None, }).take(MOST_SONGS).collect();if ids.is_empty() { returnOk((linked, Vec::new())) }let read = native(&json!({"table": linked, "ids": ids}))?;let found = read["records"].as_array().cloned().unwrap_or_default();let ordered = ids.iter().filter_map(|id| found.iter().find(|row| row["id"] == id.as_str()).cloned()).collect();Ok((linked, ordered))}fn length_of(held: &Held, table: &str, row: &Value) -> f64 {let column = held.tables.iter().find(|found| found.id == table).and_then(|found| found.card.as_ref()) .and_then(|card| card.fields.iter().find(|field| field.slot == CardSlot::Length)).and_then(|field| field.column.clone()); column.and_then(|column| row["data"][&column].as_f64()).unwrap_or(0.0).max(0.0)}/// A sleeve's songs: each its title, line and art by its own/// card's places, its length, and the recording it plays — or `unavailable`.fn songs(held: &Held, opens: &cotton_core::definitions::card::CardOpens, whole: &str, native: Native) -> Result<Value, MethodError> {let (table, tracks) = standing(held, opens, parts(opens, whole, native)?, native)?;Ok(Value::Array(tracks.iter().take(MOST_SONGS).map(|track| {let card = &track["data"][cotton_core::records::card::CARD_KEY]["fields"];letmut entry = json!({"record": track["id"], "duration": length_of(held, &table, track)});for slot in ["title", "subtitle", "photo"] {ifletSome(words) = card[slot].as_str().filter(|words| !words.is_empty()) { entry[slot] = json!(words); } }match card["play"].as_str().filter(|file| !file.is_empty()) {Some(file) => entry["play"] = json!(file),None => entry["unavailable"] = json!(true), } entry }).collect()))}/// A show's radio's episode: the one the player holds when it is the show's,/// else the newest started, else the newest (owner, 4 Nov 2026); null for a/// show with none yet.fn episode(held: &Held, opens: &cotton_core::definitions::card::CardOpens, whole: &str, holding: Option<&str>, native: Native) -> Result<Value, MethodError> {let parts = parts(opens, whole, native)?;let date = held.tables.iter().find(|table| table.id == opens.table).and_then(|table| table.date.clone());let chosen = holding.and_then(|holding| parts.iter().find(|part| part["id"] == holding)).or_else(|| {letmut newest: Vec<&Value> = parts.iter().collect(); newest.sort_by(|a, b| {let day = |row: &Value| date.as_ref().and_then(|date| row["data"][date].as_str()).unwrap_or_default().to_string(); day(b).cmp(&day(a)) }); newest.iter().find(|part| part["data"]["played"] == "started").or(newest.first()).copied() });letSome(chosen) = chosen else { returnOk(Value::Null) };letmut entry = json!({"table": opens.table, "record": chosen["id"], "duration": length_of(held, &opens.table, chosen)});ifletSome(title) = chosen["data"][cotton_core::records::card::CARD_KEY]["fields"]["title"].as_str().filter(|title| !title.is_empty()) { entry["title"] = json!(title); }Ok(entry)}/// An album's print keys, in the album's order: the first of its page's list.fn prints(held: &Held, album: &str, native: Native) -> Result<Option<Vec<String>>, MethodError> {letSome(definition) = held.tables.iter().find(|table| table.id == "album") else { returnOk(None) };letSome(list) = definition.page.iter().find_map(|section| section.list.as_ref()) else { returnOk(None) };letSome(photo) = held.tables.iter().find(|table| table.id == list.table).and_then(|table| table.slip.photo.clone()) else { returnOk(None) };letmut filter: Map<String, Value> = list.where_.iter().flat_map(|own| own.iter()).map(|(key, value)| (key.clone(), value.clone())).collect();ifletSome(link) = &list.link { filter.insert(link.clone(), json!(album)); }let read = native(&json!({"table": list.table, "where": filter, "limit": MOST_PRINTS}))?;Ok(Some(read["records"].as_array().into_iter().flatten().take(MOST_PRINTS) .filter_map(|row| row["data"][&photo].as_str().filter(|key| !key.is_empty()).map(str::to_string)).collect()))}// MARK: A list's own card/// The face a list's deck named `name` (`<tool>/group:<id>`) leads with,/// and its list: the tool's `lists` face, where the tool names one.fn listed(client: &ClientController, name: &str) -> Result<Option<(String, String)>, MethodError> {letSome((tool, group)) = name.split_once('/').and_then(|(tool, id)| Some((tool, id.strip_prefix("group:")?))) else { returnOk(None) };letmut face = None; client.read_rows(METHOD, &mut |ctx| {let tools = cotton_tools::definitions::tool_definitions(ctx).map_err(|e| e.to_string())?.definitions; face = tools.iter().find(|found| found.id == tool).and_then(|found| found.lists.as_ref()).map(|lists| lists.face.as_str().to_string());Ok(Value::Null) }).map_err(|reason| MethodError::new("unreadable", reason))?;Ok(face.map(|face| (face, group.to_string())))}/// The list's own card (`rules::list_card`), worn in its tool's face: its/// name, its members in the list's order, counted and timed, its picture/// (else its first member's). A tap on it plays the list (`open.play`);/// it offers no act of a member's — the list's own stand on its held tile/// and its deck. `list` names the list it stands for, and its `record` is/// the list's row, never one of the deck's table.fn list_card( client: &ClientController, held: &Held, face: &str, group: &str, native: Native, acts: &mutMap<String, Value>,) -> Result<Value, MethodError> {use cotton_tools::mcp::handlers::tables::groups;letmut found = None; client.read_rows(METHOD, &mut |ctx| {letSome((data, None)) = groups::group_of(ctx.read.driver(), group)? else { returnOk(Value::Null) };let members = groups::member_order(ctx, group).map_err(|failure| failure.to_string())?; found = Some((data, members));Ok(Value::Null) }).map_err(|reason| MethodError::new("unreadable", reason))?;let (data, members) = found.ok_or_else(|| bad(&format!("There is no list {group}")))?;let table = data.get("table").and_then(Value::as_str).unwrap_or_default().to_string();let ids: Vec<&String> = members.iter().take(MOST_SONGS).collect();let rows = if ids.is_empty() { Vec::new() } else { native(&json!({"table": table, "ids": ids}))?["records"].as_array().cloned().unwrap_or_default() };let members: Vec<cotton_core::rules::list_card::Member> = ids.iter().filter_map(|id| rows.iter().find(|row| row["id"] == id.as_str())).map(|row| {let card = &row["data"][cotton_core::records::card::CARD_KEY]["fields"];let said = |slot: &str| card[slot].as_str().map(str::to_string); cotton_core::rules::list_card::Member { record: row["id"].as_str().unwrap_or_default().to_string(), title: said("title"), subtitle: said("subtitle"), photo: said("photo"), play: said("play"), seconds: length_of(held, &table, row), } }).collect();let name = groups::name_of(&data);let slots = cotton_core::rules::list_card::places(name, data.get(groups::PICTURE).and_then(Value::as_str), &members, &held.lines); acts.entry("open.play".to_string()).or_insert_with(|| json!({"label": shell_lines::resolve("cards", "deck.open.play", &held.lines, &[]), "kind": "open", "red": false}));letmut record = Map::new(); record.insert("name".into(), json!(name)); record.insert("table_id".into(), json!(table));ifletSome(picture) = data.get(groups::PICTURE) { record.insert("picture".into(), picture.clone()); }Ok(json!({"id": group, "face": face, "list": group, "pressing": false,"slots": slots, "pages": [], "stored": {}, "reach": reach(&Map::new()),"tap": {"card": "open.play"}, "acts": [],"record": {"id": group, "table": "record_group", "data": record}, }))}// MARK: Taps and acts/// What a tap on the card does (`card`) and on its check (`check`), and the/// acts it offers in the held card's order (`acts` names each once).#[allow(clippy::too_many_arguments)]fn taps( held: &Held, definition: &TableDefinition, face: &str, data: &Map<String, Value>, slots: &Map<String, Value>, acts: &mutMap<String, Value>,) -> Result<(Value, Vec<String>), MethodError> {let opening = opening(definition, face, data);let open = format!("open.{opening}"); acts.entry(open.clone()).or_insert_with(|| json!({"label": shell_lines::resolve("cards", &format!("deck.open.{opening}"), &held.lines, &[]), "kind": "open", "red": false}));letmut tap = json!({"card": open});if slots.get("check").is_some_and(Value::is_boolean) { acts.entry("check".to_string()).or_insert_with(|| json!({"label": shell_lines::resolve("cards", "deck.check", &held.lines, &[]), "kind": "toggle", "red": false})); tap["check"] = json!("check"); }let worn = held.chosen.is_some().then_some(face);let offered = card_actions::opened(definition, data, &held.lines, card_actions::Held { face: worn, blank: false }, held.tools.clone());letmut ids = Vec::with_capacity(offered.len());for act in offered { ids.push(act.id.clone());let kind = serde_json::to_value(act.kind).map_err(|why| MethodError::new("unreadable", why.to_string()))?; acts.entry(act.id).or_insert_with(|| json!({"label": act.label, "kind": kind, "red": act.red, "primary": act.primary, "icon": act.icon})); }Ok((tap, ids))}/// The deck a whole's card opens into: its parts' table, narrowed to the parts/// naming it (`card.opens`' `by`); none where the tap opens no whole.pub(crate) fn parts_deck(definition: &TableDefinition, tap: &Value, id: &str) -> Value {letSome(opens) = definition.card.as_ref().and_then(|card| card.opens.as_ref()) else { returnValue::Null };if tap["card"] != "open.whole" { returnValue::Null } json!({"table": opens.table, "where": {opens.by.clone(): id}})}/// A whole's related lists that name it by a column, each counted over its/// read and said in its table's line (`cards.opened.related.<table>`, its/// plural form by the count; a table with no line its label and count).fn related_counts(held: &Held, definition: &TableDefinition, id: &str, native: Native) -> Result<Value, MethodError> {letmut counts = Vec::new();for related in definition.related.iter().flatten() {letSome(column) = &related.column else { continue };letmut filter: Map<String, Value> = related.filter.iter().flat_map(|filter| filter.iter()).map(|(key, value)| (key.clone(), value.clone())).collect(); filter.insert(column.clone(), json!(id));let count = native(&json!({"table": related.table, "where": filter, "limit": 1}))?["total"].as_u64().unwrap_or(0);let figure = count.to_string();let own = format!("opened.related.{}", related.table);let said = shell_lines::resolve("cards", &own, &held.lines, &[("n", &figure)]) .or_else(|| shell_lines::resolve("cards", "opened.related.labelled", &held.lines, &[("n", &figure), ("label", &related.label)])) .unwrap_or_default(); counts.push(json!({"id": related.table, "said": said, "count": count})); }Ok(json!(counts))}/// Where a tap on a card goes, by its table's definition (`OPENS`): a scene/// whose table writes it (`story.write`) into the writer, a book/// opens in the reader before anything else it opens; a whole into its/// parts; a group card into the view partitioned by its people; a thread/// into its conversation; a thing the viewer shows into the viewer; a card/// of its own words into its reading page; any other opens at rest.////// A BOOK WITH NO FILE OPENS AT REST (362 walk, 8 Nov 2026). The XXXL step/// tapped the first card of Books › All, a book the shelf holds by its/// details alone (seeded, or brought from Goodreads), and the reader came up/// only to say "This book could not be opened". The reader is where a row's/// Read command is offered (its `when`: the book holds a file); a row whose/// Read is not offered opens at rest, where Add file is.pub(crate) fn opening(definition: &TableDefinition, face: &str, data: &Map<String, Value>) -> &'static str {let read = definition.commands.iter().flatten() .find(|command| command.method.as_deref() == Some("reader.open") && command.bindings.as_ref().and_then(|bindings| bindings.get("id")).map(String::as_str) == Some("$id"));if read.is_some_and(|read| read.when.is_some() && !read.offered_on(&Value::Object(data.clone()))) {return OPENS[OPENS.len() - 1]; }let reader = read.is_some();// A scene is written, never read at rest: its Write command opens the writer.let writer = definition.commands.iter().flatten() .any(|command| command.method.as_deref() == Some(WRITE) && command.bindings.as_ref().and_then(|bindings| bindings.get("id")).map(String::as_str) == Some("$id"));let card = definition.card.as_ref();let whole = card.and_then(|card| card.opens.as_ref()).is_some_and(|opens| match &opens.when {None => true,Some(when) => data.get(&when.column).and_then(Value::as_str).is_some_and(|value| when.values.iter().any(|held| held == value)), });let group = face == "group";let conversation = definition.conversation.is_some() && definition.resolved_page_parts().contains(&cotton_core::definitions::parts::PagePart::Messages);let viewer = definition.viewer.is_some() || definition.slip.player.is_some();let reading = reads(definition, data);let at = [writer, reader, whole, group, conversation, viewer, reading].iter().position(|holds| *holds).unwrap_or(OPENS.len() - 1); OPENS[at]}/// Whether the card opens a reading page: a card of its own words (a note, a/// memory, a book), pictured only when it is a book, with a long text to read.fn reads(definition: &TableDefinition, data: &Map<String, Value>) -> bool {letSome(card) = &definition.card else { returnfalse };let face = card.face.as_str();if !["note.page", "memory", "book.hardback"].contains(&face) { returnfalse }if face != "book.hardback" && card.fields.iter().any(|field| field.slot == CardSlot::Photo) { returnfalse }let long = |key: &str| definition.column(key).is_some_and(|column| column.column_type == cotton_core::definitions::ColumnType::Longtext);letmut bodies: Vec<String> = if long(&definition.title) { vec![definition.title.clone()] } else { Vec::new() };for slot in [CardSlot::Body, CardSlot::Quote] {ifletSome(body) = card.fields.iter().find(|field| field.slot == slot).and_then(|field| field.column.clone()) {if !bodies.contains(&body) && long(&body) { bodies.push(body); } } } bodies.iter().any(|body| data.get(body).and_then(Value::as_str).is_some_and(|text| !text.trim().is_empty()))}// MARK: The empty deck#[allow(clippy::too_many_arguments)]fn empty_words( client: &ClientController, request: &Value, definition: &TableDefinition, view: Option<&Value>, name: Option<&str>, ink: &str, lines: &[LineRow], zone: &str, native: Native,) -> Result<Value, MethodError> {// Letters that leave no card say so, in place of the view's own words.if !ink.is_empty() {returnOk(json!({"title": shell_lines::resolve("cards", "deck.nothing_starts", lines, &[("letters", ink)]).unwrap_or_default(), "message": ""})); }let table = || {let (title, message) = table_empty(client, definition, lines); json!({"title": title, "message": message}) };letSome(empty) = view.map(|view| &view["read"]["empty"]).filter(|empty| empty.is_object()) else { returnOk(table()) };// A narrowed view says its own words until the whole table is empty.if empty["total"] == 0 { returnOk(table()) }letSome(line) = empty["line"].as_str() else { returnOk(table()) };let said = empty["view"].as_str().unwrap_or_default();letmut words = vec![shell_lines::resolve("cards", line, lines, &[("view", said)]).unwrap_or_default()];iflet (Some(counts), Some(name)) = (empty["counts"].as_object(), name) {// The views it points to, counted (Upcoming's "3 are late").let tool = name.split_once('/').map(|(tool, _)| tool).unwrap_or(name);letmut asked = json!({"tool": tool, "timezone": zone});ifletSome(today) = request.get("today").filter(|today| !today.is_null()) { asked["today"] = today.clone(); }let every = crate::phone::tool_views::read_with(client, &asked, native)?;letmut related: Vec<(&String, &Value)> = counts.iter().collect(); related.sort_by(|a, b| a.0.cmp(b.0));for (id, template) in related {let count = every["views"].as_array().and_then(|views| views.iter().find(|view| view["id"] == id.as_str())).and_then(|view| view["count"].as_u64()).unwrap_or(0);if count == 0 { continue }ifletSome(said) = template.as_str().and_then(|template| shell_lines::resolve("cards", template, lines, &[("count", &count.to_string())])) { words.push(said); } } }Ok(json!({"title": words.join(" "), "message": ""}))}/// What an empty table says: its definition's words, or the generic "No/// <plural> yet". An app alone on its phone (its manifest's `sync: false`:/// Rigby, no Mac, no account, nothing arriving from chats) says its own,/// `empty.alone.<table>`, where the definition's words speak of Cotton or a/// Mac (Rigby 11 walk, 8 Nov 2026: Photos "from your chats", Albums "Cotton/// looks through your pictures", Web pages "Share a link to Cotton").pub(crate) fn table_empty(client: &ClientController, definition: &TableDefinition, lines: &[LineRow]) -> (String, String) {// Another device of the person's holds their things and this one waits to be let in: the slim line's words,// never "No albums yet" nor "Loading your data…".ifletSome(waiting) = crate::phone::getting_in::waiting_line(client) {return (waiting, String::new()); }// The person's things are on their way (a first pull, or a backup that// connected this copy and waits for the key): never "No albums yet".ifcrate::methods::shell_home::bringing(client) {ifletSome(title) = shell_lines::resolve("empty", "bringing", lines, &[("plural", &definition.plural.to_lowercase())]) {return (title, String::new()); } }if !client.syncs() {let alone = |part: &str| shell_lines::resolve("empty", &format!("alone.{}.{part}", definition.id), lines, &[]);ifletSome(title) = alone("title") {return (title, alone("message").unwrap_or_default()); } }match &definition.empty {Some(empty) => (empty.title.clone(), empty.message.clone().unwrap_or_default()),None => (shell_lines::resolve("definitions", "reading.empty", lines, &[("plural", &definition.plural.to_lowercase())]).unwrap_or_default(), String::new()), }}fn named<'a>(request: &'a Value, key: &str) -> Option<&'a str> { request.get(key).and_then(Value::as_str).map(str::trim).filter(|value| !value.is_empty())}fn bad(why: &str) -> MethodError {MethodError::new("bad_request", why.to_string())}#[cfg(test)]#[path = "shell_deck_tests.rs"]mod tests;