garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /programs/src/bin/messages.rs

raw

//! Messages: conversations with everyone in the address book. With a
//! contact who has a Pinnacle they go end-to-end encrypted, peer to peer
//! through the p2p service, with no server, and as a text to their number
//! when their device does not answer (marked so); with someone who has only a
//! phone number they go as texts (SMS) through the phone service and the
//! modem, as anyone's phone sends them. A number that texts and is in no
//! contact has a conversation of its own. The list and a conversation,
//! side by side on a wide window and one at a time on a narrow one; what
//! arrives shows at once. Built from a view (`pinnacle_view`): the field
//! brings the on-screen keyboard up, and Enter sends.
//!
//! Each message says when it was sent, in the local time zone, with a
//! line between days. A tap on a message offers to delete it from this
//! device, and a conversation can be deleted whole, after asking once
//! more: the other side keeps theirs. A field above the list finds
//! people by name.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_locale::{Date, t, tf};
use pinnacle_modem::number;
use pinnacle_rt::locale::{self, DateTime, Zone};
use pinnacle_ui::layout::messages as panes;
use pinnacle_ui::p2p::{self, Client};
use pinnacle_ui::phone::{self, Said};
use pinnacle_ui::{App, Event, theme};
use pinnacle_view::{Clipboard, IntoView, Screen, Signal, View, el, signal};

/// How it says where its named controls are (`Screen::announce`), for
/// `cargo xtask` to tap them.
const ANNOUNCE: &str = "messages: button ";

#[derive(Clone, PartialEq)]
struct Message {
    outgoing: bool,
    text: String,
    /// When it was sent or came, ms since 1970: as the service kept it,
    /// or, for one added here, as this app saw it; the order a
    /// conversation's messages and texts are put in.
    time: u64,
    /// A text the network did not take.
    failed: bool,
    /// Went as a text (SMS), not encrypted: with a contact who has a
    /// Pinnacle, when it could not be reached online.
    sms: bool,
}

/// What the services stamp a message with: the time of day in ms, or the
/// time since boot while the device does not know it.
fn now_wall() -> u64 {
    match pinnacle_rt::clock() {
        0 => pinnacle_rt::time(),
        s => s * 1000 + pinnacle_rt::time() % 1000,
    }
}

/// A message's time as the local date and time; None for one stamped
/// before the device knew the time of day (a time since boot, before
/// 2000).
fn local(ms: u64, zone: &Zone) -> Option<DateTime> {
    (ms >= 946_684_800_000).then(|| zone.civil((ms / 1000) as i64).0)
}

fn day_of(at: &DateTime) -> Date {
    Date {
        year: at.year,
        month: at.month,
        day: at.day,
    }
}

/// Today, in the zone; None while the time of day is not known.
fn today(zone: &Zone) -> Option<Date> {
    locale::now_in(zone).map(|(now, _)| day_of(&now))
}

/// The line between days: "Today", "Yesterday", or the date.
fn day_line(day: Date, today: Option<Date>) -> String {
    match today.map(|d| d.days() - day.days()) {
        Some(0) => t("Today").into(),
        Some(1) => t("Yesterday").into(),
        _ => pinnacle_locale::date(day),
    }
}

/// When the last message was, for the list: its time today, "Yesterday",
/// or the day and month.
fn when(ms: u64, zone: &Zone) -> String {
    let Some(then) = local(ms, zone) else {
        return String::new();
    };
    let day = day_of(&then);
    match today(zone).map(|d| d.days() - day.days()) {
        Some(0) => pinnacle_locale::time(then.hour, then.minute),
        Some(1) => t("Yesterday").into(),
        _ => pinnacle_locale::date_short(day),
    }
}

/// Someone to write to: by their Pinnacle when they have one, else by
/// text to their number.
#[derive(Clone)]
struct Person {
    name: String,
    key: Option<p2p::Key>,
    phones: Vec<String>,
}

impl Person {
    /// The number texts go to, for someone with no Pinnacle.
    fn texted(&self) -> Option<&str> {
        match self.key {
            Some(_) => None,
            None => self.phones.first().map(String::as_str),
        }
    }
}

