garage44.eu/jeroen/pinnacle

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

.. /programs/src/bin/clock.rs

raw

//! A clock, built from a view, on four tabs: Clock, Alarm, Timer and
//! Stopwatch.
//!
//! Clock is the time, large, the date, and the zone. The time is local, in
//! the zone chosen in Settings → Date and time (`pinnacle_rt::locale`),
//! summer time included; the zone is read again each minute, so a change
//! shows without opening the clock again.
//!
//! Alarm keeps alarms (a time of day, on or off) in the app's folder; one
//! that is on rings every day at its time, with a sound and a notification.
//! There is no alarm service: **an alarm rings only while Clock is open**,
//! in front or behind another app, and the page says so. Timer counts down
//! from minutes and seconds set by steps or presets, and rings the same way
//! when it ends. Stopwatch counts up, with laps.
//!
//! The texts that tick are signals written while in front, so only what
//! changed is drawn again; hidden, it sleeps until a timer, an alarm's
//! minute or the ringing needs it.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;

use pinnacle_locale::{localise_number, t, tf};
use pinnacle_rt::Channel;
use pinnacle_rt::audio::Player;
use pinnacle_rt::fs;
use pinnacle_rt::locale::{self, Zone};
use pinnacle_ui::{App, Event};
use pinnacle_view::{IntoView, Screen, Signal, View, el, signal};

/// Where the alarms are kept, a line each: "07:30 on".
const ALARMS: &str = "app:/alarms";
/// Where the timer's last length is kept, in seconds.
const TIMER: &str = "app:/timer";
/// The longest timer: 99 minutes and 59 seconds.
const TIMER_MAX: u64 = 99 * 60 + 59;
/// The timer's presets, in minutes.
const PRESETS: [u64; 6] = [1, 3, 5, 10, 15, 30];
/// How long a ring sounds before it falls quiet (it stays on the page
/// until stopped).
const RING_FOR_MS: u64 = 60_000;
/// The ring: two beeps of 880 Hz each second, at 16 kHz, as the cos and
/// sin of its angle per sample (see calls.rs for the tone).
const BEEP: (f32, f32) = (0.940_881, 0.338_738);
const BEEP_SAMPLES: usize = 2400;
const GAP_SAMPLES: usize = 1600;
const RING_EVERY_MS: u64 = 1000;

/// The tabs, in their order.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Tab {
    Clock,
    Alarm,
    Timer,
    Stopwatch,
}

const TABS: [(Tab, &str); 4] = [
    (Tab::Clock, "clock"),
    (Tab::Alarm, "alarm"),
    (Tab::Timer, "timer"),
    (Tab::Stopwatch, "stopwatch"),
];

impl Tab {
    fn label(self) -> &'static str {
        match self {
            Tab::Clock => t("Clock"),
            Tab::Alarm => t("Alarm"),
            Tab::Timer => t("Timer"),
            Tab::Stopwatch => t("Stopwatch"),
        }
    }
}

/// What a tap asked for.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Tap {
    Tab(Tab),
    WatchStart,
    WatchStop,
    WatchLap,
    WatchReset,
    TimerStart,
    TimerPause,
    TimerReset,
    /// Seconds added to the timer's length (or taken, below zero).
    TimerStep(i64),
    /// A length in minutes.
    TimerPreset(u64),
    /// Hours and minutes added to the new alarm's time.
    AlarmHour(i32),
    AlarmMinute(i32),
    AlarmAdd,
    AlarmToggle(usize),
    AlarmDelete(usize),
    /// Stops the ringing.
    Dismiss,
}

/// What the page shows that ticks.
#[derive(Clone)]
struct Face {
    time: Signal<String>,
    date: Signal<String>,
    zone: Signal<String>,
    /// The stopwatch's time, and the timer's time left.
    watch: Signal<String>,
    left: Signal<String>,
}

/// The zone chosen and its name, read again once a minute.
struct Chosen {
    zone: Zone,
    name: Option<String>,
    read_at: u64,
}

