garage44.eu/jeroen/pinnacle

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

.. /programs/src/bin/settings.rs

raw

//! Settings: this device's name, its screen (turned from here as by its
//! orientation sensor) and its brightness (a slider, where the kernel can
//! set it: a laptop's panel), the sound's volume (a slider the mixer follows), its screen lock (the password that also opens the data), the network, its
//! disks and its system, and on pages of their own the network (online or
//! not, over which connection, and its switch), the hardware the
//! kernel found and which driver took each, which contacts may run
//! commands on this device from their terminal (`remote`), the Wi-Fi
//! networks nearby, joined with a password (`wifi`), updates (looked for
//! or not, installed by themselves or told: `updates`), and the agent:
//! which model it asks, its key, and every prompt that was sent. A system program, not an installed app: it reads
//! and writes `/settings`, which apps cannot reach.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_gfx::{Canvas, Rect};
use pinnacle_locale::{Language, t, tf};
use pinnacle_rt::abi::InputEvent;
use pinnacle_rt::abi::net::{
    CONNECTING as NET_CONNECTING, NONE as NET_NONE, OFF as NET_OFF, ONLINE as NET_ONLINE,
};
use pinnacle_rt::{fs, locale, net, tz};
use pinnacle_ui::keyboard::{Key, Keyboard};
use pinnacle_ui::layout::keyboard::Layout;
use pinnacle_ui::layout::{self, settings};
use pinnacle_ui::model::{self, Config};
use pinnacle_ui::p2p::{Client, Contact, Key as ContactKey};
use pinnacle_ui::{App, Event, access, theme, updates};
use pinnacle_view::{IntoView, Screen, Signal, View, el, signal};
use pinnacle_wifi::protocol::{self as wire, State as WifiState};
use pinnacle_wifi::{Security, host::password_fits};

const NAME: &str = "system:/settings/name";
/// The disks shown, by label.
const DISKS: [&str; 2] = ["system", "packages"];
/// The name's longest: what a contact's card carries.
const NAME_MAX: usize = 32;

/// What a row's button does.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Action {
    ChangeName,
    Turn,
    ChangePassword,
    LockNow,
    Network,
    /// Switches the network off, or on again.
    NetworkSwitch,
    Hardware,
    /// The disks, and installing Pinnacle on one.
    Disks,
    /// Install on disk `i` of the disks page: asked first.
    Install(usize),
    /// Yes: erase it and install.
    InstallConfirm,
    Remote,
    /// Allow contact `i` of the remote page, or stop allowing it.
    Allow(usize),
    /// Offer contact `i` this device's services, or stop.
    Offer(usize),
    Agent,
    AgentSwitch,
    Updates,
    /// Look for updates, or stop looking.
    UpdatesLook,
    /// Install them by themselves, or only tell.
    UpdatesInstall,
    UpdatesNow,
    /// Fetch the newer system the last look found.
    SystemInstall,
    /// Restart into the system waiting.
    SystemRestart,
    /// Back to the system kept in the other slot.
    SystemBack,
    AgentField(Field),
    Wifi,
    WifiScan,
    WifiLeave,
    /// Join network `i` of those nearby.
    WifiJoin(usize),
    /// Forget network `i` of those kept.
    WifiForget(usize),
    /// The person's own devices, linked to this one, kept in step.
    Devices,
    /// Show a code another device links to this one by.
    LinkShow,
    /// Type the code another device shows.
    LinkEnter,
    /// Forget own device `i`: it gets nothing more from this one.
    Forget(usize),
    /// Back the vault up to the backup disk, or put its files back.
    BackupNow,
    Restore,
    /// The date and time page: the zone, and where the time comes from.
    DateTime,
    /// The time zones' regions (Europe, America…), to choose one from.
    ZoneRegions,
    /// The zones of region `i`.
    ZoneRegion(usize),
    /// Zone `i` of the region shown.
    ZonePick(usize),
    /// UTC, no zone.
    ZoneUtc,
    /// The keyboard page: its layout.
    Keyboard,
    /// Layout `i` of `Layout::ALL`.
    KeyboardPick(usize),
    Back,
    /// The page of languages, and the formats they write.
    Language,
    /// Use language `i` of `Language::ALL`.
    SetLanguage(usize),
    /// The accessibility page: text size, contrast, the screen reader.
    Access,
    /// The next of the text sizes.
    TextSize,
    Contrast,
    Reader,
    /// The volume's slider let go at this percent: kept, and heard.
    Volume(u8),
    /// The brightness's slider let go at this percent: kept.
    Brightness(u8),
}

/// Which of the date and time pages shows.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum DatePage {
    Now,
    Regions,
    Region(usize),
}

/// What of the agent is typed.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Field {
    Host,
    Model,
    Key,
}

struct Row {
    label: String,
    value: String,
    button: Option<(&'static str, Action)>,
    /// A switch, on or off, that does `Action` when flipped.
    switch: Option<(bool, Action)>,
    /// A slider at this percent: the sound's volume or the screen's
    /// brightness.
    slider: Option<(Slider, u8)>,
    /// A dropdown to choose from.
    choice: Option<Choice>,
}

/// A dropdown's options, the one chosen, its name (as the page announces
/// it) and the action choosing option `i` does.
struct Choice {
    name: &'static str,
    options: Vec<&'static str>,
    chosen: usize,
    action: fn(usize) -> Action,
}

fn row(label: &str, value: String) -> Row {
    Row {
        label: label.into(),
        value,
        button: None,
        switch: None,
        slider: None,
        choice: None,
    }
}

fn choose(label: &str, choice: Choice) -> Row {
    Row {
        choice: Some(choice),
        ..row(label, String::new())
    }
}

/// What a row's slider sets.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Slider {
    Volume,
    Brightness,
}

impl Slider {
    fn label(self) -> &'static str {
        match self {
            Slider::Volume => t("Volume"),
            Slider::Brightness => t("Brightness"),
        }
    }

    /// Its least value: the kernel sets the screen no darker than 5 %.
    fn min(self) -> u8 {
        match self {
            Slider::Volume => 0,
            Slider::Brightness => 5,
        }
    }

    /// Sets it as the slider moves, without keeping it.
    fn follow(self, percent: u8) {
        match self {
            Slider::Volume => {
                pinnacle_rt::audio::volume(Some(percent));
            }
            Slider::Brightness => {
                pinnacle_rt::set_brightness(percent);
            }
        }
    }

    /// What letting go of it at `percent` does.
    fn action(self, percent: u8) -> Action {
        match self {
            Slider::Volume => Action::Volume(percent),
            Slider::Brightness => Action::Brightness(percent),
        }
    }
}

/// A row with `slider`, at `percent`.
fn slider(slider: Slider, percent: u8) -> Row {
    Row {
        slider: Some((slider, percent)),
        ..row(slider.label(), alloc::format!("{percent} %"))
    }
}

fn switch(label: &str, value: String, on: bool, action: Action) -> Row {
    Row {
        switch: Some((on, action)),
        ..row(label, value)
    }
}

fn with(label: &str, value: String, button: &'static str, action: Action) -> Row {
    Row {
        button: Some((button, action)),
        ..row(label, value)
    }
}

struct Section {
    title: &'static str,
    rows: Vec<Row>,
}

fn ip(a: [u8; 4]) -> String {
    alloc::format!("{}.{}.{}.{}", a[0], a[1], a[2], a[3])
}

fn mib(bytes: u64) -> String {
    alloc::format!("{} MiB", bytes >> 20)
}

/// The hardware page: each class of device and the drivers that took
/// them, each driver as open code alone or with a vendor's closed
/// firmware, then what no driver took, as many rows as fit in `height`.
fn hardware(height: i32) -> Vec<Section> {
    let devices = pinnacle_rt::devices();
    let bound = devices.iter().filter(|d| d.driver.is_some()).count();
    let mut classes: Vec<(String, Vec<(String, usize)>)> = Vec::new();
    let mut without: Vec<(String, usize)> = Vec::new();
    // Counted as "virtio-blk × 2", in the order found.
    let count = |list: &mut Vec<(String, usize)>, name: &str| match list.iter_mut().find(|(n, _)| n == name) {
        Some((_, k)) => *k += 1,
        None => list.push((name.into(), 1)),
    };
    for d in &devices {
        match (&d.class, &d.driver) {
            (Some(class), Some(driver)) => {
                let at = match classes.iter().position(|(c, _)| c == class) {
                    Some(at) => at,
                    None => {
                        classes.push((class.clone(), Vec::new()));
                        classes.len() - 1
                    }
                };
                count(&mut classes[at].1, driver);
            }
            _ => count(
                &mut without,
                d.compatible
                    .split(',')
                    .take(2)
                    .collect::<Vec<_>>()
                    .join(",")
                    .as_str(),
            ),
        }
    }
    let listed = |list: &[(String, usize)]| {
        list.iter()
            .map(|(n, k)| {
                if *k > 1 {
                    alloc::format!("{n} × {k}")
                } else {
                    n.clone()
                }
            })
            .collect::<Vec<_>>()
            .join(", ")
    };
    let capital = |s: &str| {
        let mut c = s.chars();
        c.next()
            .map_or(String::new(), |f| f.to_uppercase().chain(c).collect())
    };
    let with_driver: Vec<Row> = classes
        .iter()
        .map(|(class, drivers)| row(&capital(class), listed(drivers)))
        .collect();
    // Each driver, and whether its device runs closed code of another's:
    // the drivers are all Pinnacle's own, some hand their device a
    // vendor's firmware (`firmware/`, docs/hardware.md).
    let mut code: Vec<((String, String), usize)> = Vec::new();
    for d in &devices {
        if let Some(driver) = &d.driver {
            let what = match &d.firmware {
                Some(firmware) => tf("open driver + closed firmware ({})", &[firmware.as_str()]),
                None => t("open driver").into(),
            };
            match code.iter_mut().find(|(key, _)| key.0 == *driver && key.1 == what) {
                Some((_, k)) => *k += 1,
                None => code.push(((driver.clone(), what), 1)),
            }
        }
    }
    let times = |k: usize| {
        if k > 1 {
            alloc::format!(" × {k}")
        } else {
            String::new()
        }
    };
    let code: Vec<Row> = code
        .iter()
        .map(|((driver, what), k)| row(&alloc::format!("{driver}{}", times(*k)), what.clone()))
        .collect();
    // What room is left below the first three cards, a row each.
    let used = 120
        + 3 * (settings::HEADING + 28)
        + (1 + with_driver.len() as i32 + code.len() as i32) * settings::ROW
        + settings::HEADING;
    let room = ((height - used - 24) / settings::ROW).max(1) as usize;
    let mut rest: Vec<Row> = without
        .iter()
        .map(|(name, k)| row(&alloc::format!("{name}{}", times(*k)), t("no driver").into()))
        .collect();
    if rest.len() > room {
        let hidden = rest.len() - room + 1;
        rest.truncate(room - 1);
        rest.push(row(
            &tf("and {} more", &[&alloc::format!("{hidden}")]),
            String::new(),
        ));
    }
    let mut sections = alloc::vec![
        Section {
            title: t("Found"),
            rows: alloc::vec![with(
                t("Devices"),
                tf(
                    "{} of {} with a driver",
                    &[&alloc::format!("{bound}"), &alloc::format!("{}", devices.len())]
                ),
                t("Back"),
                Action::Back
            )],
        },
        Section {
            title: t("With a driver"),
            rows: with_driver,
        },
        Section {
            title: t("Open and closed"),
            rows: code,
        },
    ];
    if !rest.is_empty() {
        sections.push(Section {
            title: t("Without a driver"),
            rows: rest,
        });
    }
    sections
}