fn hex(key: &p2p::Key) -> String {
    // The first 16 bytes: names on disk stay under the file system's 58.
    key[..16].iter().map(|b| alloc::format!("{b:02x}")).collect()
}

fn fingerprint(key: &p2p::Key) -> String {
    let h = hex(key);
    alloc::format!("{} {} {} {}", &h[0..4], &h[4..8], &h[8..12], &h[12..16])
}

/// A conversation's records, as both services keep them: direction (0
/// in, 1 out, 2 out but gone as a text), time (u64), length (u16), text.
/// `texts`: the phone service's, every one a text.
fn records(log: &[u8], texts: bool) -> Vec<Message> {
    let mut out = Vec::new();
    let mut at = 0;
    while at + 11 <= log.len() {
        let len = usize::from(u16::from_le_bytes([log[at + 9], log[at + 10]]));
        let Some(text) = log.get(at + 11..at + 11 + len) else {
            break;
        };
        out.push(Message {
            outgoing: log[at] != 0,
            text: String::from_utf8_lossy(text).into_owned(),
            time: u64::from_le_bytes(log[at + 1..at + 9].try_into().unwrap()),
            failed: false,
            sms: texts || log[at] == 2,
        });
        at += 11 + len;
    }
    out
}

/// The services Messages talks to: p2p always, the phone service where
/// the device has a modem. What either says while it is asked something
/// waits in its `pending`.
struct Services {
    p2p: Client,
    p2p_pending: Vec<(p2p::Key, Vec<u8>)>,
    phone: Option<phone::Client>,
    phone_pending: Vec<Vec<u8>>,
}

impl Services {
    /// The conversation with `person`, asked of the service that keeps
    /// it: an app cannot read the services' files. (A message arriving
    /// meanwhile is in the service's log, and shows when the conversation
    /// is read again.)
    fn history(&mut self, person: &Person) -> Vec<Message> {
        if let Some(key) = &person.key {
            let mut all = records(&self.p2p.history(key, &mut self.p2p_pending), false);
            // Texts from their number, which came while their Pinnacle
            // could not be reached; those sent to it are in the p2p
            // service's records already, marked.
            if let Some(phone) = &self.phone {
                for n in &person.phones {
                    let texts = records(&phone.texts(n, &mut self.phone_pending), true);
                    all.extend(texts.into_iter().filter(|m| !m.outgoing));
                }
                all.sort_by_key(|m| m.time);
            }
            return all;
        }
        match (&self.phone, person.texted()) {
            (Some(phone), Some(n)) => records(&phone.texts(n, &mut self.phone_pending), true),
            _ => Vec::new(),
        }
    }

    /// Everyone in the address book who can be written to, then the
    /// numbers that texted and are in no contact.
    fn people(&mut self) -> Vec<Person> {
        let mut people: Vec<Person> = self
            .p2p
            .book(&mut self.p2p_pending)
            .into_iter()
            .filter(|e| e.key.is_some() || !e.phones.is_empty())
            .map(|e| Person {
                name: e.name,
                key: e.key,
                phones: e.phones,
            })
            .collect();
        if let Some(phone) = &self.phone {
            for n in phone.conversations(&mut self.phone_pending) {
                if !people
                    .iter()
                    .any(|p| p.phones.iter().any(|q| number::same(q, &n)))
                {
                    people.push(Person {
                        name: n.clone(),
                        key: None,
                        phones: alloc::vec![n],
                    });
                }
            }
        }
        people
    }

    /// Forgets on this device the conversation with `person`, or one of
    /// its messages, in the service that keeps it. What they have stays.
    fn forget(&self, person: &Person, message: Option<&Message>) {
        // A text that came from a Pinnacle contact's number is kept by the
        // phone service; all else with them by the p2p service.
        let by_phone = message.is_some_and(|m| m.sms && !m.outgoing);
        let message = message.map(|m| (m.outgoing, m.time));
        if let Some(key) = &person.key {
            if !by_phone {
                self.p2p.forget(key, message);
            }
            if let Some(phone) = &self.phone
                && (by_phone || message.is_none())
            {
                for n in &person.phones {
                    phone.forget(n, message);
                }
            }
        } else if let (Some(phone), Some(n)) = (&self.phone, person.texted()) {
            phone.forget(n, message);
        }
    }
}