impl Chosen {
    fn read() -> Chosen {
        let name = locale::zone_name();
        Chosen {
            zone: name
                .as_deref()
                .and_then(locale::zone_named)
                .unwrap_or_else(Zone::utc),
            name,
            read_at: pinnacle_rt::time(),
        }
    }

    fn fresh(&mut self) -> &Chosen {
        if pinnacle_rt::time() >= self.read_at + 60_000 {
            *self = Chosen::read();
        }
        self
    }
}

/// A stopwatch: the time counted before it was last started, when it was
/// (ms since boot) while it runs, and the time at each lap.
#[derive(Default)]
struct Stopwatch {
    before: u64,
    since: Option<u64>,
    laps: Vec<u64>,
}

impl Stopwatch {
    fn elapsed(&self, now: u64) -> u64 {
        self.before + self.since.map_or(0, |s| now.saturating_sub(s))
    }
}

/// The timer: set to a length, running until a moment, or paused with
/// some left.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Timer {
    Set,
    Running { ends: u64 },
    Paused { left: u64 },
}

/// An alarm: a time of day, on or off.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Alarm {
    hour: u32,
    minute: u32,
    on: bool,
}

impl Alarm {
    fn text(&self) -> String {
        format!("{:02}:{:02}", self.hour, self.minute)
    }
}

/// What rings.
#[derive(Clone, PartialEq, Eq, Debug)]
enum Rang {
    Timer,
    Alarm(String),
}

/// A ring: what, since when, and when its next beeps are due.
struct Ring {
    what: Rang,
    since: u64,
    next: u64,
}

/// Everything the app keeps, beside the view.
struct State {
    tab: Tab,
    watch: Stopwatch,
    timer: Timer,
    /// The timer's length, in seconds.
    length: u64,
    alarms: Vec<Alarm>,
    /// The time the next alarm added is set to.
    new_alarm: (u32, u32),
    ringing: Option<Ring>,
    /// The minute (since 1970) alarms were last looked at: each rings once.
    looked: u64,
}

/// The alarms kept; none when there is no file.
fn load_alarms() -> Vec<Alarm> {
    let text = fs::read_string(ALARMS).unwrap_or_default();
    text.lines()
        .filter_map(|line| {
            let (time, on) = line.trim().split_once(' ')?;
            let (hour, minute) = time.split_once(':')?;
            let (hour, minute) = (hour.parse().ok()?, minute.parse().ok()?);
            (hour < 24 && minute < 60).then_some(Alarm {
                hour,
                minute,
                on: on == "on",
            })
        })
        .collect()
}

fn save_alarms(alarms: &[Alarm]) {
    let mut text = String::new();
    for a in alarms {
        text.push_str(&format!("{} {}\n", a.text(), if a.on { "on" } else { "off" }));
    }
    if !fs::write(ALARMS, text.as_bytes()) {
        pinnacle_rt::println!("clock: could not save the alarms");
    }
}

/// "01:02,3" (or "1:01:02,3" past an hour): a stopwatch's time, to the
/// tenth, with the language's decimal separator.
fn watch_text(ms: u64) -> String {
    let (h, m, s, tenth) = (ms / 3_600_000, ms / 60_000 % 60, ms / 1000 % 60, ms / 100 % 10);
    localise_number(&if h > 0 {
        format!("{h}:{m:02}:{s:02}.{tenth}")
    } else {
        format!("{m:02}:{s:02}.{tenth}")
    })
}

/// "05:00": minutes and seconds, the seconds rounded up so a timer shows
/// 00:00 only when it is done.
fn left_text(ms: u64) -> String {
    let s = ms.div_ceil(1000);
    format!("{:02}:{:02}", s / 60, s % 60)
}

/// `n` samples of a tone, turning `phase` by `step` (cos, sin) a sample.
fn tone(phase: &mut (f32, f32), step: (f32, f32), n: usize, out: &mut Vec<i16>) {
    for _ in 0..n {
        out.push(phase.0 as i16);
        *phase = (
            phase.0 * step.0 - phase.1 * step.1,
            phase.0 * step.1 + phase.1 * step.0,
        );
    }
}

