//! The panel the Mac's menu bar shows, decided here and only drawn by Swift (owner's direction for the panel, //! 22 Nov 2026, MAC-PANEL.md; the drawing is the lane's build/panel.html): //! //! - three screens, never mixed: `signIn` (not signed in), `step` (signed in, not yet able to open the person's //! things: the getting-in page), `working` (the sources); //! - on `working`, one headline in plain words, then one row per source: its title, one line, and whether it is //! paused. A row is a `problem` only when the person must act, and then says what; a source never set up is an //! `add`, never an error; //! - no internal words (vault, pass, cursor, pushing, hourly): every sentence is the `macpanel` lines'. use chrono::{DateTime, Utc}; use cotton_core::rules::shell_lines::{resolve, resolved}; use serde_json::{json, Value}; use crate::importer::{Need, Probe, Progress, SourceKey, WAITS_FOR_THE_VAULT}; /// A `macpanel` line. pub fn say(line: &str, fills: &[(&str, &str)]) -> String { resolve("macpanel", line, &[], fills).unwrap_or_default() } /// What the panel knows of one source. pub struct RowFacts<'a> { pub key: SourceKey, pub paused: bool, pub running: bool, pub progress: Option, pub probe: &'a Probe, pub total: i64, pub last_brought_at: Option<&'a str>, pub last_error: Option<&'a str>, /// The person let it go on the panel (WhatsApp unlinked): offered as Add, never a problem. pub let_go: bool, /// Bring everything in again is asked or under way: its page says so, until that run ends. pub again: bool, /// Mail's walk through the whole mailbox ([`crate::mail::history`]), while it has one. pub history: Option, } /// How far Mail's walk through the whole mailbox has come: counts and a day, never a word of mail. #[derive(Debug, Clone, PartialEq)] pub struct History { /// `walking`, `done` or `held`. pub state: String, /// The day of the oldest mail walked, `2015-03-04`. pub reached: Option, pub done: u64, pub total: Option, } impl History { /// Out of Mail's cursor: its first mailbox's walk. pub fn of_cursor(cursor: Option<&str>) -> Option { let parsed = crate::mail::MailCursor::parse(cursor).ok()?; let at = parsed.mailboxes.values().next()?; Some(History { state: at.history_state()?.to_string(), reached: at.history_reached.clone(), done: at.history_done.unwrap_or(0), total: at.history_total, }) } } /// `2015-03-04` → "March 2015". fn month_of(day: &str) -> Option { let date = chrono::NaiveDate::parse_from_str(day, "%Y-%m-%d").ok()?; Some(date.format("%B %Y").to_string()) } /// The Mail row's second line while its walk goes on or has stopped: "Older mail: back to March 2015 · 41,200 of /// 98,000". None once it is done. fn history_line(history: &History) -> Option { let done = grouped(history.done as i64); let total = history.total.map(|t| grouped(i64::from(t))).unwrap_or_else(|| "?".into()); match history.state.as_str() { "walking" => Some(match history.reached.as_deref().and_then(month_of) { Some(month) => say("row.history", &[("month", &month), ("done", &done), ("total", &total)]), None => say("row.history_starting", &[("total", &total)]), }), "held" => Some(say("row.history_held", &[])), _ => None, } } /// What the panel knows of the app. pub struct PanelFacts<'a> { pub signed_in: bool, /// The vault line's state: `open` once this Mac opens the person's things. pub vault: Option<&'a str>, pub phone: Option<&'a str>, pub rows: Vec>, pub now: DateTime, } /// `screen`, and on `working` the `headline` and `rows`; always the `account` words. pub fn panel(facts: &PanelFacts<'_>) -> Value { let account = json!({ "who": facts.phone.map(|phone| say("account.who", &[("phone", phone)])), "signOut": say("account.sign_out", &[]), "updates": say("account.updates", &[]), "quit": say("account.quit", &[]), "quitLine": say("account.quit_line", &[]), "quitAnyway": say("account.quit_anyway", &[]), "cancel": say("account.cancel", &[]), "launchLine": say("account.launch_line", &[]), }); if !facts.signed_in { return json!({ "screen": "signIn", "heading": say("sign_in.heading", &[]), "line": say("sign_in.line", &[]), "account": account, }); } if facts.vault != Some("open") { return json!({ "screen": "step", "account": account }); } let rows: Vec = facts.rows.iter().map(|row| row_of(row, facts.now)).collect(); json!({ "screen": "working", "headline": headline(facts, &rows), "rows": rows, "account": account, "page": page_words() }) } /// The source pages' words, as the lines hold them: `{address}`, `{mailbox}`, `{count}` and `{oldest}` are filled /// by the panel with what it shows beside them. fn page_words() -> Value { resolved("macpanel", &[]).and_then(|file| file.get("page").cloned()).unwrap_or(Value::Null) } fn key_name(key: SourceKey) -> &'static str { key.as_str() } fn what(source: SourceKey, n: i64) -> String { let name = key_name(source); say(&format!("what.{name}"), &[("n", &grouped(n))]) } /// 41380 → "41,380". fn grouped(n: i64) -> String { let digits = n.abs().to_string(); let mut out = String::new(); for (i, c) in digits.chars().enumerate() { if i > 0 && (digits.len() - i) % 3 == 0 { out.push(','); } out.push(c); } if n < 0 { format!("-{out}") } else { out } } /// "just now", "4 min ago", "2 hours ago", "yesterday". pub fn when(at: &str, now: DateTime) -> Option { let at = DateTime::parse_from_rfc3339(at).ok()?.with_timezone(&Utc); let minutes = (now - at).num_minutes().max(0); Some(if minutes < 1 { say("when.now", &[]) } else if minutes < 60 { say("when.minutes", &[("n", &minutes.to_string())]) } else if minutes < 24 * 60 { say("when.hours", &[("n", &(minutes / 60).to_string())]) } else { say("when.days", &[("n", &(minutes / (24 * 60)).to_string())]) }) } fn unreachable(error: Option<&str>) -> bool { error.is_some_and(|e| e.starts_with("the object could not be reached")) } fn row_of(row: &RowFacts<'_>, now: DateTime) -> Value { let name = key_name(row.key); let title = say(&format!("title.{name}"), &[]); let brought = || match row.last_brought_at.and_then(|at| when(at, now)) { Some(when) if row.total > 0 => say("row.brought", &[("what", &what(row.key, row.total)), ("when", &when)]), _ => say("row.nothing_yet", &[]), }; let (kind, line, act): (&str, String, Option) = if row.paused { ("paused", say("row.paused", &[]), None) } else if row.running { let sent = row.progress.map(|p| p.sent).unwrap_or(0); let line = if sent > 0 { say("row.bringing_n", &[("what", &what(row.key, sent))]) } else { say("row.bringing", &[]) }; ("bringing", line, None) } else if !row.probe.ready { let never = row.total == 0 || row.let_go; match &row.probe.need { // A first link under way (or one the person backed out of) is still an offer: only a number that was // linked before and must be linked again is a problem. Some(Need::Pair { by, .. }) if by.is_some() && (row.let_go || never) => ("add", say(&format!("offer.{name}"), &[]), Some(say("act.add", &[]))), Some(Need::Pair { by, .. }) if by.is_some() => ("problem", say("row.linking", &[]), Some(say("act.link", &[]))), Some(Need::Pair { .. }) if row.let_go || (never && row.probe.detail.is_none()) => ("add", say(&format!("offer.{name}"), &[]), Some(say("act.add", &[]))), Some(Need::Pair { .. }) => ("problem", say("row.relink", &[]), Some(say("act.link", &[]))), Some(Need::Credentials) if row.probe.detail.is_none() => ("add", say(&format!("offer.{name}"), &[]), Some(say("act.add", &[]))), Some(Need::Credentials) => ("problem", say("row.password", &[]), Some(say("act.fix", &[]))), Some(Need::FullDiskAccess) if never => ("add", say(&format!("offer.{name}"), &[]), Some(say("act.add", &[]))), Some(Need::FullDiskAccess) => ("problem", say("row.disk_again", &[]), Some(say("act.allow", &[]))), None => ("unavailable", say("row.unavailable", &[]), None), } } else if row.last_error.is_some_and(|e| e != WAITS_FOR_THE_VAULT && !unreachable(Some(e))) { // A refusal the app retries by itself: said, never a problem the person must solve. ("ok", say("row.retrying", &[]), None) } else { ("ok", brought(), None) }; let history = row.history.as_ref().and_then(history_line); json!({ "source": name, "title": title, "kind": kind, "line": line, "act": act, "paused": row.paused, "again": row.again, "history": history }) } fn headline(facts: &PanelFacts<'_>, rows: &[Value]) -> Value { let problems: Vec<(&Value, &RowFacts<'_>)> = rows.iter().zip(&facts.rows).filter(|(r, _)| r["kind"] == "problem").collect(); if let Some((first, facts_of)) = problems.first() { let line = if problems.len() == 1 { say("headline.needs", &[("title", first["title"].as_str().unwrap_or(""))]) } else { say("headline.needs_many", &[("n", &problems.len().to_string())]) }; // What happened, as the source said it, and that nothing is lost; the row says what to do. let safe = say("headline.safe", &[]); let sub = match facts_of.probe.detail.as_deref().filter(|d| !d.is_empty()) { Some(detail) if problems.len() == 1 => format!("{detail} {safe}"), _ => safe, }; return json!({ "line": line, "sub": sub, "needs": true }); } if facts.rows.iter().any(|r| !r.paused && unreachable(r.last_error)) { return json!({ "line": say("headline.offline", &[]), "sub": say("headline.offline_line", &[]), "needs": false }); } if let Some(running) = facts.rows.iter().find(|r| r.running && !r.paused) { let progress = running.progress.unwrap_or_default(); let name = key_name(running.key); let plural = say(&format!("plural.{name}"), &[]); let line = match progress.total { Some(total) if total > 0 => say("headline.bringing", &[("done", &grouped(progress.sent)), ("total", &grouped(total)), ("what", &plural)]), _ => say("headline.bringing_some", &[("what", &plural)]), }; let mut answer = json!({ "line": line, "needs": false }); if let Some(total) = progress.total.filter(|t| *t > 0) { answer["progress"] = json!({ "done": progress.sent, "total": total }); } return answer; } if rows.iter().all(|r| r["kind"] == "add" || r["kind"] == "unavailable") { return json!({ "line": say("headline.choose", &[]), "sub": say("headline.choose_line", &[]), "needs": false }); } let last = facts.rows.iter().filter_map(|r| r.last_brought_at).max(); json!({ "line": say("headline.up_to_date", &[]), "sub": last.and_then(|at| when(at, facts.now)).map(|when| say("headline.last", &[("when", &when)])), "needs": false, }) } #[cfg(test)] #[path = "panel_tests.rs"] mod tests;