/// The remote-access page: who may run commands here, a row each with
/// its button; `contacts` and who of them is `allowed`, as the p2p service
/// said.
fn remote(name: &str, contacts: &[Contact], allowed: &[ContactKey], offered: &[ContactKey]) -> Vec<Section> {
    let services: Vec<Row> = contacts
        .iter()
        .enumerate()
        .map(|(i, c)| {
            let (value, button) = if offered.contains(&c.key) {
                ("Offered", t("Stop"))
            } else {
                ("Not offered", t("Offer"))
            };
            with(&c.name, value.into(), button, Action::Offer(i))
        })
        .collect();
    let mut rows: Vec<Row> = contacts
        .iter()
        .enumerate()
        .map(|(i, c)| {
            let on = allowed.contains(&c.key);
            let (value, button) = if on {
                ("Allowed", t("Stop"))
            } else {
                ("Not allowed", t("Allow"))
            };
            with(&c.name, value.into(), button, Action::Allow(i))
        })
        .collect();
    if rows.is_empty() {
        rows.push(row(t("No contacts yet"), t("Add them in Messages").into()));
    }
    let mut sections = alloc::vec![
        Section {
            title: t("Remote access"),
            rows: alloc::vec![with(
                t("From their terminal"),
                alloc::format!("remote {name}"),
                t("Back"),
                Action::Back
            )],
        },
        Section {
            title: t("May run commands on this device"),
            rows,
        },
    ];
    if !services.is_empty() {
        sections.push(Section {
            title: t("May use its services (their agent too)"),
            rows: services,
        });
    }
    sections
}

/// The contacts, and who of them may run commands here; no contacts
/// without the p2p service, waited for up to `wait` ms. The connection is let go
/// after: the service also sends its apps every message that arrives.
fn contacts(wait: u64) -> (Vec<Contact>, Vec<ContactKey>) {
    match Client::connect(wait) {
        Some(c) => (c.contacts(&mut Vec::new()), pinnacle_ui::p2p::allowed()),
        None => (Vec::new(), pinnacle_ui::p2p::allowed()),
    }
}

/// Everything shown, read afresh. The sections whose rows carry buttons
/// come first, so the buttons' places do not depend on how many disks or
/// network rows there are.
fn sections(width: i32, height: i32) -> Vec<Section> {
    let name = fs::read_string(NAME).unwrap_or_else(|| "Pinnacle".into());
    let screen = alloc::format!(
        "{width} × {height}, {}",
        if height >= width {
            t("upright")
        } else {
            t("sideways")
        }
    );
    // Only with the data in a vault: its password locks the screen.
    let lock = if fs::disk("data").is_some() {
        alloc::vec![
            with(t("Lock now"), String::new(), t("Lock"), Action::LockNow),
            with(t("Password"), String::new(), t("Change"), Action::ChangePassword),
        ]
    } else {
        alloc::vec![row(t("Screen lock"), t("Needs a data vault").into())]
    };
    let disks = DISKS
        .iter()
        .filter_map(|label| {
            let (total, free) = fs::disk(label)?;
            let value = tf("{} free of {}", &[&mib(free), &mib(total)]);
            Some(row(&theme::display_name(label), value))
        })
        .collect();
    let (cores, ram, free) = pinnacle_rt::info();
    alloc::vec![
        Section {
            title: t("This device"),
            rows: alloc::vec![
                with(t("Name"), name, t("Change"), Action::ChangeName),
                with(t("Hardware"), hardware_summary(), t("Show"), Action::Hardware),
                with(t("Disks"), disks_summary(), t("Show"), Action::Disks),
                with(t("Remote access"), remote_summary(), t("Change"), Action::Remote),
                with(t("Agent"), agent_summary(), t("Change"), Action::Agent),
                with(t("Updates"), updates_summary(), t("Change"), Action::Updates),
                with(t("Devices"), devices_summary(), t("Change"), Action::Devices),
                with(t("Date and time"), date_summary(), t("Change"), Action::DateTime),
                with(t("Keyboard"), keyboard_summary(), t("Change"), Action::Keyboard),
            ],
        },
        Section {
            title: t("Language and access"),
            rows: alloc::vec![
                with(
                    t("Language"),
                    String::from(pinnacle_locale::current().name()),
                    t("Change"),
                    Action::Language
                ),
                with(t("Accessibility"), access_summary(), t("Change"), Action::Access),
            ],
        },
        // Without a sound device the kernel has no volume to set, and the
        // section, empty, is not shown.
        Section {
            title: t("Sound"),
            rows: pinnacle_rt::audio::volume(None)
                .map(|v| slider(Slider::Volume, v))
                .into_iter()
                .collect(),
        },
        Section {
            title: t("Screen"),
            // The brightness's slider only where the kernel can set it (a
            // laptop's panel; not QEMU's screen).
            rows: core::iter::once(with(t("Size"), screen, t("Turn"), Action::Turn))
                .chain(pinnacle_rt::brightness().map(|b| slider(Slider::Brightness, b)))
                .collect(),
        },
        Section {
            title: t("Screen lock"),
            rows: lock,
        },
        Section {
            title: t("Network"),
            rows: alloc::vec![with(t("Network"), network_summary(), t("Show"), Action::Network)],
        },
        Section {
            title: t("Storage"),
            rows: disks,
        },
        Section {
            title: t("System"),
            rows: alloc::vec![
                row(t("Version"), env!("CARGO_PKG_VERSION").into()),
                row(t("Cores"), alloc::format!("{cores}")),
                row(t("Memory"), tf("{} free of {}", &[&mib(free), &mib(ram)])),
            ],
        },
    ]
}

/// The language page: the language in use, chosen from a dropdown; then a
/// date and a number as it writes them.
fn language_page() -> Vec<Section> {
    let now = pinnacle_locale::current();
    let rows = alloc::vec![
        choose(
            t("Language"),
            Choice {
                name: "language-choice",
                options: Language::ALL.iter().map(|l| l.name()).collect(),
                chosen: Language::ALL.iter().position(|&l| l == now).unwrap_or(0),
                action: Action::SetLanguage,
            },
        ),
        with("", String::new(), t("Back"), Action::Back),
    ];
    let seconds = match pinnacle_rt::clock() {
        0 => pinnacle_rt::time() / 1000,
        s => s,
    };
    let today = pinnacle_locale::Date::from_days((seconds / 86_400) as i64);
    alloc::vec![
        Section {
            title: t("Language"),
            rows,
        },
        Section {
            title: t("How it writes"),
            rows: alloc::vec![
                row(t("Date"), pinnacle_locale::date_long(today)),
                row(
                    t("Time"),
                    pinnacle_locale::time((seconds / 3600 % 24) as u32, (seconds / 60 % 60) as u32)
                ),
                row(t("Number"), pinnacle_locale::decimal(1_234_567.89, 2)),
            ],
        },
    ]
}

/// Accessibility, as the first page sums it up: "Text 125 %, high
/// contrast, screen reader".
fn access_summary() -> String {
    let p = access::current();
    let mut parts = alloc::vec![tf("Text {} %", &[&alloc::format!("{}", p.text_size)])];
    if p.high_contrast {
        parts.push(String::from(t("high contrast")));
    }
    if p.reader {
        parts.push(String::from(t("screen reader")));
    }
    parts.join(", ")
}

/// The accessibility page.
fn access_page() -> Vec<Section> {
    let p = access::current();
    alloc::vec![
        Section {
            title: t("Accessibility"),
            rows: alloc::vec![
                with(
                    t("Text size"),
                    alloc::format!("{} %", p.text_size),
                    t("Larger"),
                    Action::TextSize
                ),
                switch(
                    t("High contrast"),
                    String::new(),
                    p.high_contrast,
                    Action::Contrast
                ),
                switch(t("Screen reader"), String::new(), p.reader, Action::Reader),
                with("", String::new(), t("Back"), Action::Back),
            ],
        },
        // What each does, a line each: in the rows above they squeezed
        // the labels.
        Section {
            title: t("How they work"),
            rows: alloc::vec![
                row(t("High contrast: black, white and strong edges"), String::new()),
                row(t("Screen reader: a tap says what it touched"), String::new()),
                row(t("A double tap acts on it, a swipe moves on"), String::new()),
            ],
        },
    ]
}

/// Changes the preferences with `change`, keeps them, and has the display
/// server tell every app.
fn change_preferences(app: &App, change: impl FnOnce(&mut access::Preferences)) {
    let mut p = access::Preferences::read();
    change(&mut p);
    if !p.write() {
        pinnacle_rt::println!("settings: the preferences were not kept");
    }
    pinnacle_rt::println!(
        "settings: language {}, text {} %, contrast {}, reader {}",
        p.language.code(),
        p.text_size,
        if p.high_contrast { "high" } else { "normal" },
        if p.reader { "on" } else { "off" }
    );
    app.preferences_changed();
}

/// The network, as the first page sums it up: "Online, wired".
fn network_summary() -> String {
    match net::state() {
        NET_ONLINE => t("Online, wired").into(),
        NET_CONNECTING => t("Connecting").into(),
        NET_OFF => t("Off").into(),
        _ => t("No network").into(),
    }
}

/// The network page: whether it is online and its switch, then over which
/// connection, and the address, router and name server DHCP gave; and
/// Wi-Fi, whose page lists the networks nearby.
fn network(wifi: Option<&WifiState>) -> Vec<Section> {
    let state = net::state();
    let status = match state {
        NET_ONLINE => t("Online"),
        NET_CONNECTING => t("Connecting: asking for an address"),
        NET_OFF => t("Off: nothing is sent or received"),
        _ => t("No network device"),
    };
    let mut rows = alloc::vec![if state == NET_NONE {
        row(t("Networking"), status.into())
    } else {
        let switch = if state == NET_OFF {
            t("Turn on")
        } else {
            t("Turn off")
        };
        with(t("Networking"), status.into(), switch, Action::NetworkSwitch)
    }];
    rows.push(with("", String::new(), t("Back"), Action::Back));
    let mut sections = alloc::vec![Section {
        title: t("Network"),
        rows,
    }];
    // Wi-Fi before the connection, whose rows come and go.
    sections.push(Section {
        title: t("Wi-Fi"),
        rows: alloc::vec![with(t("Wi-Fi"), wifi_summary(wifi), t("Change"), Action::Wifi)],
    });
    if state == NET_ONLINE || state == NET_CONNECTING {
        let mut connection = alloc::vec![row(t("Over"), t("Wired (Ethernet)").into())];
        if let Some((address, router, dns)) = net::info() {
            connection.push(row(t("Address"), ip(address)));
            connection.push(row(t("Router"), ip(router)));
            connection.push(row(t("Name server"), ip(dns)));
        }
        if let Some((address, router, dns)) = net::info6() {
            let six = |a: net::Ipv6| alloc::format!("{}", net::IpAddr::V6(a));
            connection.push(row(t("IPv6 address"), six(address)));
            if let Some(router) = router {
                connection.push(row(t("IPv6 router"), six(router)));
            }
            if let Some(dns) = dns {
                connection.push(row(t("IPv6 name server"), six(dns)));
            }
        }
        sections.push(Section {
            title: t("Connection"),
            rows: connection,
        });
    }
    sections
}