/// One second's beeps of the ring: two short ones, then quiet.
fn beeps() -> Vec<i16> {
    let mut out = Vec::new();
    let mut phase = (6000.0f32, 0.0f32);
    tone(&mut phase, BEEP, BEEP_SAMPLES, &mut out);
    out.resize(out.len() + GAP_SAMPLES, 0);
    let mut phase = (6000.0f32, 0.0f32);
    tone(&mut phase, BEEP, BEEP_SAMPLES, &mut out);
    out
}

impl State {
    fn timer_left(&self, now: u64) -> u64 {
        match self.timer {
            Timer::Set => self.length * 1000,
            Timer::Running { ends } => ends.saturating_sub(now),
            Timer::Paused { left } => left,
        }
    }

    /// When the loop must wake next: for the page's ticking while in
    /// front, and, in front or not, for the timer, the ringing, and the
    /// next minute while an alarm is on.
    fn deadline(&self, shown: bool, now: u64) -> Option<u64> {
        let mut at: Option<u64> = None;
        let mut by = |t: u64| at = Some(at.map_or(t, |a| a.min(t)));
        if shown {
            match self.tab {
                Tab::Clock => by((now / 1000 + 1) * 1000),
                Tab::Stopwatch if self.watch.since.is_some() => by((now / 100 + 1) * 100),
                Tab::Timer if matches!(self.timer, Timer::Running { .. }) => by((now / 100 + 1) * 100),
                _ => {}
            }
        }
        if let Timer::Running { ends } = self.timer {
            by(ends);
        }
        if let Some(ring) = &self.ringing
            && now < ring.since + RING_FOR_MS
        {
            by(ring.next);
        }
        let clock = pinnacle_rt::clock();
        if clock != 0 && self.alarms.iter().any(|a| a.on) {
            by(now + (60 - clock % 60) * 1000);
        }
        at
    }

    /// Starts ringing `what`: the sound where there is a speaker, and a
    /// notification when Clock is not in front.
    fn ring(&mut self, what: Rang, shown: bool, display: &mut Option<Channel>, speaker: &mut Option<Player>) {
        let now = pinnacle_rt::time();
        let (title, text) = match &what {
            Rang::Timer => (t("Timer"), String::from(t("Time is up"))),
            Rang::Alarm(time) => (t("Alarm"), time.clone()),
        };
        pinnacle_rt::println!("clock: {} rings, {text}", title);
        if !shown {
            if display.is_none() {
                *display = pinnacle_rt::connect("display");
            }
            if let Some(display) = display {
                pinnacle_ui::notify(display, "clock", title, &text);
            }
        }
        if speaker.is_none() {
            *speaker = Player::open(16_000, 1);
        }
        self.ringing = Some(Ring {
            what,
            since: now,
            next: now,
        });
    }

    /// What time brought: the timer done, an alarm's minute, the ring's
    /// next beeps. True when the page is to be built again.
    fn tick(
        &mut self,
        chosen: &mut Chosen,
        shown: bool,
        display: &mut Option<Channel>,
        speaker: &mut Option<Player>,
    ) -> bool {
        let now = pinnacle_rt::time();
        let mut changed = false;
        if let Timer::Running { ends } = self.timer
            && now >= ends
        {
            self.timer = Timer::Set;
            self.ring(Rang::Timer, shown, display, speaker);
            changed = true;
        }
        let minute = pinnacle_rt::clock() / 60;
        if minute != 0 && minute != self.looked {
            self.looked = minute;
            if let Some((local, _)) = locale::now_in(&chosen.fresh().zone)
                && let Some(alarm) = self
                    .alarms
                    .iter()
                    .find(|a| a.on && a.hour == local.hour && a.minute == local.minute)
            {
                let text = alarm.text();
                self.ring(Rang::Alarm(text), shown, display, speaker);
                changed = true;
            }
        }
        if let Some(ring) = &mut self.ringing
            && now >= ring.next
        {
            if now < ring.since + RING_FOR_MS {
                if let Some(speaker) = speaker.as_mut() {
                    speaker.write(&beeps());
                }
                ring.next = now + RING_EVERY_MS;
            } else if speaker.take().is_some() {
                pinnacle_rt::println!("clock: the ring fell quiet");
            }
        }
        changed
    }