/// The conversation open, if one is: its messages and the draft are
/// signals, so what arrives and what is typed change only their own part.
struct Chat {
    person: Person,
    messages: Signal<Vec<Message>>,
    draft: Signal<String>,
    /// The message tapped, which offers to be deleted.
    selected: Signal<Option<usize>>,
    /// Whether it asks once more before the conversation is deleted.
    asking: Signal<bool>,
}

impl Chat {
    fn new(person: Person, history: Vec<Message>) -> Chat {
        Chat {
            person,
            messages: signal(history),
            draft: signal(String::new()),
            selected: signal(None),
            asking: signal(false),
        }
    }
}

/// What a tap asked for.
#[derive(Clone, Copy, PartialEq)]
enum Tap {
    Open(usize),
    Back,
    Send,
    /// Message `n` of the open conversation, deleted from this device.
    DeleteMessage(usize),
    /// The open conversation, deleted from this device.
    DeleteConversation,
}

/// A row of the list: the name, the last message or how they are
/// reached, and when the last message was.
struct Row {
    name: String,
    sub: String,
    when: String,
}

fn rows(services: &mut Services, people: &[Person], zone: &Zone) -> Vec<Row> {
    people
        .iter()
        .map(|person| {
            let last = services.history(person).pop();
            let at = last.as_ref().map(|m| when(m.time, zone)).unwrap_or_default();
            let sub = last
                .map(|m| m.text)
                .unwrap_or_else(|| match (&person.key, person.texted()) {
                    (Some(key), _) => fingerprint(key),
                    (None, Some(n)) => tf("SMS · {}", &[n]),
                    _ => String::new(),
                });
            Row {
                name: person.name.clone(),
                sub,
                when: at,
            }
        })
        .collect()
}

fn css_color(c: pinnacle_gfx::Color) -> String {
    format!("#{:06x}", c.0 & 0xff_ffff)
}

/// One person's row: their initial, name and last message, and when that
/// was.
fn row_view(i: usize, row: &Row, open: Option<usize>, tapped: &Signal<Option<Tap>>) -> View {
    let tapped = tapped.clone();
    let initial: String = row.name.chars().take(1).collect();
    el("button")
        .class("m-list-item")
        .attr("type", "button")
        .attr("role", "listitem")
        .attr("data-name", format!("contact-{i}"))
        .attr("aria-current", (open == Some(i)).then_some("true"))
        .attr(
            "style",
            (open == Some(i)).then_some("background: var(--m-pressed)"),
        )
        .on("click", move |_| tapped.set(Some(Tap::Open(i))))
        .child(
            el("span")
                .attr(
                    "style",
                    format!(
                        "flex: none; width: 48px; aspect-ratio: 1; border-radius: 50%; \
                         display: flex; align-items: center; justify-content: center; \
                         font-size: 21px; color: var(--m-text); background: {}",
                        css_color(theme::color_for(&row.name))
                    ),
                )
                .child(initial),
        )
        .child(
            el("span")
                .class("m-list-item__body")
                .child(el("span").class("m-list-item__title").child(row.name.clone()))
                .child(
                    el("span")
                        .class("m-list-item__sub")
                        .attr("style", "white-space: nowrap; overflow: hidden")
                        .child(row.sub.clone()),
                ),
        )
        .child(
            el("span")
                .attr("style", "flex: none; font-size: 12px; color: var(--m-text-dim)")
                .child(row.when.clone()),
        )
        .into_view()
}