/// Wi-Fi, as the network page sums it up.
fn wifi_summary(state: Option<&WifiState>) -> String {
    match state {
        None => t("No Wi-Fi radio").into(),
        Some(s) if !s.ready => t("No Wi-Fi radio").into(),
        Some(s) => match (&s.joined, &s.joining) {
            (_, Some(joining)) => tf("Joining {}", &[joining]),
            (Some(joined), None) => joined.clone(),
            (None, None) => t("Not connected").into(),
        },
    }
}

/// A signal of 0 to 4 bars, as dots.
fn bars(n: u8) -> String {
    (0..4).map(|i| if i < n { '●' } else { '○' }).collect()
}

/// The Wi-Fi page: the network it is on, the networks nearby (each its
/// signal, how it is protected, and Join), and those kept (Forget).
fn wifi_page(state: Option<&WifiState>) -> Vec<Section> {
    let Some(s) = state.filter(|s| s.ready) else {
        return alloc::vec![Section {
            title: t("Wi-Fi"),
            rows: alloc::vec![
                row(t("Wi-Fi"), t("This device has no Wi-Fi radio").into()),
                with("", String::new(), t("Back"), Action::Back),
            ],
        }];
    };
    let mut top = alloc::vec![match (&s.joined, &s.joining) {
        (_, Some(joining)) => row(t("Joining"), joining.clone()),
        (Some(joined), None) => with(t("Connected to"), joined.clone(), t("Leave"), Action::WifiLeave),
        (None, None) => row(t("Connected to"), t("No network").into()),
    }];
    if let Some((ssid, failure)) = &s.failed {
        top.push(row(
            &tf("Could not join {}", &[ssid]),
            pinnacle_locale::tr(failure.text()).into(),
        ));
    }
    let looking = if s.scanning {
        t("Looking…").into()
    } else {
        tf("{} found", &[&alloc::format!("{}", s.nearby.len())])
    };
    top.push(with(t("Networks nearby"), looking, t("Scan"), Action::WifiScan));
    top.push(with("", String::new(), t("Back"), Action::Back));
    let nearby = s
        .nearby
        .iter()
        .enumerate()
        .map(|(i, n)| {
            let mut value = alloc::format!(
                "{}  {}",
                bars(n.network.bars()),
                pinnacle_locale::tr(n.network.security.text())
            );
            if n.saved {
                value.push_str(t(", kept"));
            }
            if s.joined.as_deref() == Some(n.network.ssid.as_str()) {
                row(&n.network.ssid, tf("{}, connected", &[&value]))
            } else if n.network.security == Security::Enterprise {
                row(&n.network.ssid, tf("{}, needs an account", &[&value]))
            } else {
                with(&n.network.ssid, value, t("Join"), Action::WifiJoin(i))
            }
        })
        .collect();
    let mut sections = alloc::vec![
        Section {
            title: t("Wi-Fi"),
            rows: top
        },
        Section {
            title: t("Networks nearby"),
            rows: nearby,
        },
    ];
    if !s.saved.is_empty() {
        sections.push(Section {
            title: t("Networks kept"),
            rows: s
                .saved
                .iter()
                .enumerate()
                .map(|(i, ssid)| with(ssid, String::new(), t("Forget"), Action::WifiForget(i)))
                .collect(),
        });
    }
    sections
}

/// The agent, as the first page sums it up.
fn agent_summary() -> String {
    let config = Config::read();
    if config.on {
        tf("On, {}", &[host_name(&config.host)])
    } else {
        t("Off").into()
    }
}

/// "api.anthropic.com" of "https://api.anthropic.com/".
fn host_name(url: &str) -> &str {
    let rest = url.split_once("://").map_or(url, |(_, r)| r);
    rest.split('/').next().unwrap_or(rest)
}

/// The agent's page: whether it is on, the host and model it asks, its
/// key, and what was sent to it (the newest first, as many as fit).
fn agent(height: i32) -> Vec<Section> {
    let config = Config::read();
    let vault = fs::disk("data").is_some();
    let key = match (vault, model::key().is_some()) {
        (false, _) => row(t("Key"), t("Needs a data vault").into()),
        (true, true) => with(
            t("Key"),
            t("Kept in the vault").into(),
            t("Change"),
            Action::AgentField(Field::Key),
        ),
        (true, false) => with(
            t("Key"),
            t("None").into(),
            t("Give"),
            Action::AgentField(Field::Key),
        ),
    };
    let state = if config.on {
        t("On: it sends what you ask it")
    } else {
        t("Off: nothing is sent")
    };
    let sent = model::sent();
    let bytes: u64 = sent.iter().filter_map(|e| e.get("bytes").as_u64()).sum();
    let mut log = alloc::vec![row(
        t("Prompts sent"),
        tf(
            "{}, {} KB in all",
            &[
                &alloc::format!("{}", sent.len()),
                &alloc::format!("{}", bytes.div_ceil(1024))
            ]
        )
    )];
    // As many of the newest as the screen has room for under the rest.
    let room = ((height - 900) / 72).clamp(1, 6) as usize;
    for e in sent.iter().rev().take(room) {
        let asked = e
            .get("request")
            .get("messages")
            .as_array()
            .and_then(|m| m.iter().rev().find(|m| m.get("role").as_str() == Some("user")))
            .map(|m| match m.get("content") {
                pinnacle_json::Value::String(text) => text.clone(),
                blocks => blocks
                    .as_array()
                    .unwrap_or(&[])
                    .iter()
                    .filter_map(|b| b.get("text").as_str().or(b.get("content").as_str()))
                    .collect::<Vec<_>>()
                    .join(" "),
            })
            .unwrap_or_default();
        let asked: String = asked.chars().take(28).collect();
        let size = alloc::format!(
            "{} KB to {}",
            e.get("bytes").as_u64().unwrap_or(0).div_ceil(1024),
            host_name(e.get("host").as_str().unwrap_or(""))
        );
        log.push(row(&asked, size));
    }
    alloc::vec![
        Section {
            title: t("Agent"),
            rows: alloc::vec![
                switch(t("Agent"), state.into(), config.on, Action::AgentSwitch),
                with(
                    t("Host"),
                    host_name(&config.host).into(),
                    t("Change"),
                    Action::AgentField(Field::Host)
                ),
                with(
                    t("Model"),
                    config.model,
                    t("Change"),
                    Action::AgentField(Field::Model)
                ),
                key,
                with("", String::new(), t("Back"), Action::Back),
            ],
        },
        Section {
            title: t("What was sent"),
            rows: log,
        },
    ]
}