    /// Does what a tap asked for.
    fn tap(&mut self, tap: Tap, speaker: &mut Option<Player>) {
        let now = pinnacle_rt::time();
        match tap {
            Tap::Tab(tab) => {
                self.tab = tab;
                pinnacle_rt::println!("clock: tab {tab:?}");
            }
            Tap::WatchStart => {
                self.watch.since = Some(now);
                pinnacle_rt::println!("clock: stopwatch started");
            }
            Tap::WatchStop => {
                self.watch.before = self.watch.elapsed(now);
                self.watch.since = None;
                pinnacle_rt::println!("clock: stopwatch stopped at {}", self.watch.before);
            }
            Tap::WatchLap => {
                let at = self.watch.elapsed(now);
                self.watch.laps.push(at);
                pinnacle_rt::println!("clock: lap {} at {at}", self.watch.laps.len());
            }
            Tap::WatchReset => {
                self.watch = Stopwatch::default();
                pinnacle_rt::println!("clock: stopwatch reset");
            }
            Tap::TimerStart => {
                let left = self.timer_left(now);
                if left > 0 {
                    self.timer = Timer::Running { ends: now + left };
                    pinnacle_rt::println!("clock: timer started, {}", left_text(left));
                }
            }
            Tap::TimerPause => {
                let left = self.timer_left(now);
                self.timer = Timer::Paused { left };
                pinnacle_rt::println!("clock: timer paused, {}", left_text(left));
            }
            Tap::TimerReset => {
                self.timer = Timer::Set;
                pinnacle_rt::println!("clock: timer reset");
            }
            Tap::TimerStep(by) => self.set_length(self.length.saturating_add_signed(by)),
            Tap::TimerPreset(minutes) => self.set_length(minutes * 60),
            Tap::AlarmHour(by) => {
                self.new_alarm.0 = (self.new_alarm.0 as i32 + by).rem_euclid(24) as u32;
            }
            Tap::AlarmMinute(by) => {
                self.new_alarm.1 = (self.new_alarm.1 as i32 + by).rem_euclid(60) as u32;
            }
            Tap::AlarmAdd => {
                let (hour, minute) = self.new_alarm;
                let alarm = Alarm {
                    hour,
                    minute,
                    on: true,
                };
                if !self.alarms.iter().any(|a| a.hour == hour && a.minute == minute) {
                    self.alarms.push(alarm);
                    self.alarms.sort_by_key(|a| (a.hour, a.minute));
                }
                save_alarms(&self.alarms);
                pinnacle_rt::println!("clock: alarm {} added", alarm.text());
            }
            Tap::AlarmToggle(i) => {
                if let Some(a) = self.alarms.get_mut(i) {
                    a.on = !a.on;
                    pinnacle_rt::println!("clock: alarm {} {}", a.text(), if a.on { "on" } else { "off" });
                    save_alarms(&self.alarms);
                }
            }
            Tap::AlarmDelete(i) => {
                if i < self.alarms.len() {
                    let a = self.alarms.remove(i);
                    pinnacle_rt::println!("clock: alarm {} deleted", a.text());
                    save_alarms(&self.alarms);
                }
            }
            Tap::Dismiss => {
                self.ringing = None;
                *speaker = None;
                pinnacle_rt::println!("clock: ring stopped");
            }
        }
    }

    fn set_length(&mut self, seconds: u64) {
        self.length = seconds.min(TIMER_MAX);
        self.timer = Timer::Set;
        if !fs::write(TIMER, format!("{}", self.length).as_bytes()) {
            pinnacle_rt::println!("clock: could not keep the timer's length");
        }
        pinnacle_rt::println!("clock: timer set to {}", left_text(self.length * 1000));
    }
}