/// The list: the heading, this device's key, a field that finds people
/// by name, and a row for everyone it finds.
fn list_pane(
    rows: Vec<Row>,
    me: &str,
    open: Option<usize>,
    both: bool,
    query: &Signal<String>,
    tapped: &Signal<Option<Tap>>,
) -> View {
    let width = if both {
        "width: 300px; flex: none"
    } else {
        "flex: 1"
    };
    let none = rows.is_empty();
    let (q, tapped) = (query.clone(), tapped.clone());
    // Built again as the search changes, and only the list.
    let found = move || {
        let query = q.get();
        let query = query.trim().to_lowercase();
        let mut out: Vec<View> = rows
            .iter()
            .enumerate()
            .filter(|(i, row)| open == Some(*i) || row.name.to_lowercase().contains(&query))
            .map(|(i, row)| row_view(i, row, open, &tapped))
            .collect();
        if out.is_empty() {
            let said = if none {
                t("No contacts yet")
            } else {
                t("Nobody by that name")
            };
            out.push(
                el("p")
                    .attr(
                        "style",
                        "margin: 48px 0; text-align: center; color: var(--m-text-dim)",
                    )
                    .child(said)
                    .into_view(),
            );
        }
        out
    };
    let list = el("div")
        .attr("role", "list")
        .attr("style", "display: flex; flex-direction: column; gap: 8px")
        .child(found);
    let mut pane = el("section")
        .attr(
            "style",
            format!(
                "{width}; overflow-y: auto; padding: 24px 16px; display: flex; \
                 flex-direction: column; gap: 12px"
            ),
        )
        .child(
            el("h1")
                .attr("style", "font-size: 30px; margin: 16px 0 0")
                .child(t("Messages")),
        )
        .child(
            el("p")
                .attr(
                    "style",
                    "margin: 0 0 8px; font-size: 12px; color: var(--m-text-dim); \
                     white-space: nowrap; overflow: hidden",
                )
                .child(tf("My key: {}", &[me])),
        );
    if !none {
        let (q, typed) = (query.clone(), query.clone());
        pane = pane.child(
            el("div").class("m-input").child(
                el("input")
                    .class("m-input__native")
                    .attr("type", "search")
                    .attr("placeholder", t("Search"))
                    .attr("data-name", "search")
                    .prop("value", move || q.get_untracked())
                    .on("input", move |e| typed.set(e.value.clone().unwrap_or_default())),
            ),
        );
    }
    pane.child(list).into_view()
}

/// A button that runs `tap`, named for `cargo xtask`.
fn button(label: &'static str, name: &'static str, variant: &'static str, tap: impl Fn() + 'static) -> View {
    el("button")
        .class("m-button")
        .attr("type", "button")
        .attr("data-variant", variant)
        .attr("data-name", name)
        .on("click", move |_| tap())
        .child(label)
        .into_view()
}

