Cotton code
664 lines · 31.4 KB · RustRaw
//! Calls in Cotton Chat (owner, 19 Nov 2026: Chat gets calls; Cotton//! Calling retires): the header's call buttons, the line a call leaves in//! its conversation, the Calls tile's rows and the call screen, as types and//! pure rules. The call itself is Calling's engine//! ([`crate::calling::machine`]): one call per device, its phases and//! effects decided there; these rules only say it. Every word is the kit's//! (`chat` set, `app.call.*` and `app.calls.*`).//!//! A call's facts are kept where the rest of Chat reads them: the `call` row//! (`cotton_call_log`, Calling's, one per room and side) and, where the call//! has a conversation, one centred line in it (a message row with//! `meta.system` and `meta.call` = [`CallFacts`]), so the thread's pages,//! the list's last line, search and export carry it as they carry every//! other line.use serde::{Deserialize, Serialize};use super::list::say;use super::shapes::Picture;use crate::calling::machine::{Call, Direction, Phase};use crate::calling::wire::{EndReason, Mode};use crate::rules::shell_lines::LineSet;/// How long the ended screen stands before it goes, in milliseconds.pub const ENDED_FOR_MS: u64 = 2_000;/// The Calls tile's page.pub const PAGE: usize = 80;/// What a finished call was, as its line and its row say it.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct CallFacts {    /// The room: the line's and the row's id are made from it.    pub room: String,    /// `in` (rang here) or `out` (placed here).    pub direction: String,    pub video: bool,    /// `answered | missed | cancelled | failed` (the `call` table's words).    pub outcome: String,    /// The engine's end reason (`declined`, `no_answer`, `busy`, …).    pub reason: String,    pub duration_s: i64,    /// Rang here and nobody here answered or declined it.    pub missed: bool,    /// A group call.    #[serde(default)]    pub group: bool,}impl CallFacts {    /// The facts of an ended call.    pub fn of(call: &Call) -> Option<CallFacts> {        if call.phase != Phase::Ended {            return None;        }        let room = call.room.clone()?;        let ended = call.ended_at.unwrap_or(call.phase_at);        let reason = call.reason.unwrap_or(EndReason::Failed);        Some(CallFacts {            room,            direction: if call.direction == Direction::In { "in" } else { "out" }.into(),            video: call.video,            outcome: crate::calling::history::outcome(call).into(),            reason: reason.as_str().into(),            duration_s: call.duration_s(ended),            missed: call.direction == Direction::In && call.live_at.is_none() && matches!(reason, EndReason::Missed | EndReason::Cancelled | EndReason::NoAnswer),            group: call.mode == Mode::Sfu,        })    }    pub fn incoming(&self) -> bool {        self.direction == "in"    }}/// A call's length as a clock: `0:42`, `12:05`, `1:02:09`.pub fn length(seconds: i64) -> String {    let s = seconds.max(0);    if s >= 3600 {        format!("{}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)    } else {        format!("{}:{:02}", s / 60, s % 60)    }}/// The words of a call's line: "Missed video call", "Voice call · 3:12",/// "Voice call · No answer", "Declined voice call", "Cancelled video call".pub fn line(lines: &LineSet, facts: &CallFacts) -> String {    let video = facts.video;    let pick = |voice: &str, seen: &str| if video { say(lines, seen, &[]) } else { say(lines, voice, &[]) };    let kind = pick("app.call.kind.voice", "app.call.kind.video");    let with = |detail: String| say(lines, "app.call.line", &[("kind", &kind), ("detail", &detail)]);    if facts.outcome == "answered" {        return with(length(facts.duration_s));    }    if facts.missed {        return pick("app.call.missed.voice", "app.call.missed.video");    }    match (facts.incoming(), facts.reason.as_str()) {        (true, "declined") => pick("app.call.declined.voice", "app.call.declined.video"),        (false, "cancelled" | "hung_up") => pick("app.call.cancelled.voice", "app.call.cancelled.video"),        (false, "declined") => with(say(lines, "app.call.why.declined", &[])),        (false, "busy") => with(say(lines, "app.call.why.busy", &[])),        (false, "no_answer" | "remote_hung_up") => with(say(lines, "app.call.why.no_answer", &[])),        _ => with(say(lines, "app.call.why.failed", &[])),    }}/// A call an export wrote into a chat as a line of its own, under the/// caller's name (WhatsApp on iPhone: "Voice call, 41 sec", "Missed video/// call, Tap to call back", each word behind invisible direction marks):/// its centred line, in the kit's words with the export's own detail./// `None` for anything else. Only an imported row is asked: a person who/// types "Video call" in a Cotton chat wrote words.pub fn imported_line(lines: &LineSet, body: &str) -> Option<String> {    let plain: String = body.chars().filter(|c| !matches!(c, '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' | '\u{feff}')).collect();    let plain = plain.trim();    if plain.is_empty() || plain.contains('\n') || plain.chars().count() > 80 {        return None;    }    let (what, detail) = match plain.split_once([',', '\u{b7}']) {        Some((what, detail)) => (what.trim(), detail.trim()),        None => (plain, ""),    };    let what = what.to_lowercase();    let words: Vec<&str> = what.split_whitespace().collect();    let (missed, rest) = match words.split_first() {        Some((&("missed" | "silenced"), rest)) => (true, rest),        _ => (false, words.as_slice()),    };    let rest = rest.strip_prefix(&["group"]).unwrap_or(rest);    let video = match rest {        ["voice", "call"] => false,        ["video", "call"] => true,        _ => return None,    };    let pick = |voice: &str, seen: &str| if video { say(lines, seen, &[]) } else { say(lines, voice, &[]) };    if missed {        return Some(pick("app.call.missed.voice", "app.call.missed.video"));    }    let kind = pick("app.call.kind.voice", "app.call.kind.video");    let callback = ["tap to call back", "click to call back"].contains(&detail.to_lowercase().as_str());    Some(if detail.is_empty() || callback { kind } else { say(lines, "app.call.line", &[("kind", &kind), ("detail", detail)]) })}// ── the header ──────────────────────────────────────────────────────────/// One of the header's call buttons: tap it and `chat.call {thread, video}`.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct CallButton {    pub video: bool,    pub label: String,}/// The header's call and video buttons, in that order. Present on a Cotton/// conversation alone (an imported WhatsApp or SMS thread offers no call),/// once it is not a stranger's unanswered request; a group's ring everyone in it.pub fn buttons(lines: &LineSet, cotton: bool, request_pending: bool, group: bool, callable: usize) -> Option<Vec<CallButton>> {    if !cotton || request_pending || callable == 0 {        return None;    }    let (voice, video) = if group { ("app.call.button.group_voice", "app.call.button.group_video") } else { ("app.call.button.voice", "app.call.button.video") };    Some(vec![CallButton { video: false, label: say(lines, voice, &[]) }, CallButton { video: true, label: say(lines, video, &[]) }])}/// What a call's line in a thread adds to its event item: tap it to call back.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ThreadCall {    /// The `call` row: `chat.call {call}` calls back.    pub call: String,    pub video: bool,    pub missed: bool,    pub incoming: bool,    /// The line's clock.    pub time: String,    /// Words for the tap ("Call back").    pub back: String,}// ── the Calls tile ──────────────────────────────────────────────────────/// `chat.calls {after?}`: recent calls, newest first.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct CallsAnswer {    pub rows: Vec<CallRow>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub next: Option<String>,    pub words: CallsWords,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct CallsWords {    pub title: String,    pub empty: String,    pub back: String,    /// The button at the top of Calls that starts a recording (DECISIONS "Recordings").    #[serde(default)]    pub record: String,    /// Its second choice: bring in an audio file as a recording.    #[serde(default)]    pub import: String,}/// One call in the Calls tile. Tap it: `chat.call {call: <call>}` rings them/// again, the same kind of call.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct CallRow {    pub call: String,    pub name: String,    pub picture: Picture,    /// The conversation it belongs to, when there is one here.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub thread: Option<String>,    pub incoming: bool,    pub video: bool,    /// Drawn marked (the missed colour).    pub missed: bool,    pub group: bool,    /// "Missed video call", "Voice call · 3:12".    pub line: String,    /// "10:42", "Yesterday", "Mon".    pub when: String,    /// `call`, or `recording` (a recording listed with the calls: `call` is then the recording's id).    #[serde(default = "call_kind")]    pub kind: String,    /// The heading of the day the row is under ("Today", "Yesterday", "Tue 18 Nov"): draw one where it changes.    #[serde(default)]    pub day: String,    /// The notes this person took on the call, or the recording a `recording` row opens.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub recording: Option<String>,    /// A recording's mark: `recording`, `memo`, `import` or `notes`.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub mark: Option<String>,}fn call_kind() -> String {    "call".to_string()}// ── the call screen ─────────────────────────────────────────────────────/// `chat.callScreen {speaker?}`: the call screen, the ring and the/// returning bar, as drawn now. Ask again after every `calls.*` answer.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct CallScreen {    /// A call is under way, or has just ended and its screen still stands (`endedFor`).    pub shown: bool,    /// The engine's phase (`dialling`, `ringing_out`, `ringing_in`, `connecting`, `live`, `reconnecting`, `ended`).    pub phase: String,    pub name: String,    pub picture: Picture,    /// "Calling…", "Ringing…", "Connecting…", the end's words; absent while live (draw `liveAt`'s clock).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub status: Option<String>,    /// While live: milliseconds since the epoch the call went live; draw the    /// elapsed time as [`length`] does (m:ss, h:mm:ss), once a second.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub live_at: Option<i64>,    /// A video call: the other person full screen, your own picture small in a corner.    pub video: bool,    /// Your own camera is on (draw the small picture).    pub camera: bool,    /// The buttons, in order: `mute`, `speaker`, `video` (a video call only), `flip` (with the camera on), `end`.    pub controls: Vec<Control>,    /// A ring here: Answer and Decline (`calls.answer`, `calls.decline`).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub ring: Option<Ring>,    /// The bar Chat shows while a call goes on behind it: tap it to come back.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub bar: Option<String>,    /// How long the ended screen stands, then goes.    pub ended_for: u64,    /// The conversation the call belongs to.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub thread: Option<String>,    /// Where the sound goes, when the phone offers more than its own earpiece    /// and loudspeaker (a Bluetooth device, headphones): the `speaker`    /// control is then `audio`, labelled with the route in use, and tapping it    /// offers these; the one chosen is the phone's to switch to, and    /// `chat.callScreen {route}` says it back. Empty: the plain speaker toggle.    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub routes: Vec<RouteChoice>,    /// A group call (through the SFU): draw `tiles` in `grid`, say `privacy`.    #[serde(default, skip_serializing_if = "std::ops::Not::not")]    pub group: bool,    /// A group call's people, the others first in the room's order and you last: one tile each.    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub tiles: Vec<Tile>,    /// How the tiles stand on a phone held upright.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub grid: Option<Grid>,    /// What protects the call, said plainly under the name: a group call is "Protected in transit", never end to end.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub privacy: Option<String>,    /// The longer words a tap on `privacy` shows.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub privacy_detail: Option<String>,    /// The mark every phone in the call draws while anyone takes notes (CONTRACT.md "Take notes").    #[serde(default, skip_serializing_if = "Option::is_none")]    pub notes: Option<NotesMark>,    /// Take notes refused or stopped because someone cannot show the mark: "Notes can't be taken: Asha's Comms needs    /// updating." Said on the note-taker's screen until notes are asked again.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub notice: Option<String>,}/// Take notes' mark: who takes them, and the line to draw with the dot.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct NotesMark {    pub by: Vec<NotesBy>,    /// "Asha is taking notes", "You are taking notes", "Asha, Ravi are taking notes".    pub line: String,    pub mark: bool,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct NotesBy {    pub member: String,    pub name: String,}/// One person's tile in a group call.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Tile {    /// The room's member id: a pulled track names it (`pull_tracks`, `apply_remote_sdp`'s `tracks`).    pub member: String,    pub name: String,    pub picture: Picture,    /// This phone's own tile (draw the local camera in it).    pub you: bool,    /// In the call now; else `state` says where they stand ("Ringing…", "Left").    pub joined: bool,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub state: Option<String>,    /// Talking now: ring the tile.    pub speaking: bool,    /// Their microphone is off: draw the mark.    pub muted: bool,    /// Their camera is on: draw their video, else the picture.    pub camera: bool,    /// Taking notes.    pub notes: bool,}/// The tiles' columns and rows: 2 stacked; 3 or 4 as two by two; 5 or 6 as two by three; 7 or 8 as two by four; 9 as three by three.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pub struct Grid {    pub columns: u8,    pub rows: u8,}/// The grid for `n` tiles.pub fn grid(n: usize) -> Grid {    match n {        0 | 1 => Grid { columns: 1, rows: 1 },        2 => Grid { columns: 1, rows: 2 },        3 | 4 => Grid { columns: 2, rows: 2 },        5 | 6 => Grid { columns: 2, rows: 3 },        7 | 8 => Grid { columns: 2, rows: 4 },        _ => Grid { columns: 3, rows: 3 },    }}/// Who a member is on this phone: their name and picture.pub type Named<'a> = &'a dyn Fn(&crate::calling::wire::Member) -> (String, Picture);/// A group call's tiles: everyone in it or still being rung, the others first, you last.pub fn tiles(lines: &LineSet, call: &Call, named: Named<'_>) -> Vec<Tile> {    use crate::calling::wire::MemberState as S;    let me = call.me.as_deref();    let mut others = Vec::new();    let mut own = None;    for m in &call.members {        let you = Some(m.id.as_str()) == me;        let state = match m.state {            S::Joined => None,            S::Invited | S::Ringing => Some(say(lines, "app.call.phase.ringing", &[])),            // Out of the call: no tile, but for this phone's own while it still stands.            _ if !you => continue,            _ => None,        };        let (name, picture) = if you { (say(lines, "app.call.group.you", &[]), named(m).1) } else { named(m) };        let tile = Tile {            member: m.id.clone(),            name,            picture,            you,            joined: m.state == S::Joined || you,            state,            speaking: if you { call.own.speaking } else { m.speaking },            muted: if you { !call.own.audio } else { m.state == S::Joined && !m.audio },            camera: if you { call.own.video } else { m.state == S::Joined && m.video },            notes: call.notes.iter().any(|n| n == &m.id),        };        if you {            own = Some(tile);        } else {            others.push(tile);        }    }    // Before the room's roster, this phone's own tile still stands.    let own = own.or_else(|| {        let me = me.unwrap_or("caller").to_string();        let held = crate::calling::wire::Member { id: me.clone(), number: None, state: S::Joined, audio: call.own.audio, video: call.own.video, speaking: false, notes: false, can: Vec::new(), person: None, name: None };        Some(Tile { member: me, name: say(lines, "app.call.group.you", &[]), picture: named(&held).1, you: true, joined: true, state: None, speaking: call.own.speaking, muted: !call.own.audio, camera: call.own.video, notes: false })    });    others.extend(own);    others}/// The mark while anyone takes notes: "Asha is taking notes", "You are taking notes", "Asha, Ravi are taking notes".pub fn notes_mark(lines: &LineSet, tiles: &[Tile]) -> Option<NotesMark> {    let by: Vec<NotesBy> = tiles.iter().filter(|t| t.notes).map(|t| NotesBy { member: t.member.clone(), name: t.name.clone() }).collect();    let line = match by.as_slice() {        [] => return None,        [one] if tiles.iter().any(|t| t.you && t.member == one.member) => say(lines, "app.call.notes.you", &[]),        [one] => say(lines, "app.call.notes.one", &[("name", &one.name)]),        many => say(lines, "app.call.notes.many", &[("names", &many.iter().map(|b| b.name.as_str()).collect::<Vec<_>>().join(", "))]),    };    Some(NotesMark { by, line, mark: true })}/// The line a group's call leaves in the group while it goes on: "Asha started a voice call", "You started a video call".pub fn group_started(lines: &LineSet, by: Option<&str>, video: bool) -> String {    let kind = if video { "video" } else { "voice" };    match by {        Some(name) => say(lines, &format!("app.call.group.started.{kind}"), &[("name", name)]),        None => say(lines, &format!("app.call.group.mine.{kind}"), &[]),    }}/// One audio route the phone reports for a call: `kind` is `phone` (the/// earpiece), `speaker`, `wired` or `bluetooth`; `name` a Bluetooth device's own.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct AudioRoute {    pub id: String,    pub kind: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub name: Option<String>,}/// One route as the screen offers it: `id` back to the phone, the words, and whether it is in use.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct RouteChoice {    pub id: String,    pub kind: String,    pub label: String,    pub on: bool,}/// A route's words: a Bluetooth device by its own name, the rest by kind.pub fn route_label(lines: &LineSet, route: &AudioRoute) -> String {    match route.kind.as_str() {        "bluetooth" => route.name.clone().filter(|n| !n.trim().is_empty()).unwrap_or_else(|| say(lines, "app.call.route.bluetooth", &[])),        "wired" => say(lines, "app.call.route.wired", &[]),        "speaker" => say(lines, "app.call.route.speaker", &[]),        _ => say(lines, "app.call.route.phone", &[]),    }}/// One button. `id`: `mute` → `calls.mute {audio: !on…}`, `speaker` → the/// phone's own loudspeaker, `video` → `calls.mute {video: !on…}`, `flip` →/// the phone's other camera, `end` → `calls.end`.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Control {    pub id: String,    pub label: String,    /// Lit: muted, the speaker on, the camera on.    pub on: bool,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Ring {    /// "Cotton voice call", "Cotton video call".    pub title: String,    pub answer: String,    pub decline: String,}/// The screen for `call` named `name`, at `now` (ms), the speaker as the phone has it.pub fn screen(lines: &LineSet, call: &Call, name: &str, picture: Picture, speaker: bool, now: i64) -> CallScreen {    routed(lines, call, name, picture, speaker, &[], None, now)}/// [`screen`] with the phone's audio routes and the one in use: with a/// Bluetooth device or headphones among them, `speaker` becomes `audio`.#[allow(clippy::too_many_arguments)]pub fn routed(lines: &LineSet, call: &Call, name: &str, picture: Picture, speaker: bool, routes: &[AudioRoute], current: Option<&str>, now: i64) -> CallScreen {    let ended_recently = call.phase == Phase::Ended && call.ended_at.is_some_and(|at| now - at < ENDED_FOR_MS as i64);    let shown = call.is_active() || ended_recently;    let phase = serde_json::to_value(call.phase).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();    let status = match call.phase {        Phase::Idle | Phase::Live => None,        Phase::Dialling => Some(say(lines, "app.call.phase.calling", &[])),        Phase::RingingOut => Some(say(lines, "app.call.phase.ringing", &[])),        Phase::RingingIn => Some(if call.video { say(lines, "app.call.ring.video", &[]) } else { say(lines, "app.call.ring.voice", &[]) }),        Phase::Connecting => Some(say(lines, "app.call.phase.connecting", &[])),        Phase::Reconnecting => Some(say(lines, "app.call.phase.reconnecting", &[])),        Phase::Ended => Some(ended_words(lines, call)),    };    let up = call.is_active() && call.phase != Phase::RingingIn;    let mut controls = Vec::new();    if up {        let muted = !call.own.audio;        controls.push(Control { id: "mute".into(), label: say(lines, if muted { "app.call.control.unmute" } else { "app.call.control.mute" }, &[]), on: muted });        let more = routes.iter().any(|r| r.kind == "bluetooth" || r.kind == "wired");        if more {            let using = routes.iter().find(|r| Some(r.id.as_str()) == current).or_else(|| routes.iter().find(|r| r.kind == if speaker { "speaker" } else { "phone" }));            let label = using.map_or_else(|| say(lines, "app.call.route.choose", &[]), |r| route_label(lines, r));            controls.push(Control { id: "audio".into(), label, on: using.is_some_and(|r| r.kind != "phone") });        } else {            controls.push(Control { id: "speaker".into(), label: say(lines, "app.call.control.speaker", &[]), on: speaker });        }        // The camera is offered only in a video call: in a voice call the call machine turns no camera on (a voice        // call carries no video to turn on), and the button did nothing on the emulators (21 Nov 2026).        if call.video {            controls.push(Control { id: "video".into(), label: say(lines, "app.call.control.video", &[]), on: call.own.video });        }        if call.own.video {            controls.push(Control { id: "flip".into(), label: say(lines, "app.call.control.flip", &[]), on: false });        }        // Take notes (CONTRACT "Take notes"): offered once the call is live and everyone else in it can show the        // mark; lit while this phone takes them.        if call.phase == Phase::Live && notes_offered(call) {            let mine = call.me.as_ref().is_some_and(|me| call.notes.contains(me));            controls.push(Control { id: "notes".into(), label: say(lines, if mine { "app.call.control.notes_stop" } else { "app.call.control.notes" }, &[]), on: mine });        }        // In a group the red button leaves: the others go on.        let end = if call.mode == Mode::Sfu { "app.call.control.leave" } else { "app.call.control.end" };        controls.push(Control { id: "end".into(), label: say(lines, end, &[]), on: false });    }    let ring = (call.phase == Phase::RingingIn).then(|| Ring {        title: if call.video { say(lines, "app.call.ring.video", &[]) } else { say(lines, "app.call.ring.voice", &[]) },        answer: say(lines, "app.call.ring.answer", &[]),        decline: say(lines, "app.call.ring.decline", &[]),    });    CallScreen {        shown,        phase,        name: name.to_string(),        picture,        status,        live_at: if call.phase == Phase::Live { call.live_at } else { None },        video: call.video,        camera: up && call.own.video,        controls,        ring,        bar: up.then(|| say(lines, "app.call.bar", &[("name", name)])),        ended_for: ENDED_FOR_MS,        thread: call.thread.clone(),        routes: if up && routes.iter().any(|r| r.kind == "bluetooth" || r.kind == "wired") {            let using = routes.iter().find(|r| Some(r.id.as_str()) == current).map(|r| r.id.clone()).or_else(|| routes.iter().find(|r| r.kind == if speaker { "speaker" } else { "phone" }).map(|r| r.id.clone()));            routes.iter().map(|r| RouteChoice { id: r.id.clone(), kind: r.kind.clone(), label: route_label(lines, r), on: using.as_deref() == Some(r.id.as_str()) }).collect()        } else {            Vec::new()        },        group: call.mode == Mode::Sfu,        tiles: Vec::new(),        grid: None,        privacy: (call.mode == Mode::Sfu).then(|| say(lines, "app.call.group.privacy", &[])),        privacy_detail: (call.mode == Mode::Sfu).then(|| say(lines, "app.call.group.privacy_detail", &[])),        notes: (call.phase != Phase::RingingIn && up).then(|| pair_mark(lines, call, name)).flatten(),        notice: up.then(|| notes_notice(lines, call, &|_| name.to_string())).flatten(),    }}/// When notes stop, a line says so (no dot) until notes start again or the call ends: "You stopped taking notes",/// "<name> stopped taking notes". [named] names a member (None: this phone).fn stopped_mark(lines: &LineSet, call: &Call, named: impl Fn(&str) -> Option<String>) -> Option<NotesMark> {    let who = call.notes_stopped.as_deref()?;    let (name, line) = match named(who) {        None => (say(lines, "app.call.group.you", &[]), say(lines, "app.call.notes.stopped_you", &[])),        Some(name) => (name.clone(), say(lines, "app.call.notes.stopped_one", &[("name", &name)])),    };    Some(NotesMark { by: vec![NotesBy { member: who.to_string(), name }], line, mark: false })}/// The words for Take notes refused or stopped, each member named by `name_of` (their member id).pub fn notes_notice(lines: &LineSet, call: &Call, name_of: &dyn Fn(&str) -> String) -> Option<String> {    use crate::calling::machine::NotesNotice;    Some(match call.notes_notice.as_ref()? {        NotesNotice::Refused { members } => match members.as_slice() {            [] | [_] => say(lines, "app.call.notes.refused_one", &[("name", &members.first().map(|m| name_of(m)).unwrap_or_default())]),            many => say(lines, "app.call.notes.refused_many", &[("names", &many.iter().map(|m| name_of(m)).collect::<Vec<_>>().join(", "))]),        },        NotesNotice::Stopped { member } => say(lines, "app.call.notes.stopped_cannot_show", &[("name", &name_of(member))]),    })}/// Whether Take notes is offered: someone else is in the call, and everyone else in it says it can show the mark.fn notes_offered(call: &Call) -> bool {    let others: Vec<_> = call.members.iter().filter(|m| Some(&m.id) != call.me.as_ref() && m.state == crate::calling::wire::MemberState::Joined).collect();    !others.is_empty() && others.iter().all(|m| m.can.iter().any(|c| c == "notes"))}/// The mark on a call of two: "You are taking notes", or "<name> is taking notes" (a group's is [`notes_mark`]).fn pair_mark(lines: &LineSet, call: &Call, name: &str) -> Option<NotesMark> {    if call.notes.is_empty() {        return stopped_mark(lines, call, |id| if Some(id) == call.me.as_deref() { None } else { Some(name.to_string()) });    }    let by: Vec<NotesBy> = call        .notes        .iter()        .map(|id| NotesBy { member: id.clone(), name: if Some(id) == call.me.as_ref() { say(lines, "app.call.group.you", &[]) } else { name.to_string() } })        .collect();    let line = match by.as_slice() {        [one] if Some(&one.member) == call.me.as_ref() => say(lines, "app.call.notes.you", &[]),        [one] => say(lines, "app.call.notes.one", &[("name", &one.name)]),        many => say(lines, "app.call.notes.many", &[("names", &many.iter().map(|b| b.name.as_str()).collect::<Vec<_>>().join(", "))]),    };    Some(NotesMark { by, line, mark: true })}/// [`routed`] for a group call, its tiles named on this phone: the grid, and the notes mark.#[allow(clippy::too_many_arguments)]pub fn group_screen(lines: &LineSet, call: &Call, name: &str, picture: Picture, speaker: bool, routes: &[AudioRoute], current: Option<&str>, now: i64, named: Named<'_>) -> CallScreen {    let mut screen = routed(lines, call, name, picture, speaker, routes, current, now);    if call.mode == Mode::Sfu && call.phase != Phase::RingingIn {        screen.tiles = tiles(lines, call, named);        screen.grid = Some(grid(screen.tiles.len()));        screen.notes = notes_mark(lines, &screen.tiles).or_else(|| {            let tiles = screen.tiles.clone();            stopped_mark(lines, call, |id| tiles.iter().find(|t| t.member == id && !t.you).map(|t| t.name.clone()))        });        let name_of = |id: &str| call.members.iter().find(|m| m.id == id).map_or_else(String::new, |m| named(m).0);        if screen.notice.is_some() { screen.notice = notes_notice(lines, call, &name_of); }    }    screen}/// What the ended screen says.pub fn ended_words(lines: &LineSet, call: &Call) -> String {    let key = match call.reason {        Some(EndReason::Declined) if call.direction == Direction::Out => "app.call.ended.declined",        Some(EndReason::Busy) => "app.call.ended.busy",        Some(EndReason::NoAnswer) => "app.call.ended.no_answer",        Some(EndReason::Failed) => "app.call.ended.failed",        Some(EndReason::Lost) => "app.call.ended.lost",        Some(EndReason::TooManyCalls) => "app.call.ended.too_many",        Some(EndReason::UnreachableNetwork) => "app.call.ended.offline",        Some(EndReason::AnsweredElsewhere) => "app.call.ended.answered_elsewhere",        Some(EndReason::DeclinedElsewhere) => "app.call.ended.declined_elsewhere",        _ => "app.call.ended.ended",    };    say(lines, key, &[])}#[cfg(test)]#[path = "calls_tests.rs"]mod tests;