/// The texts now: the local time, or the time since boot when nothing
/// knows the time of day; and the stopwatch's and the timer's.
fn show(face: &Face, chosen: &Chosen, state: &State) {
    let now = pinnacle_rt::time();
    face.watch.set(watch_text(state.watch.elapsed(now)));
    face.left.set(left_text(state.timer_left(now)));
    let Some((t, local)) = locale::now_in(&chosen.zone) else {
        let s = now / 1000;
        face.time
            .set(format!("{:02}:{:02}:{:02}", s / 3600 % 24, s / 60 % 60, s % 60));
        face.date
            .set(t("The time of day is not known yet: time since boot").into());
        face.zone.set(String::new());
        return;
    };
    face.time
        .set(format!("{:02}:{:02}:{:02}", t.hour, t.minute, t.second));
    // In the language chosen: "zondag 29 november 2026". The zone's
    // weekday counts from Sunday, the language's from Monday.
    face.date.set(format!(
        "{} {} {} {}",
        pinnacle_locale::weekday_name((t.weekday as usize + 6) % 7),
        t.day,
        pinnacle_locale::month_name(t.month),
        t.year
    ));
    face.zone.set(match &chosen.name {
        Some(name) => format!(
            "{} · {} (UTC{})",
            pinnacle_rt::tz::place(name),
            local.name,
            pinnacle_rt::tz::offset_text(local.offset)
        ),
        None => "UTC".into(),
    });
}

/// A button that puts `tap` in `tapped`, named for `cargo xtask`.
fn button(
    label: impl IntoView,
    name: impl Into<String>,
    variant: &'static str,
    tap: Tap,
    tapped: &Signal<Option<Tap>>,
) -> View {
    said(label, name, variant, None, tap, tapped)
}

/// A [`button`] whose label is a sign ("−", "+5"), with the words a screen
/// reader says for it.
fn said(
    label: impl IntoView,
    name: impl Into<String>,
    variant: &'static str,
    spoken: Option<&'static str>,
    tap: Tap,
    tapped: &Signal<Option<Tap>>,
) -> View {
    let tapped = tapped.clone();
    el("button")
        .class("m-button")
        .attr("type", "button")
        .attr("data-variant", (!variant.is_empty()).then_some(variant))
        .attr("data-name", name.into())
        .attr("aria-label", spoken)
        .on("click", move |_| tapped.set(Some(tap)))
        .child(label)
        .into_view()
}

/// A row of controls, centred and wrapping on a narrow window.
fn row(children: Vec<View>) -> View {
    el("div")
        .attr(
            "style",
            "display: flex; flex-wrap: wrap; justify-content: center; align-items: center; gap: 12px",
        )
        .children(children)
        .into_view()
}

/// A large time, in the mono face so its digits do not jump.
fn big(text: Signal<String>) -> View {
    el("div")
        .attr(
            "style",
            "font-size: 64px; line-height: 1.2; font-family: monospace; color: var(--m-text)",
        )
        .child(move || text.get())
        .into_view()
}

/// The time, large; the date under it; the zone under that.
fn clock_tab(face: &Face) -> View {
    let (time, date, zone) = (face.time.clone(), face.date.clone(), face.zone.clone());
    el("div")
        .attr(
            "style",
            "flex: 1; display: flex; flex-direction: column; \
             align-items: center; justify-content: center; gap: 12px",
        )
        .child(
            el("div")
                .attr("style", "font-size: 72px; line-height: 1.2; color: var(--m-text)")
                .child(move || time.get()),
        )
        .child(
            el("div")
                .attr("style", "font-size: 21px; color: var(--m-text-dim)")
                .child(move || date.get()),
        )
        .child(
            el("div")
                .attr(
                    "style",
                    "font-size: 12px; color: var(--m-text-dim); margin-top: 24px",
                )
                .child(move || zone.get()),
        )
        .into_view()
}