/// The conversation: who with and how (encrypted, or a text), Delete, the
/// messages from the oldest down to the newest, each with its time and a
/// line between days, and the field to write in.
fn chat_pane(chat: &Chat, both: bool, zone: &Zone, tapped: &Signal<Option<Tap>>) -> View {
    let mut header = el("div").attr(
        "style",
        "flex: none; display: flex; align-items: center; gap: 8px; padding: 16px; \
         background: var(--m-surface); border-bottom: 1px solid var(--m-border)",
    );
    if !both {
        let tapped = tapped.clone();
        header = header.child(
            el("button")
                .class("m-button")
                .attr("type", "button")
                .attr("data-variant", "ghost")
                .attr("data-name", "back")
                .on("click", move |_| tapped.set(Some(Tap::Back)))
                .child("←"),
        );
    }
    // How it goes: encrypted peer to peer, or as a text anyone could read
    // on the way.
    let (note, color) = match chat.person.texted() {
        None => (t("end-to-end encrypted"), "var(--m-success)"),
        Some(_) => (t("SMS · not encrypted"), "var(--m-text-dim)"),
    };
    let asking = chat.asking.clone();
    header = header
        .child(
            el("h2")
                .attr(
                    "style",
                    "flex: 1; min-width: 0; margin: 0; font-size: 21px; white-space: nowrap; overflow: hidden",
                )
                .child(chat.person.name.clone()),
        )
        .child(
            el("span")
                .attr("style", format!("font-size: 12px; color: {color}"))
                .child(note),
        )
        .child(button(t("Delete"), "delete-conversation", "ghost", move || {
            asking.set(true)
        }));
    // Asked once more, under the header, before the conversation goes.
    let (asking, ask_tapped) = (chat.asking.clone(), tapped.clone());
    let ask = move || {
        if !asking.get() {
            return Vec::new();
        }
        let (keep, delete) = (asking.clone(), ask_tapped.clone());
        alloc::vec![
            el("div")
                .attr(
                    "style",
                    "flex: none; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; \
                     padding: 8px 16px; background: var(--m-surface); \
                     border-bottom: 1px solid var(--m-border)",
                )
                .child(
                    el("span")
                        .attr("style", "flex: 1; min-width: 160px")
                        .child(t("Delete this conversation from this device? They keep theirs.")),
                )
                .child(button(t("Delete"), "delete-for-good", "danger", move || {
                    delete.set(Some(Tap::DeleteConversation))
                }))
                .child(button(t("Keep"), "keep", "ghost", move || keep.set(false)))
                .into_view(),
        ]
    };
    let (messages, selected) = (chat.messages.clone(), chat.selected.clone());
    let (zone, delete) = (zone.clone(), tapped.clone());
    // With a contact who has a Pinnacle, the header says encrypted: a
    // message that went as a text says it did not.
    let encrypted = chat.person.key.is_some();
    let bubbles = move || {
        let mut out = Vec::new();
        let today = today(&zone);
        let chosen = selected.get();
        let mut last_day: Option<Date> = None;
        for (i, m) in messages.get().into_iter().enumerate() {
            let at = local(m.time, &zone);
            // A line where a new day starts.
            if let Some(day) = at.as_ref().map(day_of)
                && last_day != Some(day)
            {
                last_day = Some(day);
                out.push(
                    el("div")
                        .attr(
                            "style",
                            "align-self: center; margin-top: 8px; font-size: 12px; color: var(--m-text-dim)",
                        )
                        .child(day_line(day, today))
                        .into_view(),
                );
            }
            let (side, fill) = match (m.outgoing, m.failed) {
                (true, false) => ("flex-end", "var(--m-accent)"),
                (true, true) => ("flex-end", "var(--m-pressed)"),
                _ => ("flex-start", "var(--m-pressed)"),
            };
            let mine = chosen == Some(i);
            let ring = if mine {
                "; border: 2px solid var(--m-text)"
            } else {
                ""
            };
            let select = selected.clone();
            // A div, not a button: a tap on it leaves the keyboard up.
            let mut bubble = el("div")
                .attr("role", "button")
                .attr("data-name", format!("message-{i}"))
                .attr(
                    "style",
                    format!(
                        "align-self: {side}; max-width: 66%; padding: 8px 12px; \
                         border-radius: 15px; background: {fill}; color: var(--m-text); \
                         display: flex; flex-direction: column; gap: 2px{ring}"
                    ),
                )
                .on("click", move |_| select.set((!mine).then_some(i)))
                .child(el("span").child(m.text));
            if let Some(at) = at {
                bubble = bubble.child(
                    el("span")
                        .attr("style", "align-self: flex-end; font-size: 12px")
                        .child(pinnacle_locale::time(at.hour, at.minute)),
                );
            }
            out.push(bubble.into_view());
            if m.sms && encrypted && !m.failed {
                out.push(
                    el("div")
                        .attr(
                            "style",
                            format!("align-self: {side}; font-size: 12px; color: var(--m-text-dim)"),
                        )
                        .child(t("SMS · not encrypted"))
                        .into_view(),
                );
            }
            if m.failed {
                out.push(
                    el("div")
                        .attr(
                            "style",
                            "align-self: flex-end; font-size: 12px; color: var(--m-danger)",
                        )
                        .child(t("Not sent"))
                        .into_view(),
                );
            }
            if mine {
                let delete = delete.clone();
                out.push(
                    el("div")
                        .attr("style", format!("align-self: {side}"))
                        .child(button(
                            t("Delete message"),
                            "delete-message",
                            "danger",
                            move || delete.set(Some(Tap::DeleteMessage(i))),
                        ))
                        .into_view(),
                );
            }
        }
        out
    };
    let draft = chat.draft.clone();
    let typed = chat.draft.clone();
    let send = tapped.clone();
    let placeholder = if chat.person.texted().is_some() {
        t("Text message")
    } else {
        t("Message")
    };
    el("section")
        .attr(
            "style",
            "flex: 1; min-width: 0; display: flex; flex-direction: column; background: var(--m-bg)",
        )
        .child(header)
        .child(ask)
        .child(
            el("div")
                .attr("data-name", "conversation")
                .attr(
                    "style",
                    "flex: 1; min-height: 0; overflow-y: auto; padding: 16px; display: flex; \
                     flex-direction: column; gap: 8px",
                )
                .child(bubbles),
        )
        .child(
            el("div")
                .attr("style", "flex: none; padding: 12px 16px 16px")
                .child(
                    el("input")
                        .class("m-input")
                        .attr("data-name", "draft")
                        .attr("enterkeyhint", "send")
                        .attr("placeholder", placeholder)
                        .attr("style", "width: 100%; border-radius: 999px")
                        .prop("value", draft)
                        .prop_bool("@focus", true)
                        .on("input", move |e| typed.set(e.value.clone().unwrap_or_default()))
                        .on("keydown", move |e| {
                            if e.key.as_deref() == Some("Enter") {
                                send.set(Some(Tap::Send));
                                e.prevent_default();
                            }
                        }),
                ),
        )
        .into_view()
}