/// Linking a device, as far as it got.
#[derive(Clone, PartialEq, Eq, Debug)]
enum Link {
    Idle,
    /// Showing this code, waiting for the other device.
    Showing(String),
    /// Looking for the device that shows the code typed.
    Looking,
    Linked(String),
    Failed(&'static str),
}

/// When a sync with own device `key` last ended, and how, as the sync
/// service keeps it: "In step 2 min ago".
fn last_sync(key: &ContactKey) -> String {
    let hex: String = key[..16].iter().map(|b| alloc::format!("{b:02x}")).collect();
    let Some(text) = fs::read_string(&alloc::format!("data:/sync/last/{hex}")) else {
        return "Not in step yet".into();
    };
    let n: Vec<u64> = text.split_whitespace().filter_map(|w| w.parse().ok()).collect();
    let (Some(&at), Some(&failed)) = (n.first(), n.get(4)) else {
        return "Not in step yet".into();
    };
    let now = match pinnacle_rt::clock() {
        0 => pinnacle_rt::time() / 1000,
        s => s,
    };
    let ago = match now.saturating_sub(at) {
        s if s < 60 => "just now".into(),
        s if s < 3600 => alloc::format!("{} min ago", s / 60),
        s if s < 86_400 => alloc::format!("{} h ago", s / 3600),
        s => alloc::format!("{} days ago", s / 86_400),
    };
    match failed {
        0 => alloc::format!("In step {ago}"),
        f => alloc::format!("In step {ago}, {f} not copied"),
    }
}

/// The backup disk, and the last backup made to it.
fn backup_rows(busy: Option<&str>) -> Vec<Row> {
    use pinnacle_ui::p2p::{BACKUP_DISK, BACKUP_LAST};
    let Some((total, free)) = fs::disk(BACKUP_DISK) else {
        return alloc::vec![row("Backup disk", "None connected".into())];
    };
    let last = fs::read_string(BACKUP_LAST)
        .and_then(|t| {
            let n: Vec<u64> = t.split_whitespace().filter_map(|w| w.parse().ok()).collect();
            Some(alloc::format!("{} files", n.get(1)?))
        })
        .unwrap_or_else(|| "None yet".into());
    if let Some(busy) = busy {
        return alloc::vec![row("Backup", busy.into())];
    }
    alloc::vec![
        row(
            "Backup disk",
            alloc::format!("{} free of {}", mib(free), mib(total))
        ),
        with("Last backup", last, "Back up now", Action::BackupNow),
        with("Restore", "Put its files back".into(), "Restore", Action::Restore),
    ]
}

/// The person's own devices: this one, those linked (their names from the
/// contacts), and linking another; then the backup.
fn devices_page(link: &Link, contacts: &[Contact], backup_busy: Option<&str>) -> Vec<Section> {
    let own = pinnacle_ui::p2p::own_devices();
    let name = fs::read_string(NAME).unwrap_or_else(|| "Pinnacle".into());
    let mut linked: Vec<Row> = own
        .iter()
        .enumerate()
        .map(|(i, key)| {
            let name = contacts
                .iter()
                .find(|c| c.key == *key)
                .map_or_else(|| String::from("A device"), |c| c.name.clone());
            with(&name, last_sync(key), "Forget", Action::Forget(i))
        })
        .collect();
    if linked.is_empty() {
        linked.push(row("None linked yet", "Link one below".into()));
    }
    let linking = match link {
        Link::Idle => alloc::vec![
            with(
                "Link a device",
                "It types the code shown here".into(),
                "Show code",
                Action::LinkShow
            ),
            with(
                "Link to my device",
                "Type the code it shows".into(),
                "Enter code",
                Action::LinkEnter
            ),
        ],
        Link::Showing(code) => alloc::vec![
            row("Code", code.clone()),
            row(
                "On the other device",
                "Settings, Devices, Link to my device".into()
            ),
        ],
        Link::Looking => alloc::vec![row("Looking for your device", "Up to a minute".into())],
        Link::Linked(other) => alloc::vec![
            row("Linked", alloc::format!("with {other}")),
            with("Link another", String::new(), "Show code", Action::LinkShow),
        ],
        Link::Failed(why) => alloc::vec![
            row("Not linked", (*why).into()),
            with("Link a device", String::new(), "Show code", Action::LinkShow),
            with(
                "Link to my device",
                String::new(),
                "Enter code",
                Action::LinkEnter
            ),
        ],
    };
    alloc::vec![
        Section {
            title: "Devices",
            rows: alloc::vec![with(name.trim(), "This device".into(), "Back", Action::Back)],
        },
        Section {
            title: "Linking",
            rows: linking,
        },
        Section {
            title: "Kept in step with",
            rows: linked,
        },
        Section {
            title: "Backup",
            rows: backup_rows(backup_busy),
        },
    ]
}

/// The own devices, as the first page sums them up.
fn devices_summary() -> String {
    if fs::disk("data").is_none() {
        return "Needs a data vault".into();
    }
    match pinnacle_ui::p2p::own_devices().len() {
        0 => "Only this one".into(),
        1 => "This one and 1 more".into(),
        n => alloc::format!("This one and {n} more"),
    }
}

/// Who may run commands here, as the first page sums it up.
fn remote_summary() -> String {
    // Not waited for: the page shows at once, without the service too.
    let (contacts, allowed) = contacts(0);
    let names: Vec<&str> = contacts
        .iter()
        .filter(|c| allowed.contains(&c.key))
        .map(|c| c.name.as_str())
        .collect();
    match names.len() {
        0 => t("Nobody").into(),
        1 | 2 => names.join(", "),
        n => tf("{} contacts", &[&alloc::format!("{n}")]),
    }
}

/// The choice, as the first page sums updates up.
fn updates_summary() -> String {
    match updates::Choice::read() {
        updates::Choice::Off => t("Not looked for").into(),
        updates::Choice::Tell => t("Told").into(),
        updates::Choice::Install => t("Installed by themselves").into(),
    }
}

/// How long Look now waits for the service: a look that installs fetches
/// the apps it brings up to date.
const LOOK_WAIT_MS: u64 = 10 * 60_000;

/// The system's part of the updates page: the version that runs, and what
/// may be done with another: one offered installed, one fetched started
/// (a restart), the one kept before gone back to. `busy` says what is
/// under way instead.
fn system_rows(busy: Option<&str>) -> Vec<Row> {
    let running = updates::Running::now();
    let from = match running.slot {
        Some(slot) => tf("Updated, slot {}", &[slot.name()]),
        None => t("As it came").into(),
    };
    let mut rows = alloc::vec![row(&tf("Version {}", &[&running.version]), from)];
    if let Some(busy) = busy {
        rows.push(row(busy, String::new()));
        return rows;
    }
    let record = updates::record();
    if let Some(failed) = record.failed {
        let version = updates::slot_version(failed).unwrap_or_default();
        rows.push(row(&tf("Version {}", &[&version]), t("Did not start").into()));
    }
    if let Some((_, version)) = updates::waiting() {
        rows.push(with(
            &tf("Version {}", &[&version]),
            t("Starts at the next restart").into(),
            t("Restart"),
            Action::SystemRestart,
        ));
    } else if let Some(version) = updates::offered() {
        rows.push(with(
            &tf("Version {}", &[&version]),
            t("Can be installed").into(),
            t("Install"),
            Action::SystemInstall,
        ));
    }
    let kept = running
        .slot
        .map(|s| s.other())
        .filter(|&s| record.failed != Some(s) && record.next != Some(s))
        .and_then(updates::slot_version);
    if let Some(version) = kept {
        rows.push(with(
            &tf("Version {}", &[&version]),
            t("Kept from before").into(),
            t("Go back"),
            Action::SystemBack,
        ));
    }
    rows
}

/// The updates page: whether they are looked for, whether apps are then
/// brought up to date by themselves, the system, and what the last look
/// found, or that a look is under way (`looking_now`).
fn updates_page(looking_now: bool, system_busy: Option<&str>) -> Vec<Section> {
    let choice = updates::Choice::read();
    let looking = choice != updates::Choice::Off;
    let mut rows = alloc::vec![switch(
        t("Look for updates"),
        String::from(if looking { t("Now and then") } else { t("Never") }),
        looking,
        Action::UpdatesLook,
    )];
    if looking {
        let install = choice == updates::Choice::Install;
        rows.push(switch(
            t("Install by themselves"),
            String::from(if install {
                t("When they ask for no more")
            } else {
                t("Told in a notification")
            }),
            install,
            Action::UpdatesInstall,
        ));
    }
    rows.push(with("", String::new(), t("Back"), Action::Back));
    let (at, what) = match updates::last() {
        _ if looking_now => ("Now".into(), t("Looking…").into()),
        Some(last) => last,
        None => (t("Not yet").into(), String::new()),
    };
    alloc::vec![
        Section {
            title: t("Apps and system"),
            rows,
        },
        Section {
            title: t("System"),
            rows: system_rows(system_busy),
        },
        Section {
            title: t("Last look"),
            rows: alloc::vec![
                with(&at, String::new(), t("Look now"), Action::UpdatesNow),
                row(&what, String::new()),
            ],
        },
    ]
}

/// "3 disks", as the first page sums them up.
fn disks_summary() -> String {
    match pinnacle_rt::install::disks().len() {
        1 => "1 disk".into(),
        n => alloc::format!("{n} disks"),
    }
}

/// A disk's size, in GiB from one on.
fn size(bytes: u64) -> String {
    if bytes >= 1 << 30 {
        alloc::format!("{}.{} GiB", bytes >> 30, ((bytes & ((1 << 30) - 1)) * 10) >> 30)
    } else {
        mib(bytes)
    }
}

/// The disks page: installing Pinnacle (the disk chosen, asked about
/// first; how it goes; what it did), then each disk the kernel found,
/// what it holds, and Install on those it may go on.
fn disks_page(choice: Option<usize>) -> Vec<Section> {
    use pinnacle_rt::install::{self, State};
    let disks = install::disks();
    let state = install::state();
    let mut rows = Vec::new();
    match (&state, choice.and_then(|i| disks.get(i))) {
        (State::Running(what), _) => rows.push(row("Installing…", what.clone())),
        (State::Done(what), _) => {
            rows.push(row("Installed", what.clone()));
            rows.push(with(
                "Start from it",
                "Take the stick out once the screen goes dark".into(),
                "Restart",
                Action::SystemRestart,
            ));
        }
        (State::Failed(why), _) => rows.push(row("Not installed", why.clone())),
        (State::Idle, Some(d)) => {
            rows.push(row(
                &alloc::format!("Install on {}?", d.name),
                alloc::format!("Everything on it ({}, {}) is erased", d.model, size(d.bytes)),
            ));
            rows.push(with(
                "",
                String::new(),
                "Erase and install",
                Action::InstallConfirm,
            ));
        }
        (State::Idle, None) if !disks.iter().any(|d| d.installable) => rows.push(row(
            "Install Pinnacle",
            "Start Pinnacle from its USB stick, with a free disk of at least 1 GiB in the device".into(),
        )),
        (State::Idle, None) => rows.push(row(
            "Install Pinnacle",
            "Choose the disk: the device starts from it once it is there".into(),
        )),
    }
    rows.push(with("", String::new(), "Back", Action::Back));
    let offer = matches!(state, State::Idle) && choice.is_none();
    let list = disks
        .iter()
        .enumerate()
        .map(|(i, d)| {
            let holds = match d.holds.as_str() {
                "pinnacle" => "Pinnacle",
                "other" => "another system's",
                "empty" => "empty",
                _ => "holds something",
            };
            let value = alloc::format!(
                "{}, {}, {holds}{}",
                d.model,
                size(d.bytes),
                if d.removable { ", removable" } else { "" }
            );
            if offer && d.installable {
                with(&d.name, value, "Install", Action::Install(i))
            } else {
                row(&d.name, value)
            }
        })
        .collect();
    alloc::vec![
        Section {
            title: "Install Pinnacle",
            rows,
        },
        Section {
            title: "Disks",
            rows: list,
        },
    ]
}

/// The zones Settings offers, by name with their country
/// (`system:/zoneinfo/zones`).
fn zone_list() -> String {
    fs::read_string(&alloc::format!("{}/zones", locale::ZONEINFO)).unwrap_or_default()
}

/// The regions of the zones (`Europe` of `Europe/Amsterdam`), in order.
fn zone_regions(list: &str) -> Vec<&str> {
    let mut regions: Vec<&str> = tz::zones(list)
        .filter_map(|(name, _)| name.split_once('/').map(|(region, _)| region))
        .collect();
    regions.dedup();
    regions
}

/// The zones of `region`, name and country.
fn zones_of<'a>(list: &'a str, region: &str) -> Vec<(&'a str, &'a str)> {
    tz::zones(list)
        .filter(|(name, _)| name.split_once('/').is_some_and(|(r, _)| r == region))
        .collect()
}

/// "Amsterdam, CET": the zone chosen, as the first page sums it up.
fn date_summary() -> String {
    let Some(name) = locale::zone_name() else {
        return "UTC".into();
    };
    let zone = locale::zone_named(&name).unwrap_or_else(locale::Zone::utc);
    let abbreviation = zone.at(pinnacle_rt::clock() as i64).name;
    alloc::format!("{}, {abbreviation}", tz::place(&name))
}

/// The layout chosen, as the first page sums it up.
fn keyboard_summary() -> String {
    Layout::from_name(&locale::keyboard())
        .unwrap_or(Layout::Us)
        .title()
        .into()
}

const WEEKDAYS: [&str; 7] = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
];
const MONTHS: [&str; 12] = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
];

/// The date and time page: now, in the zone chosen; the zone; and where
/// the time of day comes from.
fn date_page() -> Vec<Section> {
    let name = locale::zone_name();
    let zone = locale::zone();
    let (_, source) = pinnacle_rt::clock_ms();
    let (local, time) = match locale::now_in(&zone) {
        Some((t, l)) => (
            Some(l),
            (
                alloc::format!("{:02}:{:02}", t.hour, t.minute),
                alloc::format!(
                    "{} {} {} {}",
                    WEEKDAYS[t.weekday as usize],
                    t.day,
                    MONTHS[t.month as usize - 1],
                    t.year
                ),
            ),
        ),
        None => (None, ("Not known".into(), String::new())),
    };
    let zone_text = match (&name, &local) {
        (Some(name), Some(l)) => alloc::format!(
            "{}, {} (UTC{}{})",
            tz::place(name),
            l.name,
            tz::offset_text(l.offset),
            if l.dst { ", summer time" } else { "" }
        ),
        (Some(name), None) => tz::place(name),
        (None, _) => "UTC".into(),
    };
    let from = match source {
        pinnacle_rt::ClockSource::Network => "Set from the network, authenticated",
        pinnacle_rt::ClockSource::Board => "This device's clock, until the network sets it",
        pinnacle_rt::ClockSource::None => "Not known until the network sets it",
    };
    alloc::vec![
        Section {
            title: "Now",
            rows: alloc::vec![
                row(&time.0, time.1),
                with("Time zone", zone_text, "Change", Action::ZoneRegions),
                with("", String::new(), "Back", Action::Back),
            ],
        },
        Section {
            title: "The time of day",
            rows: alloc::vec![row(from, String::new())],
        },
    ]
}