/// The stopwatch: its time, its buttons, and the laps, the last first.
fn stopwatch_tab(state: &State, face: &Face, tapped: &Signal<Option<Tap>>) -> View {
    let watch = &state.watch;
    let running = watch.since.is_some();
    let buttons = row(match (running, watch.before) {
        (true, _) => alloc::vec![
            button(t("Lap"), "stopwatch-lap", "", Tap::WatchLap, tapped),
            button(t("Stop"), "stopwatch-stop", "primary", Tap::WatchStop, tapped),
        ],
        (false, 0) => alloc::vec![button(
            t("Start"),
            "stopwatch-start",
            "primary",
            Tap::WatchStart,
            tapped
        )],
        (false, _) => alloc::vec![
            button(t("Reset"), "stopwatch-reset", "", Tap::WatchReset, tapped),
            button(t("Resume"), "stopwatch-start", "primary", Tap::WatchStart, tapped),
        ],
    });
    let mut laps = el("div")
        .class("m-list")
        .attr("role", "list")
        .attr("style", "width: 100%; max-width: 420px");
    for (i, at) in watch.laps.iter().enumerate().rev() {
        let before = if i == 0 { 0 } else { watch.laps[i - 1] };
        laps = laps.child(
            el("div")
                .class("m-list-item")
                .attr("role", "listitem")
                .attr("data-name", format!("lap-{}", i + 1))
                .child(
                    el("span")
                        .class("m-list-item__body")
                        .child(
                            el("span")
                                .class("m-list-item__title")
                                .child(tf("Lap {}", &[&format!("{}", i + 1)])),
                        )
                        .child(el("span").class("m-list-item__sub").child(watch_text(*at))),
                )
                .child(
                    el("span")
                        .attr("style", "font-family: monospace")
                        .child(watch_text(at - before)),
                ),
        );
    }
    el("div")
        .attr(
            "style",
            "flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; \
             align-items: center; gap: 24px; padding-top: 32px",
        )
        .child(big(face.watch.clone()))
        .child(buttons)
        .child(laps)
        .into_view()
}

/// The timer: its time left, steps for its length and presets while it is
/// set, and start, pause and reset.
fn timer_tab(state: &State, face: &Face, tapped: &Signal<Option<Tap>>) -> View {
    let mut page = el("div").attr(
        "style",
        "flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; \
         align-items: center; gap: 24px; padding-top: 32px",
    );
    if state.timer == Timer::Set {
        // Minutes on the left of the time, seconds on its right.
        let step =
            |label, name, spoken, by| said(label, name, "ghost", Some(spoken), Tap::TimerStep(by), tapped);
        page = page.child(row(alloc::vec![
            step("−", "timer-minus-minute", t("One minute less"), -60),
            step("+", "timer-plus-minute", t("One minute more"), 60),
            big(face.left.clone()),
            step("−", "timer-minus-seconds", t("Ten seconds less"), -10),
            step("+", "timer-plus-seconds", t("Ten seconds more"), 10),
        ]));
        let presets = PRESETS
            .iter()
            .map(|&minutes| {
                button(
                    tf("{} min", &[&format!("{minutes}")]),
                    format!("timer-preset-{minutes}"),
                    "",
                    Tap::TimerPreset(minutes),
                    tapped,
                )
            })
            .collect();
        page = page.child(row(presets));
    } else {
        page = page.child(big(face.left.clone()));
    }
    let buttons = row(match state.timer {
        Timer::Set => alloc::vec![button(
            t("Start"),
            "timer-start",
            "primary",
            Tap::TimerStart,
            tapped
        )],
        Timer::Running { .. } => alloc::vec![
            button(t("Reset"), "timer-reset", "", Tap::TimerReset, tapped),
            button(t("Pause"), "timer-pause", "primary", Tap::TimerPause, tapped),
        ],
        Timer::Paused { .. } => alloc::vec![
            button(t("Reset"), "timer-reset", "", Tap::TimerReset, tapped),
            button(t("Resume"), "timer-start", "primary", Tap::TimerStart, tapped),
        ],
    });
    page.child(buttons)
        .child(
            el("p")
                .attr("style", "margin: 0; color: var(--m-text-dim); text-align: center")
                .child(t("It rings while Clock is open, in front or not.")),
        )
        .into_view()
}