/// What the page's controls write: the search, and what was tapped.
struct Signals {
    query: Signal<String>,
    tapped: Signal<Option<Tap>>,
}

/// The page: the list and the conversation side by side on a wide window,
/// one of them on a narrow one.
fn page(
    rows: Vec<Row>,
    me: &str,
    open: Option<usize>,
    chat: Option<&Chat>,
    both: bool,
    zone: &Zone,
    s: &Signals,
) -> View {
    let mut root = el("div").attr("style", "display: flex; height: 100vh");
    if both || chat.is_none() {
        root = root.child(list_pane(rows, me, open, both, &s.query, &s.tapped));
    }
    match chat {
        Some(chat) => root = root.child(chat_pane(chat, both, zone, &s.tapped)),
        None if both => {
            root = root.child(
                el("section")
                    .attr(
                        "style",
                        "flex: 1; display: flex; align-items: center; justify-content: center; \
                         background: var(--m-surface); color: var(--m-text-dim)",
                    )
                    .child(t("Choose a contact to write to")),
            )
        }
        None => {}
    }
    root.into_view()
}

/// Scrolls the conversation to its newest message.
fn to_latest(screen: &mut Screen) {
    let at = {
        let ui = screen.ui();
        let tree = ui.tree();
        tree.iter()
            .find(|(_, n)| n.attr("data-name") == Some("conversation"))
            .map(|(_, n)| n.placed.rect)
    };
    if let Some(r) = at {
        screen.ui().scroll(r.x + 1.0, r.y + 1.0, 0.0, 1.0e6);
    }
}

/// Takes what a signal holds, leaving it empty.
fn take<T: Clone + 'static>(s: &Signal<Option<T>>) -> Option<T> {
    let v = s.get_untracked();
    if v.is_some() {
        s.set(None);
    }
    v
}