/// The regions to choose a zone in, and UTC.
fn regions_page() -> Vec<Section> {
    let list = zone_list();
    let mut rows: Vec<Row> = zone_regions(&list)
        .into_iter()
        .enumerate()
        .map(|(i, region)| {
            with(
                &region.replace('_', " "),
                String::new(),
                "Show",
                Action::ZoneRegion(i),
            )
        })
        .collect();
    rows.push(with(
        "UTC",
        "No zone, no summer time".into(),
        "Choose",
        Action::ZoneUtc,
    ));
    rows.push(with("", String::new(), "Back", Action::DateTime));
    alloc::vec![Section {
        title: "Time zone",
        rows,
    }]
}

/// The zones of region `i`, each with its time now.
fn region_page(i: usize) -> Vec<Section> {
    let list = zone_list();
    let Some(region) = zone_regions(&list).get(i).copied() else {
        return regions_page();
    };
    let chosen = locale::zone_name();
    let now = pinnacle_rt::clock() as i64;
    let mut rows = alloc::vec![with("", String::new(), "Back", Action::ZoneRegions)];
    for (n, (name, country)) in zones_of(&list, region).into_iter().enumerate() {
        let offset = locale::zone_named(name).map_or(0, |z| z.at(now).offset);
        let value = alloc::format!("{country}, UTC{}", tz::offset_text(offset));
        rows.push(if chosen.as_deref() == Some(name) {
            row(&tz::place(name), alloc::format!("{value} · chosen"))
        } else {
            with(&tz::place(name), value, "Choose", Action::ZonePick(n))
        });
    }
    // IANA's regions, by name: a section's title is kept as it is.
    const REGIONS: [&str; 10] = [
        "Africa",
        "America",
        "Antarctica",
        "Arctic",
        "Asia",
        "Atlantic",
        "Australia",
        "Europe",
        "Indian",
        "Pacific",
    ];
    let title = REGIONS.into_iter().find(|r| *r == region).unwrap_or("Time zones");
    alloc::vec![Section { title, rows }]
}

/// The zone `n` of region `i`, by name.
fn zone_at(i: usize, n: usize) -> Option<String> {
    let list = zone_list();
    let region = zone_regions(&list).get(i).copied()?;
    zones_of(&list, region)
        .get(n)
        .map(|(name, _)| String::from(*name))
}

/// Writes the zone chosen (None: UTC).
fn choose_zone(name: Option<&str>) {
    fs::create_dir("system:/locale");
    match name {
        Some(name) => fs::write(locale::ZONE, name.as_bytes()),
        None => fs::remove(locale::ZONE),
    };
    pinnacle_rt::println!("settings: time zone {}", name.unwrap_or("UTC"));
}

/// The keyboard page: the layouts, the chosen one marked.
fn keyboard_page() -> Vec<Section> {
    let chosen = Layout::from_name(&locale::keyboard()).unwrap_or(Layout::Us);
    let about = |layout: Layout| match layout {
        Layout::Us => "As printed on most keyboards",
        Layout::UsInternational => "' \" ` ^ ~ put accents on the next letter: 'e is é, \"e is ë, 'c is ç",
        Layout::Dutch => "@ left of 1, + beside L; ¨ ^ ´ ` ~ ¸ put accents on the next letter",
    };
    let mut rows: Vec<Row> = Layout::ALL
        .into_iter()
        .enumerate()
        .map(|(i, layout)| {
            if layout == chosen {
                row(layout.title(), alloc::format!("{} · chosen", about(layout)))
            } else {
                with(
                    layout.title(),
                    about(layout).into(),
                    "Choose",
                    Action::KeyboardPick(i),
                )
            }
        })
        .collect();
    rows.push(with("", String::new(), "Back", Action::Back));
    alloc::vec![Section {
        title: "Layout",
        rows,
    }]
}

/// "8 devices", as the first page sums the hardware up.
fn hardware_summary() -> String {
    let bound = pinnacle_rt::devices()
        .iter()
        .filter(|d| d.driver.is_some())
        .count();
    tf("{} devices", &[&alloc::format!("{bound}")])
}

/// A button's name, as the page announces it (`settings: button <name> at x
/// y`) for `cargo xtask` to tap.
fn name_of(action: Action) -> String {
    match action {
        Action::ChangeName => "name".into(),
        Action::Turn => "turn".into(),
        Action::ChangePassword => "password".into(),
        Action::LockNow => "lock".into(),
        Action::Network => "network".into(),
        Action::NetworkSwitch => "network-switch".into(),
        Action::Hardware => "hardware".into(),
        Action::Disks => "disks".into(),
        Action::Install(i) => alloc::format!("install-{i}"),
        Action::InstallConfirm => "install-confirm".into(),
        Action::Remote => "remote".into(),
        Action::Allow(i) => alloc::format!("allow-{i}"),
        Action::Offer(i) => alloc::format!("offer-{i}"),
        Action::Agent => "agent".into(),
        Action::Updates => "updates".into(),
        Action::UpdatesLook => "updates-look".into(),
        Action::UpdatesInstall => "updates-install".into(),
        Action::UpdatesNow => "updates-now".into(),
        Action::SystemInstall => "system-install".into(),
        Action::SystemRestart => "system-restart".into(),
        Action::SystemBack => "system-back".into(),
        Action::AgentSwitch => "agent-switch".into(),
        Action::AgentField(Field::Host) => "agent-host".into(),
        Action::AgentField(Field::Model) => "agent-model".into(),
        Action::AgentField(Field::Key) => "agent-key".into(),
        Action::Wifi => "wifi".into(),
        Action::WifiScan => "wifi-scan".into(),
        Action::WifiLeave => "wifi-leave".into(),
        Action::WifiJoin(i) => alloc::format!("wifi-join-{i}"),
        Action::WifiForget(i) => alloc::format!("wifi-forget-{i}"),
        Action::Devices => "devices".into(),
        Action::LinkShow => "link-show".into(),
        Action::LinkEnter => "link-enter".into(),
        Action::Forget(i) => alloc::format!("forget-{i}"),
        Action::BackupNow => "backup".into(),
        Action::Restore => "restore".into(),
        Action::DateTime => "date-time".into(),
        Action::ZoneRegions => "zone-regions".into(),
        Action::ZoneRegion(i) => alloc::format!("zone-region-{i}"),
        Action::ZonePick(i) => alloc::format!("zone-{i}"),
        Action::ZoneUtc => "zone-utc".into(),
        Action::Keyboard => "keyboard".into(),
        Action::KeyboardPick(i) => alloc::format!("keyboard-{i}"),
        Action::Back => "back".into(),
        Action::Language => "language".into(),
        Action::SetLanguage(i) => alloc::format!("language-{}", Language::ALL[i].code()),
        Action::Access => "access".into(),
        Action::TextSize => "text-size".into(),
        Action::Contrast => "contrast".into(),
        Action::Reader => "reader".into(),
        Action::Volume(_) => "volume".into(),
        Action::Brightness(_) => "brightness".into(),
    }
}

/// The tone the volume's slider plays when let go: 200 ms at 660 Hz
/// (16 kHz, mono), at [`TONE_LEVEL`] before the mixer's volume.
fn play_tone() {
    let Some(mut player) = pinnacle_rt::audio::Player::open(16_000, 1) else {
        return;
    };
    // A rotating phasor: cos and sin of 2π·660/16000, no `sin` needed.
    let (c, s) = (0.966_600_1f32, 0.256_289_4f32);
    let mut phase = (TONE_LEVEL, 0.0f32);
    let samples: Vec<i16> = (0..3200)
        .map(|_| {
            let v = phase.0 as i16;
            phase = (phase.0 * c - phase.1 * s, phase.0 * s + phase.1 * c);
            v
        })
        .collect();
    player.write(&samples);
    player.drain();
}

/// The tone's loudest sample before the mixer: `cargo xtask sound-demo`
/// finds it scaled by the volume in what QEMU heard.
const TONE_LEVEL: f32 = 8000.0;

/// A page: its title, then each section as the library's titled list, a row
/// its label, its value and its button. A tap puts the button's action in
/// `tapped`.
fn page(title: &str, sections: &[Section], tapped: &Signal<Option<Action>>) -> View {
    let mut main = el("main")
        .attr(
            "style",
            "max-width: 760px; margin: 0 auto; padding: 24px 16px 32px; \
             display: flex; flex-direction: column; gap: 20px",
        )
        .child(
            el("h1")
                .attr("style", "font-size: 30px; margin: 16px 0 0")
                .child(String::from(title)),
        );
    for section in sections.iter().filter(|s| !s.rows.is_empty()) {
        let mut list = el("div").class("m-list").attr("role", "list");
        for row in &section.rows {
            // What the row's slider is at, said beside it as it moves.
            let said = signal(row.value.clone());
            let shown = said.clone();
            let mut item = el("div")
                .class("m-list-item")
                .attr("role", "listitem")
                .child(
                    el("span")
                        .class("m-list-item__body")
                        .child(el("span").class("m-list-item__title").child(row.label.clone())),
                )
                .child(el("span").class("m-list-item__end").child(move || shown.get()));
            if let Some((kind, percent)) = row.slider {
                let tapped = tapped.clone();
                let min = kind.min();
                let percent_of = move |e: &pinnacle_view::Event| {
                    e.value
                        .as_deref()
                        .and_then(|v| v.parse::<u8>().ok())
                        .map(|v| v.clamp(min, 100))
                };
                let moving = said.clone();
                item = item.child(
                    el("div")
                        .class("m-slider")
                        .attr("style", "flex: 1; min-width: 160px")
                        .child(
                            el("input")
                                .class("m-slider__native")
                                .attr("type", "range")
                                .attr("min", alloc::format!("{min}"))
                                .attr("max", "100")
                                .attr("step", "5")
                                .attr("aria-label", kind.label())
                                .attr("data-name", name_of(kind.action(percent)))
                                .prop("value", alloc::format!("{percent}"))
                                // Followed as it moves: the mixer (and what
                                // plays with it) or the panel follows the
                                // finger.
                                .on("input", move |e| {
                                    if let Some(v) = percent_of(e) {
                                        kind.follow(v);
                                        moving.set(alloc::format!("{v} %"));
                                    }
                                })
                                .on("change", move |e| {
                                    if let Some(v) = percent_of(e) {
                                        tapped.set(Some(kind.action(v)));
                                    }
                                }),
                        ),
                );
            }
            if let Some(choice) = &row.choice {
                let tapped = tapped.clone();
                let action = choice.action;
                let mut select = el("select")
                    .class("m-select__native")
                    .attr("aria-label", row.label.clone())
                    .attr("data-name", choice.name);
                for (i, label) in choice.options.iter().enumerate() {
                    select = select.child(
                        el("option")
                            .attr("value", alloc::format!("{i}"))
                            .attr("data-name", name_of(action(i)))
                            .child(*label),
                    );
                }
                let select = select
                    .prop("selectedIndex", alloc::format!("{}", choice.chosen))
                    .on("change", move |e| {
                        if let Some(i) = e.selected_index.and_then(|i| usize::try_from(i).ok()) {
                            tapped.set(Some(action(i)));
                        }
                    });
                item = item.child(
                    el("div")
                        .class("m-select")
                        .attr("style", "flex: 1; min-width: 200px")
                        .child(select),
                );
            }
            if let Some((label, action)) = row.button {
                let tapped = tapped.clone();
                item = item.child(
                    el("button")
                        .class("m-button")
                        .attr("data-size", "sm")
                        .attr("type", "button")
                        .attr("data-name", name_of(action))
                        .on("click", move |_| tapped.set(Some(action)))
                        .child(label),
                );
            }
            if let Some((on, action)) = row.switch {
                let tapped = tapped.clone();
                item = item.child(
                    el("input")
                        .class("m-switch")
                        .attr("type", "checkbox")
                        .attr("role", "switch")
                        .attr("data-name", name_of(action))
                        .prop_bool("checked", on)
                        .on("change", move |_| tapped.set(Some(action))),
                );
            }
            list = list.child(item);
        }
        main = main.child(
            el("section")
                .class("m-section")
                .child(el("h2").class("m-section__title").child(section.title))
                .child(list),
        );
    }
    main.into_view()
}