/// The alarms, each with a switch and Delete; a time to add one at; and
/// what an alarm can and cannot do.
fn alarm_tab(state: &State, tapped: &Signal<Option<Tap>>) -> View {
    let mut list = el("div")
        .class("m-list")
        .attr("role", "list")
        .attr("style", "width: 100%; max-width: 420px");
    for (i, alarm) in state.alarms.iter().enumerate() {
        let toggled = tapped.clone();
        list = list.child(
            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")
                                .attr("style", "font-size: 30px")
                                .child(alarm.text()),
                        )
                        .child(el("span").class("m-list-item__sub").child(if alarm.on {
                            t("Every day")
                        } else {
                            t("Off")
                        })),
                )
                .child(
                    el("input")
                        .class("m-switch")
                        .attr("type", "checkbox")
                        .attr("role", "switch")
                        .attr("aria-label", tf("Alarm {}", &[&alarm.text()]))
                        .attr("data-name", format!("alarm-on-{i}"))
                        .prop_bool("checked", alarm.on)
                        .on("change", move |_| toggled.set(Some(Tap::AlarmToggle(i)))),
                )
                .child(button(
                    t("Delete"),
                    format!("alarm-delete-{i}"),
                    "ghost",
                    Tap::AlarmDelete(i),
                    tapped,
                )),
        );
    }
    if state.alarms.is_empty() {
        list = list.child(
            el("p")
                .attr("style", "margin: 0; color: var(--m-text-dim); text-align: center")
                .child(t("No alarms yet")),
        );
    }
    let (hour, minute) = state.new_alarm;
    let step = |label, name, spoken, tap| said(label, name, "ghost", Some(spoken), tap, tapped);
    // The hour's steps on the left of the time, the minutes' on its right.
    let new = row(alloc::vec![
        step("−", "alarm-hour-minus", t("One hour earlier"), Tap::AlarmHour(-1)),
        step("+", "alarm-hour-plus", t("One hour later"), Tap::AlarmHour(1)),
        el("div")
            .attr("style", "font-size: 48px; font-family: monospace")
            .child(format!("{hour:02}:{minute:02}"))
            .into_view(),
        step(
            "−5",
            "alarm-minute-minus-5",
            t("Five minutes earlier"),
            Tap::AlarmMinute(-5)
        ),
        step(
            "−1",
            "alarm-minute-minus",
            t("One minute earlier"),
            Tap::AlarmMinute(-1)
        ),
        step(
            "+1",
            "alarm-minute-plus",
            t("One minute later"),
            Tap::AlarmMinute(1)
        ),
        step(
            "+5",
            "alarm-minute-plus-5",
            t("Five minutes later"),
            Tap::AlarmMinute(5)
        ),
    ]);
    let note = if pinnacle_rt::clock() == 0 {
        t("The time of day is not known yet, so no alarm can ring.")
    } else {
        t("An alarm rings only while Clock is open, in front or not. Closed, it cannot ring.")
    };
    el("div")
        .attr(
            "style",
            "flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; \
             align-items: center; gap: 20px; padding-top: 24px",
        )
        .child(list)
        .child(new)
        .child(button(
            t("Add alarm"),
            "alarm-add",
            "primary",
            Tap::AlarmAdd,
            tapped,
        ))
        .child(
            el("p")
                .attr(
                    "style",
                    "margin: 0; max-width: 420px; color: var(--m-text-dim); text-align: center",
                )
                .child(note),
        )
        .into_view()
}

/// The page: the tabs along the top, what rings under them, and the tab
/// chosen filling the rest.
fn page(state: &State, face: &Face, tapped: &Signal<Option<Tap>>) -> View {
    let mut tabs = el("div").class("m-tabs__list").attr("role", "tablist");
    for (tab, name) in TABS {
        let tapped = tapped.clone();
        tabs = tabs.child(
            el("button")
                .class("m-tabs__tab")
                .attr("type", "button")
                .attr("role", "tab")
                .attr("aria-selected", if state.tab == tab { "true" } else { "false" })
                .attr("data-name", format!("tab-{name}"))
                .on("click", move |_| tapped.set(Some(Tap::Tab(tab))))
                .child(tab.label()),
        );
    }
    let mut main = el("main")
        .attr(
            "style",
            "height: 100vh; display: flex; flex-direction: column; gap: 12px; padding: 16px",
        )
        .child(
            el("div")
                .class("m-tabs")
                .attr("data-variant", "pill")
                .attr("style", "display: flex; justify-content: center")
                .child(tabs),
        );
    if let Some(ring) = &state.ringing {
        let what = match &ring.what {
            Rang::Timer => String::from(t("Time is up")),
            Rang::Alarm(time) => tf("Alarm {}", &[time]),
        };
        main = main.child(
            el("section")
                .attr("role", "alert")
                .attr(
                    "style",
                    "display: flex; align-items: center; justify-content: space-between; gap: 12px; \
                     padding: 12px 16px; border-radius: 16px; \
                     background: var(--m-accent); color: var(--m-on-accent)",
                )
                .child(el("span").attr("style", "font-size: 21px").child(what))
                .child(button(t("Stop"), "dismiss", "", Tap::Dismiss, tapped)),
        );
    }
    main.child(match state.tab {
        Tab::Clock => clock_tab(face),
        Tab::Alarm => alarm_tab(state, tapped),
        Tab::Timer => timer_tab(state, face, tapped),
        Tab::Stopwatch => stopwatch_tab(state, face, tapped),
    })
    .into_view()
}

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