#[unsafe(no_mangle)]
fn main(_argument: u64) -> u64 {
    let mut app = App::new("Messages");
    let mut screen = Screen::new(app.width, app.height);
    let Some(client) = Client::connect(10_000) else {
        let missing = || {
            el("p")
                .attr(
                    "style",
                    "height: 100vh; margin: 0; display: flex; align-items: center; \
                     justify-content: center; color: var(--m-text-dim)",
                )
                .child(t("The p2p service is not running"))
                .into_view()
        };
        screen.mount(missing());
        screen.draw(&mut app.canvas(), true);
        app.present_all();
        loop {
            match app.next_event(None) {
                Event::Closed => return 0,
                Event::Shown(true) | Event::Resized => {
                    screen.resize(app.width, app.height);
                    screen.draw(&mut app.canvas(), true);
                    app.present_all();
                }
                Event::Preferences => {
                    screen.restyle();
                    screen.mount(missing());
                    screen.draw(&mut app.canvas(), true);
                    app.present_all();
                }
                _ => {}
            }
        }
    };
    let mut services = Services {
        p2p: client,
        p2p_pending: Vec::new(),
        // Texts, where the device has a modem.
        phone: phone::Client::connect(),
        phone_pending: Vec::new(),
    };
    let me = services.p2p.card(&mut services.p2p_pending);
    let me = if me.len() >= 32 {
        fingerprint(&me[..32].try_into().unwrap())
    } else {
        String::new()
    };
    let mut people = services.people();
    let mut chat: Option<Chat> = None;
    let mut open: Option<usize> = None;
    let s = Signals {
        query: signal(String::new()),
        tapped: signal(None),
    };
    let tapped = s.tapped.clone();
    // The local time zone, for when messages were sent: read again when
    // the app comes to the front.
    let mut zone = locale::zone();
    let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
    // The page is built again when what it lists changes, or a
    // conversation opens or closes; within one, only its parts change.
    let mut rebuild = true;
    loop {
        if rebuild {
            let both = panes::two_panes(app.width as i32);
            let list = rows(&mut services, &people, &zone);
            screen.resize(app.width, app.height);
            screen.clear();
            screen.mount(page(list, &me, open, chat.as_ref(), both, &zone, &s));
            screen.draw(&mut app.canvas(), true);
            to_latest(&mut screen);
            screen.draw(&mut app.canvas(), true);
            app.present_all();
            screen.announce(ANNOUNCE);
            rebuild = false;
        }
        // What the phone service said while it was asked something.
        for m in core::mem::take(&mut services.phone_pending) {
            rebuild |= phone_said(&m, &mut chat, &mut people, &mut services);
        }
        let mut channels = alloc::vec![services.p2p.channel()];
        channels.extend(services.phone.as_ref().map(phone::Client::channel));
        let event = app.wait(&channels, &mut buffer, None);
        drop(channels);
        // A message in the open conversation moves it to the newest.
        let mut arrived = false;
        match event {
            Event::Channel { index: 0, len, .. } => {
                if let Some((from, payload)) = p2p::parse_received(&buffer[..len])
                    && payload.first() == Some(&p2p::TEXT)
                {
                    pinnacle_rt::println!("messages: received {} bytes", payload.len() - 1);
                    match &chat {
                        Some(chat) if chat.person.key == Some(from) => {
                            let text = String::from_utf8_lossy(&payload[1..]).into_owned();
                            chat.messages.update(|m| {
                                m.push(Message {
                                    outgoing: false,
                                    text,
                                    time: now_wall(),
                                    failed: false,
                                    sms: false,
                                })
                            });
                            arrived = true;
                        }
                        // The list's last line changes.
                        _ => rebuild = true,
                    }
                }
            }
            Event::Channel { index: 1, len, .. } => {
                let m = buffer[..len].to_vec();
                rebuild |= phone_said(&m, &mut chat, &mut people, &mut services);
                arrived = true;
            }
            Event::Shown(true) | Event::Resized => {
                zone = locale::zone();
                people = services.people();
                rebuild = true;
            }
            // The language changed: everything is said again in it.
            Event::Preferences => {
                screen.restyle();
                rebuild = true;
            }
            Event::Input(e) => {
                screen.input(&e);
                if screen.clipboard() == Some(Clipboard::Paste) {
                    app.paste();
                }
                match take(&tapped) {
                    Some(Tap::Open(i)) if i < people.len() => {
                        let person = people[i].clone();
                        let history = services.history(&person);
                        pinnacle_rt::println!("messages: opened {}", person.name);
                        chat = Some(Chat::new(person, history));
                        open = Some(i);
                        rebuild = true;
                    }
                    Some(Tap::DeleteMessage(i)) => {
                        if let Some(chat) = &chat {
                            delete_message(chat, i, &mut services);
                        }
                    }
                    Some(Tap::DeleteConversation) => {
                        if let Some(gone) = chat.take() {
                            services.forget(&gone.person, None);
                            pinnacle_rt::println!(
                                "messages: deleted the conversation with {}",
                                gone.person.name
                            );
                            // A number in no contact leaves the list with it.
                            people = services.people();
                            open = None;
                            rebuild = true;
                        }
                    }
                    Some(Tap::Back) => {
                        chat = None;
                        open = None;
                        rebuild = true;
                    }
                    Some(Tap::Send) => {
                        if let Some(chat) = &chat {
                            arrived = send(chat, &services);
                        }
                    }
                    _ => {}
                }
            }
            Event::Clipboard(text) => {
                screen.paste(&text);
            }
            Event::Closed => return 0,
            _ => {}
        }
        if !rebuild {
            let mut area = screen.draw(&mut app.canvas(), false);
            if arrived {
                to_latest(&mut screen);
                let more = screen.draw(&mut app.canvas(), false);
                area = match (area, more) {
                    (Some(a), Some(b)) => Some(a.union(&b)),
                    (a, b) => a.or(b),
                };
            }
            if let Some(area) = area {
                app.present(area);
            }
        }
    }
}

