//! A tool's ordered views and their list totals, as `shell.fan` answers the//! tile the fan stands on (`{tool, today?, timezone?}`).//!//! The tool's lists (its tables' groups) follow its fixed views, or stand//! just before the view that says so (`ToolView::lists_before`: Books'//! lists before On this phone). A view with a head (`ToolView::head`) says//! it as `head`: its rows counted in the head's period, against a goal one//! row holds ("12 of 24 this year"). A view's painted tile goes as//! `picture` (`ToolView::picture`), the fan's to draw.//!//! A list's tile is made from what it holds (5 Nov 2026): each list answers//! `stack`, the pictures of its first three members in the list's order —//! the column the table's face draws its picture from (a book's cover, a//! film's poster), a member with none left out — and `cover`, the list's own//! picture when the person gave it one (`record_group.picture`), which the//! tile draws in the stack's place. Keys only: the tile reads each//! picture's thumbnail from this phone (`read.mediaPath`), never the network.usecrate::methods::MethodError;usecrate::shell::client::ClientController;use serde_json::{json, Value};/// A tool's views as `shell.fan` counts them, read on the phone's own/// records path (the suites').#[cfg(test)]pubfn read(client: &ClientController, request: &Value) -> Result<Value, MethodError> { read_with(client, request, &|args| super::records::call(client, "records.list", args))}/// The views `shell.fan` counts for the tile the fan stands on: native/// engines are read through `native`, outside the file transaction, just as/// records.list does.pub(crate) fn read_with( client: &ClientController, request: &Value, native: &dynFn(&Value) -> Result<Value, MethodError>,) -> Result<Value, MethodError> {let tool = request["tool"] .as_str() .ok_or_else(|| MethodError::new("bad_request", "a tool's views are asked by the tool's id"))?;// One view alone (`shell.deck`'s): its id, a list's `group:<id>`.let only = request["only"].as_str();let now = client.clock().now().timestamp_millis();let zone = request["timezone"] .as_str() .unwrap_or(client.time_zone().unwrap_or("UTC"));if !cotton_tools::mcp::handlers::common::is_known_zone(zone) {returnErr(MethodError::new("bad_request","timezone is a named time zone", )); }let today = match request["today"].as_str() {Some(day) if cotton_core::records::is_date(day) => day.to_string(),Some(_) => {returnErr(MethodError::new("bad_request","today is a day, YYYY-MM-DD", )) }None => cotton_tools::mcp::handlers::common::today_in(zone, now) .map_err(|e| MethodError::new("bad_request", e.to_string()))?, };// The app's kit: the tools it folds, and no view over a table it leaves to another app (`AppKit::deals_view`).let kit = crate::phone::tool_acts::app_kit(client)?;letmut result = client.read_rows("shell.fan.views", &mut |ctx| {letmut definitions = cotton_tools::definitions::table_definitions(ctx).map_err(|e| e.to_string())?;// The tools the app's kit folds are its one tool's views (Cotton People's Birthdays).letmut folded = None;ifletSome(kit) = kit.as_ref().filter(|kit| kit.folds_any()) {letmut tools = cotton_tools::definitions::tool_definitions(ctx).map_err(|e| e.to_string())?.definitions; kit.fold(&mut definitions.definitions, &mut tools); folded = Some(tools); }let table = definitions.definitions.iter().find(|table| table.tool.as_ref().is_some_and(|home| home.key.as_deref().unwrap_or(&table.id) == tool));let installed = match (table, folded) { (Some(_), _) => Vec::new(), (None, Some(tools)) => tools, (None, None) => cotton_tools::definitions::tool_definitions(ctx).map_err(|e| e.to_string())?.definitions, };let declared = match table {Some(table) => &table.tool.as_ref().unwrap().views,None => &installed.iter().find(|definition| definition.id == tool) .ok_or_else(|| format!("No tool {tool}"))?.views, };// A view's list is headed by the tool's own name — Artifacts over// Documents' document table says "Artifacts", never the table's// plural — and its search says the same name, from set `reading`.let name = match table {Some(table) => table.tool.as_ref().unwrap().name.clone(),None => installed.iter().find(|definition| definition.id == tool).map(|definition| definition.name.clone()).unwrap_or_default(), };let search = cotton_core::rules::shell_lines::resolve("reading","list.search", &cotton_tools::presentation::line_rows(ctx.read.driver(), ctx.workspace_id), &[("name", &name.to_lowercase())], );letmut views = Vec::new();let lines = cotton_tools::presentation::line_rows(ctx.read.driver(), ctx.workspace_id);letmut table_totals: std::collections::BTreeMap<String, u64> = std::collections::BTreeMap::new();// Every tool, read once and only when a table may be another's.letmut every_tool: Option<Vec<cotton_core::definitions::ToolDefinition>> = None;// A partitioned view is one record's list, opened from its act: it// is no slip of the tool's ring.for view in declared.iter().filter(|view| view.partition.is_none()).filter(|view| only.is_none_or(|only| only == view.id)) .filter(|view| kit.as_ref().is_none_or(|kit| kit.deals_view(view.read.get("table").and_then(Value::as_str)))) {letmut args = view.read.clone(); args.insert("today".into(), json!(today)); args.insert("timezone".into(), json!(zone));// Count the selected list itself. Whole-table inventory counts can include rows// that a list omits (Email's Junk), so they are a different read. args.insert("limit".into(), json!(1));// Imported narrowed views inherit the kit's named-view line// until their definition supplies more specific wording.if !args.contains_key("empty") && ["where", "section", "query", "group", "album"].iter().any(|key| args.get(*key).is_some_and(|value| !value.is_null())) { args.insert("empty".into(), json!({"line":"empty_views.named","table":true,"view":view.label})); }// RULE (Developer Dev, 12 Nov 2026: Made for you read a table the// copy did not hold and the whole fan was unreadable): a view// naming a table this copy does not hold is dropped, logged once// a launch, and the tool's other views are drawn.letSome(source) = definitions.definitions.iter().find(|table| Some(table.id.as_str()) == args["table"].as_str()) else {if first_absent_table(tool, &view.id) { tracing::warn!(tool = %tool, view = %view.id, table = ?args["table"].as_str(), "a view names a table this copy does not hold; the fan draws the tool without it"); }continue; };// A view of the current record counts that record's rows alone. cotton_tools::mcp::handlers::tables::narrow_to_current(ctx, source, view, &mut args).map_err(|failure| failure.to_string())?;// RULE: a table's own empty words ("No documents yet…") are its// owner's to say. A view over another tool's table (Web pages// over Documents' document table) says its own line however// empty that table is, so it is never asked for the table's total.if args.get("empty").and_then(|empty| empty.get("table")).and_then(Value::as_bool) == Some(true) && key_of(source) != tool {if every_tool.is_none() { every_tool = Some(if installed.is_empty() { cotton_tools::definitions::tool_definitions(ctx).map_err(|e| e.to_string())?.definitions } else { installed.clone() }); }if !owns(tool, source, every_tool.as_deref().unwrap_or_default()) { args.get_mut("empty").and_then(Value::as_object_mut).map(|empty| empty.remove("table")); } }let native_source = crate::phone::records::settings_tables::TABLES.iter().any(|(table, _)| *table == source.id);let count = if native_source {Value::Null// Filled by that engine after releasing the file's read transaction. } else {// A view read by a book's, a song's or a film's// `on_phone` counts what this device keeps, narrowed exactly as// records.list narrows the deck's read, so the tile and the deck// count one list; its `read` goes back as declared.letmut counted = args.clone();// A sealed table's view narrowed once its rows open (Health's// Sleep) counts the rows its deck deals: this copy holds them open.ifletSome(opened) = view.opened.as_ref().filter(|opened| !opened.where_.is_empty()) {ifletSome(filter) = counted.entry("where").or_insert_with(|| json!({})).as_object_mut() { filter.extend(opened.where_.clone()); } }crate::phone::books::narrow_where(client, &mut counted).map_err(|e| e.message.clone())?;crate::phone::songs::narrow_where(client, &mut counted).map_err(|e| e.message.clone())?;crate::phone::films::narrow_where(client, &mut counted).map_err(|e| e.message.clone())?;crate::phone::meetings_app::narrow_where(client, &mut counted).map_err(|e| e.message.clone())?;crate::phone::pictures_here::narrow_where_in(ctx.read.driver(), ctx.workspace_id, &mut counted).map_err(|e| e.message.clone())?;let answer = cotton_tools::mcp::handlers::tables::list_answer_on(ctx, source, &counted, cotton_tools::mcp::handlers::tables::Total::Counted).map_err(|e| e.to_string())?;let total = answer["total"].as_u64().ok_or_else(|| format!("View {} answered no count", view.id))?;// A group deck (By person) deals one card per group: its tile// counts those, read over every row as records.list deals them.let over = view.over(source);match over.card.as_ref().and_then(|card| cotton_core::records::card::group_by(card, &over)) {Some(by) if total > 0 => json!(group_total(ctx, source, &counted, by)?), _ => json!(total), } };if !native_source && args.get("empty").and_then(|empty| empty.get("table")).and_then(Value::as_bool) == Some(true) {let total = match table_totals.get(&source.id) {Some(total) => *total,None => {// Empty-table copy asks whether any live rows exist,// including rows another view owns (Email's Junk).let whole = json!({"table": source.id, "today": today, "timezone": zone, "count_only": true});let answer = cotton_tools::mcp::handlers::tables::list_answer_on(ctx, source, whole.as_object().unwrap(), cotton_tools::mcp::handlers::tables::Total::Counted).map_err(|e| e.to_string())?;let total = answer["total"].as_u64().ok_or_else(|| format!("Table {} answered no count", source.id))?; table_totals.insert(source.id.clone(), total); total } }; args.get_mut("empty").unwrap()["total"] = json!(total); }let head = match &view.head {Some(head) if !native_source => Some(head_line(client, ctx, &definitions.definitions, source, &args, head, &lines)?),Some(_) => returnErr(format!("View {} counts a head over a table read by its engine", view.id)),None => None, }; args.remove("limit"); views.push(json!({"id":view.id,"label":view.label,"visibility":view.visibility,"count":count,"is_default":view.is_default,"face":view.face,"sort":view.sort,"slip":view.slip,"tile":view.tile,"card":view.card,"title":name,"search":search,"head":head,"picture":view.picture,"read":args,"opened":view.opened})); }// The lists stand before the view that says so, else after the last.let lists_at = declared.iter().filter(|view| view.partition.is_none()).position(|view| view.lists_before).unwrap_or(views.len());let after = views.split_off(lists_at.min(views.len()));letmut grouped = std::collections::BTreeSet::new();for id in declared.iter().filter_map(|view| view.read["table"].as_str()).filter(|id| grouped.insert(*id)) .filter(|_| only.is_none_or(|only| only.starts_with("group:"))) {letSome(table) = definitions.definitions.iter().find(|table| table.id == id && table.groups.is_some()) else { continue };// A table's groups are its owner's slips: Birthdays reading People's// person table shows its own views, never My people or Family.// The tools are read only when the table is not keyed to this one.let owned = key_of(table) == tool || {let tools = if installed.is_empty() { cotton_tools::definitions::tool_definitions(ctx).map_err(|e| e.to_string())?.definitions } else { installed.clone() }; owns(tool, table, &tools) };if !owned { continue }let args = json!({"table":table.id,"today":today,"timezone":zone});let answer = cotton_tools::mcp::handlers::tables::groups::list_groups(ctx, args.as_object().unwrap()).map_err(|e| e.to_string())?;let pictured = face_picture(table);for group in answer["groups"].as_array().into_iter().flatten() .filter(|group| only.is_none_or(|only| only.strip_prefix("group:") == group["id"].as_str())) {letmut args = json!({"table":table.id,"where":{"group":group["id"]},"today":today,"timezone":zone,"limit":1});let answer = cotton_tools::mcp::handlers::tables::list_answer_on(ctx, table, args.as_object().unwrap(), cotton_tools::mcp::handlers::tables::Total::Counted).map_err(|e| e.to_string())?;let count = answer["total"].as_u64().ok_or_else(|| "A group answered no count".to_string())?; args.as_object_mut().unwrap().remove("limit");let total = match table_totals.get(&table.id) {Some(total) => *total,None => {let whole = json!({"table":table.id,"today":today,"timezone":zone,"count_only":true});let answer = cotton_tools::mcp::handlers::tables::list_answer_on(ctx, table, whole.as_object().unwrap(), cotton_tools::mcp::handlers::tables::Total::Counted).map_err(|e| e.to_string())?;let total = answer["total"].as_u64().ok_or_else(|| format!("Table {} answered no count", table.id))?; table_totals.insert(table.id.clone(), total); total } }; args["empty"] = json!({"line":"empty_views.named","table":true,"view":group["name"],"total":total});let stack = stack_of(group, pictured);let cover = group[cotton_tools::mcp::handlers::tables::groups::PICTURE].as_str().filter(|key| !key.trim().is_empty()); views.push(json!({"id":format!("group:{}",group["id"].as_str().unwrap_or_default()),"label":group["name"],"count":count,"is_default":false,"visibility":declared.iter().find(|v|v.read["table"] == table.id).map(|v|v.visibility.as_str()).unwrap_or("owner"),"stack":stack,"cover":cover,"read":args})); } } views.extend(after);Ok(json!({"tool":tool,"views":views})) }).map_err(|reason| MethodError::new("unreadable", reason))?;letmut native_totals = std::collections::BTreeMap::new();for view in result["views"] .as_array_mut() .into_iter() .flatten() .filter(|view| view["count"].is_null()) {letmut args = view["read"].clone(); args["limit"] = json!(1);let answer = native(&args)?; view["count"] = json!(answer["total"] .as_u64() .ok_or_else(|| MethodError::new("unreadable", "A view answered no count"))?);if view["read"]["empty"]["table"] == true {let table = view["read"]["table"].as_str().unwrap_or_default().to_string();let total = match native_totals.get(&table) {Some(total) => *total,None => {let answer = native(&json!({"table":table,"count_only":true}))?;let total = answer["total"].as_u64().ok_or_else(|| MethodError::new("unreadable", "A table answered no count"))?; native_totals.insert(table, total); total } }; view["read"]["empty"]["total"] = json!(total); } }Ok(result)}/// How many of a list's first members its tile stacks.pubconst STACKED: usize = 3;/// The column a table's face draws its picture from: its card's photo place,/// else its slip's photo — a photo column either way; None for a table whose/// face carries no picture (a todo), whose lists draw the default tile.pubfn face_picture(table: &cotton_core::definitions::TableDefinition) -> Option<&str> {use cotton_core::definitions::{card::CardSlot, ColumnType};let card = table.card.as_ref().and_then(|card| card.fields.iter().find(|field| field.slot == CardSlot::Photo)).and_then(|field| field.column.as_deref()); card.or(table.slip.photo.as_deref()) .filter(|column| table.column(column).is_some_and(|column| column.column_type == ColumnType::Photo))}/// A list's stack: the pictures of its first members (`top`, in its order)/// in the face's picture column, at most [`STACKED`], a member with none/// left out.fn stack_of(group: &Value, pictured: Option<&str>) -> Vec<String> {letSome(column) = pictured else { returnVec::new() }; group["top"].as_array().into_iter().flatten() .filter_map(|record| record["data"][column].as_str().map(str::trim).filter(|key| !key.is_empty()).map(str::to_string)) .take(STACKED) .collect()}/// A view's head as it is said: the view's own read (`args`, with its day and/// zone) counted in the head's period, by the same list read that counts the/// view; with a goal one row holds above nought, said against it.fn head_line( client: &ClientController, ctx: &mut cotton_tools::mcp::dispatch::Ctx<'_>, tables: &[cotton_core::definitions::TableDefinition], source: &cotton_core::definitions::TableDefinition, args: &serde_json::Map<String, Value>, head: &cotton_core::definitions::tool_views::ViewHead, lines: &[cotton_core::rules::shell_lines::LineRow],) -> Result<String, String> {use cotton_core::definitions::tool_views::HEAD_LINES;use cotton_tools::mcp::handlers::tables::{list_answer_on, Total};ifletSome(here) = &head.here {return here_line(client, ctx, source, args, &head.line, &here.not_backed_up, lines); }let period = head.period.ok_or_else(|| "a head counts a period or this device".to_string())?;letmut counted = args.clone(); counted.remove("empty"); counted.insert("period".into(), serde_json::to_value(period).map_err(|e| e.to_string())?); counted.insert("limit".into(), json!(1));let answer = list_answer_on(ctx, source, &counted, Total::Counted).map_err(|e| e.to_string())?;let n = answer["total"].as_u64().ok_or_else(|| "a head answered no count".to_string())?.to_string();let goal = match &head.goal {None => None,Some(goal) => {let table = tables.iter().find(|table| table.id == goal.table).ok_or_else(|| format!("a head's goal names no table {}", goal.table))?;let read = json!({"table": table.id, "ids": [goal.row]});let answer = list_answer_on(ctx, table, read.as_object().unwrap(), Total::Counted).map_err(|e| e.to_string())?; answer["records"][0]["data"][&goal.column].as_f64().filter(|goal| *goal > 0.0).map(|number| (goal, number)) } };let said = match goal {Some((goal, number)) => {// A goal is a count of books: said whole, as it was kept.let number = if number.fract() == 0.0 { format!("{}", number as i64) } else { number.to_string() }; cotton_core::rules::shell_lines::resolve(HEAD_LINES, &goal.line, lines, &[("n", &n), ("goal", &number)]) }None => cotton_core::rules::shell_lines::resolve(HEAD_LINES, &head.line, lines, &[("n", &n)]), }; said.ok_or_else(|| format!("the {HEAD_LINES} set says no line {}", head.line))}/// A head of this device (`here`): the view's rows as this device answers/// them, the bytes of their files on this device, and the database's last/// pass while this phone is signed in to its object; `not_backed_up` while/// it is not, or no pass has come back yet.fn here_line( client: &ClientController, ctx: &mut cotton_tools::mcp::dispatch::Ctx<'_>, source: &cotton_core::definitions::TableDefinition, args: &serde_json::Map<String, Value>, line: &str, not_backed_up: &str, lines: &[cotton_core::rules::shell_lines::LineRow],) -> Result<String, String> {use cotton_core::definitions::tool_views::HEAD_LINES;use cotton_tools::mcp::handlers::tables::{list_answer_on, Total};letmut read = args.clone(); read.remove("empty"); read.remove("limit");crate::phone::books::narrow_where(client, &mut read).map_err(|e| e.message.clone())?;crate::phone::meetings_app::narrow_where(client, &mut read).map_err(|e| e.message.clone())?;let answer = list_answer_on(ctx, source, &read, Total::Counted).map_err(|e| e.to_string())?;let n = answer["total"].as_u64().ok_or_else(|| "a head answered no count".to_string())?;// The rows' files: the media key a kept row names (a book's `file`).let files = crate::phone::books::FILE_COLUMN;letmut keys = std::collections::BTreeSet::new();if n > 0 { read.insert("limit".into(), json!(n));let rows = list_answer_on(ctx, source, &read, Total::Counted).map_err(|e| e.to_string())?;for record in rows["records"].as_array().into_iter().flatten() {ifletSome(key) = record["data"][files].as_str().filter(|key| !key.trim().is_empty()) { keys.insert(key.to_string()); } } }let bytes: u64 = keys.iter() .filter_map(|key| crate::phone::media::local_path_of(ctx.read.driver(), key)) .filter_map(|path| std::fs::metadata(path).ok()) .map(|meta| meta.len()) .sum();let n_said = n.to_string();// A size breaks as one word: "228.9 KB" never leaves its unit on the next line.let size = cotton_core::records::page::bytes_words(bytes as f64).replace(' ', "\u{a0}");let now = client.clock().now();let synced = client.object_door().and_then(|_| client.database_sync_facts(ctx.workspace_id).0.synced_at);let said = match synced.and_then(chrono::DateTime::from_timestamp_millis) {Some(at) => {let dates = cotton_core::records::page::DateWords::of_rows(lines);let ago = dates.ago(now.signed_duration_since(at).num_seconds()).unwrap_or_else(|| {use chrono::Datelike; dates.day_month(at.timestamp().div_euclid(86_400), i64::from(now.year())) }); cotton_core::rules::shell_lines::resolve(HEAD_LINES, line, lines, &[("n", &n_said), ("size", &size), ("ago", &ago)]) }None => cotton_core::rules::shell_lines::resolve(HEAD_LINES, not_backed_up, lines, &[("n", &n_said), ("size", &size)]), }; said.ok_or_else(|| format!("the {HEAD_LINES} set says no line {line}"))}/// RULE: a table belongs to one tool — the one its tool block is keyed to, or,/// where no installed tool carries that key (Notebook's note table is keyed/// `notes`), a tool that lists it. Another tool reading the same table (an/// imported Birthdays over People's person) does not own it, so the table's/// groups never join that tool's ring (lane ringviews, 21 Oct 2026).pubfn owns( tool: &str, table: &cotton_core::definitions::TableDefinition, tools: &[cotton_core::definitions::ToolDefinition],) -> bool {let key = key_of(table); key == tool || (!tools.iter().any(|other| other.id == key) && tools.iter().any(|other| other.id == tool && other.tables.contains(&table.id)))}/// The tool a table's tool block is keyed to: its key, else its own id.fn key_of(table: &cotton_core::definitions::TableDefinition) -> &str { table.tool.as_ref().and_then(|home| home.key.as_deref()).unwrap_or(&table.id)}#[cfg(test)]#[path = "tool_views_tests.rs"]mod tests;#[cfg(test)]#[path = "views_own_cards_tests.rs"]mod views_own_cards_tests;/// A group view's card count: its rows read page by page, their distinct/// groups counted by the rule the deck deals them with.fn group_total( ctx: &mut cotton_tools::mcp::dispatch::Ctx<'_>, source: &cotton_core::definitions::TableDefinition, counted: &serde_json::Map<String, Value>, by: &str,) -> Result<usize, String> {use cotton_tools::mcp::handlers::tables::{list_answer_on, Total, MAX_PAGE_SIZE};letmut rows: Vec<serde_json::Map<String, Value>> = Vec::new();letmut page: Option<u64> = None;loop {letmut args = counted.clone(); args.insert("limit".into(), json!(MAX_PAGE_SIZE));ifletSome(page) = page { args.insert("page".into(), json!(page)); }let answer = list_answer_on(ctx, source, &args, Total::Counted).map_err(|e| e.to_string())?;let read: Vec<_> = answer["records"].as_array().into_iter().flatten().filter_map(|record| record["data"].as_object().cloned()).collect();let next = answer["next_page"].as_u64().filter(|after| Some(*after) != page && !read.is_empty()); rows.extend(read);match next {Some(after) => page = Some(after),None => break, } }Ok(cotton_core::records::card::group_count(by, &rows))}/// Whether `tool`'s view `view` naming an absent table is said for the first/// time this launch: the fan is read often, and the log says it once.fn first_absent_table(tool: &str, view: &str) -> bool {static SAID: std::sync::Mutex<std::collections::BTreeSet<String>> = std::sync::Mutex::new(std::collections::BTreeSet::new()); SAID.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).insert(format!("{tool}/{view}"))}