#[unsafe(no_mangle)]
fn main(_argument: u64) -> u64 {
    let mut app = App::new("Clock");
    let mut screen = Screen::new(app.width, app.height);
    let face = Face {
        time: signal(String::new()),
        date: signal(String::new()),
        zone: signal(String::new()),
        watch: signal(String::new()),
        left: signal(String::new()),
    };
    let tapped: Signal<Option<Tap>> = signal(None);
    let mut state = State {
        tab: Tab::Clock,
        watch: Stopwatch::default(),
        timer: Timer::Set,
        length: fs::read_string(TIMER)
            .and_then(|s| s.trim().parse().ok())
            .map_or(5 * 60, |s: u64| s.min(TIMER_MAX)),
        alarms: load_alarms(),
        new_alarm: (7, 0),
        ringing: None,
        // An alarm for the minute Clock opens in has had its chance.
        looked: pinnacle_rt::clock() / 60,
    };
    let mut chosen = Chosen::read();
    // A channel to the display server for notifications, opened at the
    // first; and the speaker, open while something rings.
    let mut display: Option<Channel> = None;
    let mut speaker: Option<Player> = None;
    let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
    show(&face, &chosen, &state);
    screen.mount(page(&state, &face, &tapped));
    screen.draw(&mut app.canvas(), true);
    app.present_all();
    screen.announce("clock: button ");
    pinnacle_rt::println!(
        "clock: drawn, {} {}, {} alarms",
        face.time.get(),
        face.zone.get(),
        state.alarms.len()
    );
    let mut redraw = false;
    loop {
        if redraw {
            show(&face, &chosen, &state);
            screen.resize(app.width, app.height);
            screen.clear();
            screen.mount(page(&state, &face, &tapped));
            screen.draw(&mut app.canvas(), true);
            app.present_all();
            screen.announce("clock: button ");
            redraw = false;
        }
        let deadline = state.deadline(app.shown, pinnacle_rt::time());
        // While something rings, the speaker's reports come in too.
        let event = match &speaker {
            Some(p) => app.wait(&[p.channel()], &mut buffer, deadline),
            None => app.next_event(deadline),
        };
        match event {
            Event::Input(e) => {
                screen.input(&e);
                if let Some(tap) = take(&tapped) {
                    state.tap(tap, &mut speaker);
                    redraw = true;
                }
            }
            Event::Channel { len, .. } => {
                if let Some(speaker) = &mut speaker {
                    speaker.report(&buffer[..len]);
                }
            }
            Event::ChannelClosed { .. } => speaker = None,
            Event::Shown(true) | Event::Resized => {
                chosen = Chosen::read();
                redraw = true;
            }
            Event::Preferences => {
                screen.restyle();
                redraw = true;
            }
            Event::Closed => return 0,
            _ => {}
        }
        redraw |= state.tick(&mut chosen, app.shown, &mut display, &mut speaker);
        if app.shown && !redraw {
            show(&face, chosen.fresh(), &state);
            if let Some(area) = screen.draw(&mut app.canvas(), false) {
                app.present(area);
            }
        }
    }
}