/// What the phone service said: a text that came, or how one sent went.
/// Returns whether the page is to be built again (a number new to the
/// list).
fn phone_said(m: &[u8], chat: &mut Option<Chat>, people: &mut Vec<Person>, services: &mut Services) -> bool {
    /// The messages of the conversation open, when it is with `n`: with
    /// someone texted, or with a contact who has a Pinnacle and that
    /// number (a text from them, or one to them when they were offline).
    fn open<'a>(chat: &'a Option<Chat>, n: &str) -> Option<&'a Signal<Vec<Message>>> {
        chat.as_ref()
            .filter(|c| c.person.phones.iter().any(|t| number::same(t, n)))
            .map(|c| &c.messages)
    }
    match phone::parse(m) {
        Some(Said::TextReceived { number, text }) => {
            pinnacle_rt::println!("messages: a text from {number}");
            let shown = match open(chat, &number) {
                Some(messages) => {
                    messages.update(|m| {
                        m.push(Message {
                            outgoing: false,
                            text,
                            time: now_wall(),
                            failed: false,
                            sms: true,
                        })
                    });
                    true
                }
                None => false,
            };
            // A number not in the list yet gets its row.
            if !people
                .iter()
                .any(|p| p.phones.iter().any(|q| number::same(q, &number)))
            {
                *people = services.people();
                return true;
            }
            !shown
        }
        Some(Said::TextFailed { number }) => {
            pinnacle_rt::println!("messages: the text to {number} did not go");
            if let Some(messages) = open(chat, &number) {
                messages.update(|m| {
                    if let Some(m) = m.iter_mut().rev().find(|m| m.outgoing) {
                        m.failed = true;
                    }
                });
            }
            false
        }
        Some(Said::TextSent { number }) => {
            pinnacle_rt::println!("messages: texted {number}");
            // To a contact who has a Pinnacle, the p2p service texted what
            // their device did not take: read back, it says so.
            if let Some(c) = chat.as_ref().filter(|c| c.person.key.is_some())
                && open(chat, &number).is_some()
            {
                let person = c.person.clone();
                c.messages.set(services.history(&person));
            }
            false
        }
        _ => false,
    }
}

/// Sends the draft, if there is one, and empties the field. Returns
/// whether a message was added.
fn send(open: &Chat, services: &Services) -> bool {
    let draft = open.draft.get_untracked();
    let text = draft.trim();
    if text.is_empty() {
        return false;
    }
    let mut failed = false;
    match (&open.person.key, open.person.texted(), &services.phone) {
        (Some(key), _, _) => {
            services.p2p.send_text(key, text);
            pinnacle_rt::println!("messages: sent {} bytes", text.len());
        }
        (None, Some(n), Some(phone)) => {
            phone.send_text(n, text);
            pinnacle_rt::println!("messages: texting {} bytes to {n}", text.len());
        }
        // No modem to text with.
        _ => failed = true,
    }
    let text = String::from(text);
    open.messages.update(|m| {
        m.push(Message {
            outgoing: true,
            text,
            time: now_wall(),
            failed,
            sms: open.person.key.is_none(),
        })
    });
    open.draft.set(String::new());
    true
}

/// Deletes message `i` of the open conversation from this device. The
/// service stamped it with its own time, which a message added here knows
/// only to within a moment: it is found again among those kept by its
/// direction and text, the nearest in time. One never kept (a text that
/// did not go) only leaves the page.
fn delete_message(chat: &Chat, i: usize, services: &mut Services) {
    let Some(m) = chat.messages.get_untracked().get(i).cloned() else {
        return;
    };
    if !m.failed
        && let Some(kept) = services
            .history(&chat.person)
            .into_iter()
            .filter(|k| k.outgoing == m.outgoing && k.text == m.text)
            .min_by_key(|k| k.time.abs_diff(m.time))
            .filter(|k| k.time.abs_diff(m.time) < 60_000)
    {
        services.forget(&chat.person, Some(&kept));
    }
    chat.selected.set(None);
    chat.messages.update(|ms| {
        ms.remove(i);
    });
    pinnacle_rt::println!("messages: deleted a message");
}