/// What is being typed, while something is.
enum Editing {
    Name(String),
    /// Of the agent: what, and what is typed so far.
    Agent(Field, String),
    /// A new password: the current one, then the new one twice.
    Password {
        current: Option<String>,
        new: Option<String>,
        entry: String,
        /// Why it starts again, when it does.
        problem: &'static str,
    },
    /// The code another device shows, to link to it.
    Code(String),
    /// The password a backup is sealed under, to make one or restore it.
    Backup {
        restore: bool,
        entry: String,
    },
    /// The password of Wi-Fi network `ssid`.
    Wifi {
        ssid: String,
        security: Security,
        entry: String,
        problem: &'static str,
    },
}

/// The longest host, model or key typed.
const AGENT_MAX: usize = 200;

/// A password's shortest and longest, as the display server takes them.
const PASSWORD_MIN: usize = 8;
const PASSWORD_MAX: usize = 64;

/// Typing: a heading, a line under it, the field, and the keyboard.
fn draw_editing(canvas: &mut Canvas, keyboard: &Keyboard, editing: &Editing) {
    let (width, height) = (canvas.width, canvas.height);
    canvas.fill(theme::BACKGROUND);
    let (x, w) = layout::column(width, layout::COLUMN_MAX);
    let (heading, help, shown) = match editing {
        Editing::Name(name) => (
            t("Device name"),
            t("What contacts see on this device's card. Enter keeps it."),
            name.clone(),
        ),
        Editing::Agent(field, text) => {
            let (heading, help) = match field {
                Field::Host => (
                    t("Agent host"),
                    "Where the model is: https:// and its address. Enter keeps it.",
                ),
                Field::Model => ("Model", t("Which of the host's models answers. Enter keeps it.")),
                Field::Key => (
                    t("Key"),
                    t("The host's key for you, kept in the vault and sent only to the host."),
                ),
            };
            let shown = match field {
                Field::Key => "•".repeat(text.chars().count()),
                _ => text.clone(),
            };
            (heading, help, shown)
        }
        Editing::Password {
            current,
            new,
            entry,
            problem,
        } => {
            let (heading, help) = match (current, new) {
                (None, _) => (t("Current password"), t("The one that opens your data now.")),
                (Some(_), None) => (
                    t("New password"),
                    t("At least eight characters. It opens your data and unlocks the screen."),
                ),
                (Some(_), Some(_)) => (t("New password, again"), t("To be sure of it.")),
            };
            let help = if problem.is_empty() { help } else { problem };
            (heading, help, "•".repeat(entry.chars().count()))
        }
        Editing::Code(code) => (
            "Link to my device",
            "The code your other device shows in Settings, Devices. Enter links.",
            code.clone(),
        ),
        Editing::Backup { restore, entry } => (
            if *restore { "Restore" } else { "Back up" },
            if *restore {
                "The password of the device the backup was made on."
            } else {
                "Your password: the backup is sealed with it."
            },
            "•".repeat(entry.chars().count()),
        ),
        Editing::Wifi {
            ssid, entry, problem, ..
        } => {
            let help = if problem.is_empty() {
                t("The network's password. Enter joins it, and it is kept.")
            } else {
                problem
            };
            (ssid.as_str(), help, "•".repeat(entry.chars().count()))
        }
    };
    canvas.text(theme::title(), x, 80, heading, theme::TEXT);
    canvas.text(theme::small(), x, 116, help, theme::TEXT_DIM);
    let field = Rect::new(x, 150, w, 68);
    canvas.fill_rounded(field, 34, theme::SURFACE);
    let body = theme::body();
    let end = canvas.text(body, field.x + 28, field.y + 44, &shown, theme::TEXT);
    canvas.fill_rect(Rect::new(end + 2, field.y + 18, 3, 34), theme::ACCENT);
    keyboard.draw(canvas, keyboard.area(Rect::new(0, 0, width, height)));
}

fn password(current: Option<String>, new: Option<String>, problem: &'static str) -> Option<Editing> {
    Some(Editing::Password {
        current,
        new,
        entry: String::new(),
        problem,
    })
}

/// A key while typing. Returns what is typed next, `None` when done; a
/// Wi-Fi password typed goes to the service on `wifi`.
fn type_key(editing: Editing, key: Key, wifi: Option<&pinnacle_rt::Channel>) -> Option<Editing> {
    match editing {
        // Enter is the caller's: it backs up or restores.
        Editing::Backup { restore, mut entry } => {
            match key {
                Key::Char(c) if entry.len() < PASSWORD_MAX => entry.push(c),
                Key::Space if entry.len() < PASSWORD_MAX => entry.push(' '),
                Key::Backspace => {
                    entry.pop();
                }
                _ => {}
            }
            Some(Editing::Backup { restore, entry })
        }
        // Enter is the caller's: it links.
        Editing::Code(mut code) => match key {
            Key::Char(c) if code.len() < 20 => {
                code.push(c.to_ascii_uppercase());
                Some(Editing::Code(code))
            }
            Key::Backspace => {
                code.pop();
                Some(Editing::Code(code))
            }
            _ => Some(Editing::Code(code)),
        },
        Editing::Wifi {
            ssid,
            security,
            mut entry,
            problem,
        } => match key {
            Key::Char(c) if entry.len() < 64 => {
                entry.push(c);
                Some(Editing::Wifi {
                    ssid,
                    security,
                    entry,
                    problem,
                })
            }
            Key::Space if entry.len() < 64 => {
                entry.push(' ');
                Some(Editing::Wifi {
                    ssid,
                    security,
                    entry,
                    problem,
                })
            }
            Key::Backspace => {
                entry.pop();
                Some(Editing::Wifi {
                    ssid,
                    security,
                    entry,
                    problem,
                })
            }
            Key::Enter if !password_fits(security, &entry) => Some(Editing::Wifi {
                ssid,
                security,
                entry: String::new(),
                problem: t("That cannot be its password: at least eight characters."),
            }),
            Key::Enter => {
                if let Some(wifi) = wifi {
                    wifi.send(
                        &wire::message(wire::JOIN, &wire::join_body(&ssid, &entry)),
                        Vec::new(),
                    );
                }
                pinnacle_rt::println!("settings: joining {ssid}");
                None
            }
            _ => Some(Editing::Wifi {
                ssid,
                security,
                entry,
                problem,
            }),
        },
        Editing::Agent(field, mut text) => match key {
            Key::Char(c) if text.len() < AGENT_MAX => {
                text.push(c);
                Some(Editing::Agent(field, text))
            }
            Key::Space if text.len() < AGENT_MAX && field != Field::Key => {
                text.push(' ');
                Some(Editing::Agent(field, text))
            }
            Key::Backspace => {
                text.pop();
                Some(Editing::Agent(field, text))
            }
            Key::Enter => {
                let text = text.trim();
                let mut config = Config::read();
                match field {
                    Field::Host if text.starts_with("https://") || text.starts_with("http://") => {
                        config.host = text.into();
                        config.write();
                    }
                    Field::Host => return Some(Editing::Agent(field, text.into())),
                    Field::Model if !text.is_empty() => {
                        config.model = text.into();
                        config.write();
                    }
                    Field::Key if !text.is_empty() => {
                        model::set_key(text);
                    }
                    _ => {}
                }
                pinnacle_rt::println!("settings: the agent's {field:?} changed");
                None
            }
            _ => Some(Editing::Agent(field, text)),
        },
        Editing::Name(mut name) => match key {
            Key::Char(c) if name.len() < NAME_MAX => {
                name.push(c);
                Some(Editing::Name(name))
            }
            Key::Space if name.len() < NAME_MAX => {
                name.push(' ');
                Some(Editing::Name(name))
            }
            Key::Backspace => {
                name.pop();
                Some(Editing::Name(name))
            }
            Key::Enter => {
                let name = String::from(name.trim());
                if !name.is_empty() {
                    fs::create_dir("system:/settings");
                    fs::write(NAME, name.as_bytes());
                    pinnacle_rt::println!("settings: name is {name}");
                }
                None
            }
            _ => Some(Editing::Name(name)),
        },
        Editing::Password {
            current,
            new,
            mut entry,
            problem,
        } => match key {
            Key::Char(c) if entry.len() < PASSWORD_MAX => {
                entry.push(c);
                Some(Editing::Password {
                    current,
                    new,
                    entry,
                    problem,
                })
            }
            Key::Space if entry.len() < PASSWORD_MAX => {
                entry.push(' ');
                Some(Editing::Password {
                    current,
                    new,
                    entry,
                    problem,
                })
            }
            Key::Backspace => {
                entry.pop();
                Some(Editing::Password {
                    current,
                    new,
                    entry,
                    problem,
                })
            }
            Key::Enter => match (current, new) {
                (None, _) => password(Some(entry), None, ""),
                (Some(current), None) if entry.chars().count() < PASSWORD_MIN => {
                    password(Some(current), None, t("At least eight characters, please."))
                }
                (Some(current), None) => password(Some(current), Some(entry), ""),
                (Some(current), Some(new)) if new == entry => {
                    if pinnacle_rt::vault::change(&current, &new) {
                        pinnacle_rt::println!("settings: password changed");
                        None
                    } else {
                        pinnacle_rt::println!("settings: wrong current password");
                        password(None, None, t("That was not the current password: try again."))
                    }
                }
                (Some(current), Some(_)) => {
                    password(Some(current), None, t("The two differed: choose it again."))
                }
            },
            _ => Some(Editing::Password {
                current,
                new,
                entry,
                problem,
            }),
        },
    }
}

#[unsafe(no_mangle)]
fn main(_argument: u64) -> u64 {
    let mut app = App::new("Settings");
    let mut keyboard = Keyboard::new();
    let mut editing: Option<Editing> = None;
    let mut redraw = true;
    let mut on_hardware = false;
    let mut on_disks = false;
    // The disk chosen to install on, asked about before anything is erased.
    let mut install_choice: Option<usize> = None;
    let mut on_remote = false;
    let mut on_agent = false;
    let mut on_network = false;
    // What the network page shows the state of: it is drawn again when that
    // changes (an address from DHCP), looked at twice a second.
    let mut shown_net = net::state();
    let mut on_wifi = false;
    let mut on_updates = false;
    let mut on_date: Option<DatePage> = None;
    let mut on_keyboard = false;
    let mut on_language = false;
    let mut on_access = false;
    // A look asked for, done once the page shows it is under way.
    let mut look_pending = false;
    // The same for the system: Install or Restart, done once the page says so.
    let mut system_pending: Option<Action> = None;
    // The Wi-Fi service, and what it last said.
    let mut wifi: Option<pinnacle_rt::Channel> = pinnacle_rt::connect("wifi");
    let mut wifi_state: Option<WifiState> = None;
    let mut wifi_buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
    let mut people: (Vec<Contact>, Vec<ContactKey>) = (Vec::new(), Vec::new());
    let mut on_devices = false;
    let mut link = Link::Idle;
    // The p2p service's end of a linking under way.
    let mut linking: Option<pinnacle_rt::Channel> = None;
    // A backup or restore asked for (whether a restore, and the password),
    // done once the page says it is under way.
    let mut backup_pending: Option<(bool, String)> = None;
    let mut screen = Screen::new(app.width, app.height);
    let tapped: Signal<Option<Action>> = signal(None);
    loop {
        let (width, height) = (app.width as i32, app.height as i32);
        if redraw {
            screen.resize(app.width, app.height);
            let mut canvas = app.canvas();
            match &editing {
                Some(editing) => draw_editing(&mut canvas, &keyboard, editing),
                None => {
                    shown_net = net::state();
                    let (title, shown) = if on_network {
                        (t("Network"), network(wifi_state.as_ref()))
                    } else if on_hardware {
                        (t("Hardware"), hardware(height))
                    } else if on_disks {
                        (t("Disks"), disks_page(install_choice))
                    } else if on_remote {
                        people = contacts(2000);
                        let name = fs::read_string(NAME).unwrap_or_else(|| "Pinnacle".into());
                        let offered = pinnacle_ui::p2p::offered();
                        (
                            t("Remote access"),
                            remote(name.trim(), &people.0, &people.1, &offered),
                        )
                    } else if on_devices {
                        people = contacts(2000);
                        let busy = backup_pending
                            .as_ref()
                            .map(|(restore, _)| if *restore { "Restoring…" } else { "Backing up…" });
                        ("Devices", devices_page(&link, &people.0, busy))
                    } else if on_agent {
                        (t("Agent"), agent(height))
                    } else if on_wifi {
                        (t("Wi-Fi"), wifi_page(wifi_state.as_ref()))
                    } else if on_language {
                        (t("Language"), language_page())
                    } else if on_access {
                        (t("Accessibility"), access_page())
                    } else if on_updates {
                        let busy = match system_pending {
                            Some(Action::SystemInstall) => Some(t("Fetching…")),
                            Some(_) => Some(t("Restarting…")),
                            None => None,
                        };
                        (t("Updates"), updates_page(look_pending, busy))
                    } else if let Some(date) = on_date {
                        match date {
                            DatePage::Now => (t("Date and time"), date_page()),
                            DatePage::Regions => (t("Time zone"), regions_page()),
                            DatePage::Region(i) => (t("Time zone"), region_page(i)),
                        }
                    } else if on_keyboard {
                        (t("Keyboard"), keyboard_page())
                    } else {
                        (t("Settings"), sections(width, height))
                    };
                    screen.clear();
                    screen.mount(page(title, &shown, &tapped));
                    screen.draw(&mut canvas, true);
                }
            }
            app.present_all();
            if editing.is_none() {
                screen.announce("settings: button ");
            }
            redraw = false;
        }
        if look_pending {
            pinnacle_rt::println!("settings: looking for updates");
            let ended = updates::look_now(LOOK_WAIT_MS);
            pinnacle_rt::println!(
                "settings: {}",
                match (ended, updates::last()) {
                    (true, Some((_, what))) => alloc::format!("updates looked: {what}"),
                    _ => "the updates service did not answer".into(),
                }
            );
            look_pending = false;
            redraw = true;
            continue;
        }
        if let Some((restore, password)) = backup_pending.take() {
            let what = if restore { "restored" } else { "backed up" };
            match pinnacle_ui::p2p::backup(restore, &password) {
                Some(c) => pinnacle_rt::println!("settings: {what} {} files, {} written", c.files, c.written),
                None if restore => pinnacle_rt::println!("settings: no backup that password opens"),
                None => pinnacle_rt::println!("settings: the backup was not made"),
            }
            redraw = true;
            continue;
        }
        match system_pending.take() {
            Some(Action::SystemInstall) => {
                let running = updates::Running::now();
                let outcome = match updates::system_offer(&running) {
                    Some(offer) => updates::fetch_system(&offer, &mut |_, _| {})
                        .map(|slot| alloc::format!("system {} ready in slot {}", offer.version, slot.name())),
                    None => Err("no newer system offered"),
                };
                match outcome {
                    Ok(what) => {
                        updates::set_offered(None);
                        pinnacle_rt::println!("settings: {what}");
                    }
                    Err(why) => pinnacle_rt::println!("settings: the system was not fetched: {why}"),
                }
                redraw = true;
                continue;
            }
            Some(_) => {
                pinnacle_rt::println!("settings: restarting");
                updates::restart();
                // Refused: an installed app may not, which Settings is not.
                redraw = true;
                continue;
            }
            None => {}
        }
        // The network page, and an installation under way, looked at again
        // twice a second.
        let installing = on_disks
            && matches!(
                pinnacle_rt::install::state(),
                pinnacle_rt::install::State::Running(_)
            );
        let watch = ((on_network || installing) && editing.is_none()).then(|| pinnacle_rt::time() + 500);
        // The Wi-Fi service and a linking under way, whichever are there;
        // a message lands in `wifi_buffer` either way.
        let others: Vec<&pinnacle_rt::Channel> = wifi.iter().chain(linking.iter()).collect();
        let link_index = wifi.is_some() as usize;
        let event = app.wait(&others, &mut wifi_buffer, watch);
        drop(others);
        let event = match event {
            Event::Channel { index, len, .. } if linking.is_some() && index == link_index => {
                match wifi_buffer[..len].split_first() {
                    Some((&pinnacle_ui::p2p::LINK_CODE, code)) => {
                        let code = String::from_utf8_lossy(code).into_owned();
                        pinnacle_rt::println!("settings: showing link code {code}");
                        link = Link::Showing(code);
                    }
                    Some((&pinnacle_ui::p2p::LINKED, card)) if card.len() >= 96 => {
                        let name = &card[64..96];
                        let n = name.iter().position(|&b| b == 0).unwrap_or(32);
                        let name = String::from_utf8_lossy(&name[..n]).into_owned();
                        pinnacle_rt::println!("settings: linked with {name}");
                        link = Link::Linked(name);
                        linking = None;
                    }
                    _ => {
                        pinnacle_rt::println!("settings: not linked");
                        link = Link::Failed("No device showed that code");
                        linking = None;
                    }
                }
                redraw = editing.is_none();
                continue;
            }
            Event::ChannelClosed { index } if linking.is_some() && index == link_index => {
                if matches!(link, Link::Showing(_)) {
                    link = Link::Failed("The code ran out");
                }
                linking = None;
                redraw = editing.is_none();
                continue;
            }
            event => event,
        };
        let key = match event {
            Event::Shown(true) | Event::Resized => {
                redraw = true;
                continue;
            }
            // The language, the text size or the contrast changed: the page
            // in the new ones.
            Event::Preferences => {
                screen.restyle();
                redraw = true;
                continue;
            }
            Event::Timeout => {
                redraw = net::state() != shown_net || installing;
                continue;
            }
            Event::Channel { index: 0, len, .. } => {
                if wifi_buffer[..len].first() == Some(&wire::STATE_IS) {
                    wifi_state = WifiState::from_bytes(&wifi_buffer[1..len]);
                    // Typing over it is left as it is.
                    redraw = editing.is_none();
                }
                continue;
            }
            Event::ChannelClosed { .. } => {
                wifi = None;
                wifi_state = None;
                redraw = true;
                continue;
            }
            Event::Input(e) if e.kind == InputEvent::PRESS && editing.is_some() => {
                let all = Rect::new(0, 0, width, height);
                let (pressed, key) = keyboard.touch(e.x, e.y, keyboard.area(all), e.value == 1);
                redraw |= pressed;
                key
            }
            Event::Input(e) if editing.is_none() && e.kind != InputEvent::KEY => {
                // The page takes the press: its states, and a button's click
                // into `tapped`.
                screen.input(&e);
                let action = tapped.get_untracked();
                tapped.set(None);
                if action.is_none()
                    && let Some(area) = screen.draw(&mut app.canvas(), false)
                {
                    app.present(area);
                    // A drag may have scrolled the page: where the buttons
                    // are now.
                    screen.announce("settings: button ");
                }
                match action {
                    Some(Action::ChangeName) => {
                        editing = Some(Editing::Name(fs::read_string(NAME).unwrap_or_default()));
                    }
                    Some(Action::Turn) => {
                        pinnacle_rt::println!("settings: turning the screen");
                        app.turn();
                    }
                    Some(Action::ChangePassword) => {
                        editing = password(None, None, "");
                    }
                    Some(Action::LockNow) => {
                        pinnacle_rt::println!("settings: locking the screen");
                        app.lock();
                    }
                    Some(Action::Network) => {
                        pinnacle_rt::println!("settings: network");
                        on_network = true;
                    }
                    Some(Action::Language) => {
                        pinnacle_rt::println!("settings: language");
                        on_language = true;
                    }
                    Some(Action::SetLanguage(i)) => {
                        change_preferences(&app, |p| p.language = Language::ALL[i]);
                    }
                    Some(Action::Access) => {
                        pinnacle_rt::println!("settings: accessibility");
                        on_access = true;
                    }
                    Some(Action::TextSize) => change_preferences(&app, |p| {
                        let i = access::TEXT_SIZES
                            .iter()
                            .position(|&s| s == p.text_size)
                            .unwrap_or(0);
                        p.text_size = access::TEXT_SIZES[(i + 1) % access::TEXT_SIZES.len()];
                    }),
                    Some(Action::Contrast) => {
                        change_preferences(&app, |p| p.high_contrast = !p.high_contrast)
                    }
                    Some(Action::Reader) => change_preferences(&app, |p| p.reader = !p.reader),
                    Some(Action::Volume(v)) => {
                        pinnacle_rt::audio::volume(Some(v));
                        if !pinnacle_ui::sound::keep(v) {
                            pinnacle_rt::println!("settings: the volume was not kept");
                        }
                        pinnacle_rt::println!("settings: volume {v} %");
                        // A short tone at the new volume, as the person
                        // will hear the ringtone; on a thread, so the page
                        // does not wait for it.
                        pinnacle_rt::thread::spawn(play_tone);
                    }
                    Some(Action::Brightness(v)) => {
                        let set = pinnacle_rt::set_brightness(v);
                        if !pinnacle_ui::brightness::keep(set.unwrap_or(v)) {
                            pinnacle_rt::println!("settings: the brightness was not kept");
                        }
                        pinnacle_rt::println!("settings: brightness {} %", set.unwrap_or(v));
                    }
                    Some(Action::NetworkSwitch) => {
                        let on = net::state() == NET_OFF;
                        let state = net::switch(on);
                        pinnacle_rt::println!(
                            "settings: networking switched {}",
                            if state == Some(NET_OFF) { "off" } else { "on" }
                        );
                    }
                    Some(Action::Hardware) => {
                        pinnacle_rt::println!("settings: hardware");
                        on_hardware = true;
                    }
                    Some(Action::Disks) => {
                        pinnacle_rt::println!("settings: disks");
                        on_disks = true;
                        install_choice = None;
                    }
                    Some(Action::Install(i)) => {
                        pinnacle_rt::println!("settings: install on disk {i}?");
                        install_choice = Some(i);
                    }
                    Some(Action::InstallConfirm) => {
                        let disks = pinnacle_rt::install::disks();
                        if let Some(d) = install_choice.and_then(|i| disks.get(i)) {
                            let started = pinnacle_rt::install::start(&d.name);
                            pinnacle_rt::println!(
                                "settings: installing on {}: {}",
                                d.name,
                                if started { "started" } else { "refused" }
                            );
                        }
                        install_choice = None;
                    }
                    Some(Action::Remote) => {
                        pinnacle_rt::println!("settings: remote access");
                        on_remote = true;
                    }
                    Some(Action::Allow(i)) => {
                        if let Some(contact) = people.0.get(i) {
                            let allow = !people.1.contains(&contact.key);
                            pinnacle_ui::p2p::allow(&contact.key, allow);
                            pinnacle_rt::println!(
                                "settings: {} {} to run commands here",
                                contact.name,
                                if allow { "allowed" } else { "no longer allowed" }
                            );
                        }
                    }
                    Some(Action::Offer(i)) => {
                        if let Some(contact) = people.0.get(i) {
                            let offer = !pinnacle_ui::p2p::offered().contains(&contact.key);
                            pinnacle_ui::p2p::offer(&contact.key, offer);
                            pinnacle_rt::println!(
                                "settings: {} {} this device's services",
                                contact.name,
                                if offer { "may use" } else { "may no longer use" }
                            );
                        }
                    }
                    Some(Action::Agent) => {
                        pinnacle_rt::println!("settings: agent");
                        on_agent = true;
                    }
                    Some(Action::AgentSwitch) => {
                        let mut config = Config::read();
                        config.on = !config.on;
                        config.write();
                        pinnacle_rt::println!(
                            "settings: the agent is {}",
                            if config.on { "on" } else { "off" }
                        );
                    }
                    Some(Action::Updates) => {
                        pinnacle_rt::println!("settings: updates");
                        on_updates = true;
                    }
                    Some(Action::UpdatesLook) => {
                        let choice = match updates::Choice::read() {
                            updates::Choice::Off => updates::Choice::Tell,
                            _ => updates::Choice::Off,
                        };
                        choice.write();
                        updates::changed();
                        pinnacle_rt::println!("settings: updates {choice:?}");
                    }
                    Some(Action::UpdatesInstall) => {
                        let choice = match updates::Choice::read() {
                            updates::Choice::Install => updates::Choice::Tell,
                            _ => updates::Choice::Install,
                        };
                        choice.write();
                        updates::changed();
                        pinnacle_rt::println!("settings: updates {choice:?}");
                    }
                    // Looked for once the page says so.
                    Some(Action::UpdatesNow) => look_pending = true,
                    Some(action @ (Action::SystemInstall | Action::SystemRestart)) => {
                        system_pending = Some(action);
                    }
                    Some(Action::SystemBack) => match updates::go_back() {
                        Some(version) => {
                            pinnacle_rt::println!("settings: going back to system {version}");
                            system_pending = Some(Action::SystemRestart);
                        }
                        None => pinnacle_rt::println!("settings: no system kept to go back to"),
                    },
                    Some(Action::AgentField(field)) => {
                        let config = Config::read();
                        let text = match field {
                            Field::Host => config.host,
                            Field::Model => config.model,
                            Field::Key => String::new(),
                        };
                        editing = Some(Editing::Agent(field, text));
                    }
                    Some(Action::Wifi) => {
                        pinnacle_rt::println!("settings: wi-fi");
                        if wifi.is_none() {
                            wifi = pinnacle_rt::connect("wifi");
                        }
                        if let Some(wifi) = &wifi {
                            wifi.send(&wire::message(wire::SCAN, &[]), Vec::new());
                        }
                        on_wifi = true;
                        on_network = false;
                    }
                    Some(Action::WifiScan) => {
                        if let Some(wifi) = &wifi {
                            wifi.send(&wire::message(wire::SCAN, &[]), Vec::new());
                        }
                    }
                    Some(Action::WifiLeave) => {
                        if let Some(wifi) = &wifi {
                            wifi.send(&wire::message(wire::LEAVE, &[]), Vec::new());
                        }
                    }
                    Some(Action::WifiJoin(i)) => {
                        let network = wifi_state.as_ref().and_then(|s| s.nearby.get(i));
                        if let (Some(n), Some(channel)) = (network, &wifi) {
                            if n.saved || !n.network.security.needs_password() {
                                // Kept, or open: no password to type.
                                pinnacle_rt::println!("settings: joining {}", n.network.ssid);
                                channel.send(
                                    &wire::message(wire::JOIN, &wire::join_body(&n.network.ssid, "")),
                                    Vec::new(),
                                );
                            } else {
                                editing = Some(Editing::Wifi {
                                    ssid: n.network.ssid.clone(),
                                    security: n.network.security,
                                    entry: String::new(),
                                    problem: "",
                                });
                            }
                        }
                    }
                    Some(Action::WifiForget(i)) => {
                        let ssid = wifi_state.as_ref().and_then(|s| s.saved.get(i));
                        if let (Some(ssid), Some(channel)) = (ssid, &wifi) {
                            pinnacle_rt::println!("settings: forgetting {ssid}");
                            channel.send(&wire::message(wire::FORGET, ssid.as_bytes()), Vec::new());
                        }
                    }
                    Some(Action::Devices) => {
                        pinnacle_rt::println!("settings: devices");
                        on_devices = true;
                    }
                    Some(Action::LinkShow) => {
                        linking = pinnacle_ui::p2p::link_show();
                        link = match linking {
                            Some(_) => Link::Looking,
                            None => Link::Failed("The p2p service is not running"),
                        };
                    }
                    Some(Action::LinkEnter) => editing = Some(Editing::Code(String::new())),
                    Some(action @ (Action::BackupNow | Action::Restore)) => {
                        editing = Some(Editing::Backup {
                            restore: action == Action::Restore,
                            entry: String::new(),
                        });
                    }
                    Some(Action::Forget(i)) => {
                        if let Some(key) = pinnacle_ui::p2p::own_devices().get(i) {
                            pinnacle_ui::p2p::set_own(key, false);
                            let hex: String = key[..16].iter().map(|b| alloc::format!("{b:02x}")).collect();
                            fs::remove(&alloc::format!("data:/sync/base/{hex}"));
                            fs::remove(&alloc::format!("data:/sync/last/{hex}"));
                            pinnacle_rt::println!("settings: forgot device {i}");
                        }
                    }
                    Some(Action::DateTime) => {
                        let (ms, source) = pinnacle_rt::clock_ms();
                        let t = locale::Zone::utc().civil((ms / 1000) as i64).0;
                        pinnacle_rt::println!(
                            "settings: date and time, {:02}:{:02} UTC, from {source:?}",
                            t.hour,
                            t.minute
                        );
                        on_date = Some(DatePage::Now);
                    }
                    Some(Action::ZoneRegions) => on_date = Some(DatePage::Regions),
                    Some(Action::ZoneRegion(i)) => on_date = Some(DatePage::Region(i)),
                    Some(Action::ZonePick(n)) => {
                        if let Some(DatePage::Region(i)) = on_date
                            && let Some(name) = zone_at(i, n)
                        {
                            choose_zone(Some(&name));
                            on_date = Some(DatePage::Now);
                        }
                    }
                    Some(Action::ZoneUtc) => {
                        choose_zone(None);
                        on_date = Some(DatePage::Now);
                    }
                    Some(Action::Keyboard) => {
                        pinnacle_rt::println!("settings: keyboard");
                        on_keyboard = true;
                    }
                    Some(Action::KeyboardPick(i)) => {
                        if let Some(layout) = Layout::ALL.get(i) {
                            fs::create_dir("system:/locale");
                            fs::write(locale::KEYBOARD, layout.name().as_bytes());
                            pinnacle_rt::println!("settings: keyboard {}", layout.name());
                        }
                    }
                    Some(Action::Back) => {
                        // Wi-Fi's page goes back to the network page it
                        // was opened from; every other to the first.
                        on_devices = false;
                        on_network = on_wifi;
                        on_hardware = false;
                        // Back from the question goes to the list.
                        on_disks = install_choice.is_some();
                        install_choice = None;
                        on_remote = false;
                        on_agent = false;
                        on_wifi = false;
                        on_updates = false;
                        on_date = None;
                        on_keyboard = false;
                        on_language = false;
                        on_access = false;
                    }
                    None => continue,
                }
                redraw = true;
                continue;
            }
            Event::Input(e) if e.kind == InputEvent::KEY && editing.is_some() => {
                let was_physical = keyboard.physical;
                let key = keyboard.key_event(e.code, e.value);
                redraw |= was_physical != keyboard.physical;
                key
            }
            Event::Closed => return 0,
            _ => continue,
        };
        let Some(key) = key else { continue };
        if let Some(Editing::Code(code)) = &editing
            && matches!(key, Key::Enter)
        {
            pinnacle_rt::println!("settings: linking by code");
            linking = pinnacle_ui::p2p::link_enter(code);
            link = match linking {
                Some(_) => Link::Looking,
                None => Link::Failed("The p2p service is not running"),
            };
            editing = None;
            redraw = true;
            continue;
        }
        if let Some(Editing::Backup { restore, entry }) = &editing
            && matches!(key, Key::Enter)
        {
            // Made once the page says so.
            backup_pending = Some((*restore, entry.clone()));
            editing = None;
            redraw = true;
            continue;
        }
        let Some(typing) = editing.take() else { continue };
        editing = type_key(typing, key, wifi.as_ref());
        // An accent that went on nothing, then the key typed after it.
        if let Some(queued) = keyboard.queued()
            && let Some(typing) = editing.take()
        {
            editing = type_key(typing, queued, wifi.as_ref());
        }
        redraw = true;
    }
}