diff --git a/apps/watch-music/Cargo.toml b/apps/watch-music/Cargo.toml
new file mode 100644
index 0000000..ff96b4f
--- /dev/null
+++ b/apps/watch-music/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "watch-music"
+edition.workspace = true
+license.workspace = true
+version.workspace = true
+
+[dependencies]
+cmf-wp2-app.workspace = true
+cmf-wp2-ui.workspace = true
+
+[dev-dependencies]
+wp2-core.workspace = true
+
+[[bin]]
+name = "watch-music"
+bench = false
diff --git a/apps/watch-music/icon.svg b/apps/watch-music/icon.svg
new file mode 100644
index 0000000..f16d3a4
--- /dev/null
+++ b/apps/watch-music/icon.svg
@@ -0,0 +1,19 @@
+
diff --git a/apps/watch-music/shots/control-media.png b/apps/watch-music/shots/control-media.png
new file mode 100644
index 0000000..483e4df
Binary files /dev/null and b/apps/watch-music/shots/control-media.png differ
diff --git a/apps/watch-music/shots/home.png b/apps/watch-music/shots/home.png
new file mode 100644
index 0000000..dc124e2
Binary files /dev/null and b/apps/watch-music/shots/home.png differ
diff --git a/apps/watch-music/shots/music-list.png b/apps/watch-music/shots/music-list.png
new file mode 100644
index 0000000..899de57
Binary files /dev/null and b/apps/watch-music/shots/music-list.png differ
diff --git a/apps/watch-music/shots/music-player.png b/apps/watch-music/shots/music-player.png
new file mode 100644
index 0000000..a8f2f08
Binary files /dev/null and b/apps/watch-music/shots/music-player.png differ
diff --git a/apps/watch-music/shots/podcasts.png b/apps/watch-music/shots/podcasts.png
new file mode 100644
index 0000000..edb3c4a
Binary files /dev/null and b/apps/watch-music/shots/podcasts.png differ
diff --git a/apps/watch-music/shots/saved-song.png b/apps/watch-music/shots/saved-song.png
new file mode 100644
index 0000000..f45194e
Binary files /dev/null and b/apps/watch-music/shots/saved-song.png differ
diff --git a/apps/watch-music/shots/volume.png b/apps/watch-music/shots/volume.png
new file mode 100644
index 0000000..8e613d8
Binary files /dev/null and b/apps/watch-music/shots/volume.png differ
diff --git a/apps/watch-music/src/main.rs b/apps/watch-music/src/main.rs
new file mode 100644
index 0000000..eb2f77d
--- /dev/null
+++ b/apps/watch-music/src/main.rs
@@ -0,0 +1,1667 @@
+//! Watch Music: the phone's Music, Podcasts, or Custom actions on the watch, in the stock look (ui-gallery widgets).
+//! A dynamic start screen shows only categories with saved entries; songs and shows are a focus list, and a tap opens
+//! the media-control player. Custom actions run on the phone, and Return to controls opens the active media session.
+//! In the player the volume button turns the crown into a volume control for 30 seconds. The message formats are
+//! listed at the top of model.rs.
+#![cfg_attr(any(target_os = "none", wp2_sim), no_main, cfg_attr(target_os = "none", no_std))]
+
+#[cfg_attr(not(any(target_os = "none", wp2_sim)), allow(dead_code))]
+mod model;
+#[cfg_attr(not(any(target_os = "none", wp2_sim)), allow(dead_code))]
+mod photo;
+#[cfg_attr(not(any(target_os = "none", wp2_sim)), allow(dead_code))]
+mod thumb;
+#[cfg(test)]
+mod photo_vectors;
+#[cfg_attr(not(any(target_os = "none", wp2_sim)), allow(dead_code))]
+mod screens;
+
+#[cfg(not(any(target_os = "none", wp2_sim)))]
+fn main() {}
+
+#[cfg(any(target_os = "none", wp2_sim))]
+mod device {
+ use crate::model::*;
+ use crate::photo::{self, Photos, Status};
+ use crate::thumb::{self, Thumbs};
+ use crate::screens::{self, Kind, Screen};
+ use cmf_wp2_app::lv::{Batch, FOCUSED, Lv, LvError, ROOT};
+ use cmf_wp2_app::{Api, BUTTON, CROWN, LV, MESSAGE, MSG_MAX, PAUSE, RESUME};
+ use cmf_wp2_ui::haptic::{DOUBLE, Motor, Pattern, TICK};
+
+ cmf_wp2_app::entry!(main);
+ cmf_wp2_app::app_icon!();
+ cmf_wp2_app::app_features!(cmf_wp2_app::PAGE);
+
+ const CLICKED: i16 = 7;
+ const LONG_PRESSED: i16 = 5;
+ /// two taps on the same half of the player within this time = a double tap (seek)
+ const DOUBLE_TAP_MS: u32 = 350;
+ /// how far a double tap seeks
+ const SEEK_S: i32 = 5;
+ /// after a long press (back), the tap that LVGL still sends on release is ignored for this long
+ const LONG_GUARD_MS: u32 = 900;
+ /// how soon the hello is sent again while the phone has not answered; each try waits twice as long, up to the max
+ /// (a steady 0.4 s flood made the phone answer every copy, and every answer rebuilt the screen)
+ const HELLO_MS: u32 = 400;
+ const HELLO_MAX_MS: u32 = 2000;
+ /// the phone can open or close a screen by itself (a lone category, the media controls) at most this often
+ const AUTO_GAP_MS: u32 = 4000;
+ /// how long a restore may take before the watch asks the phone for it again
+ const RESUME_MS: u32 = 2500;
+ /// taps on the start screen's rows are ignored this long after it appears
+ const TAP_GUARD_MS: u32 = 600;
+ /// the player looks at the clock this often while the song is paused
+ const IDLE_MS: u32 = 5000;
+ /// the volume stays on the crown this long after the last touch or turn
+ /// the soft tick of a list scroll
+ const SOFT: Pattern = Pattern::new(&[(170, 14), (0, 0)]);
+ /// at most one scroll tick this often, and none for this long after the screen or the phone changed something
+ const TICK_GAP_MS: u32 = 220;
+ const QUIET_MS: u32 = 900;
+ const VOL_MS: u32 = 1_000;
+ /// the tide is drawn as fast as the watch can, but not more often than this
+ const TIDE_MS: u32 = 33;
+ /// the volume goes to the phone at most this often while the crown turns (the last value is always sent)
+ const VOL_GAP_MS: u32 = 120;
+ /// A burst of native FOCUSED events is settled before its logical anchor is committed. Fast page swipes can
+ /// enqueue several intermediate centre rows; only the final stable row is retained.
+ const FOCUS_SETTLE_MS: u32 = 100;
+ /// Focus events queued by the screen being replaced must not be applied to the newly-created list (LVGL handles
+ /// are reused by the batch allocator).
+ const FOCUS_REBUILD_GUARD_MS: u32 = 80;
+
+ /// The list has to rest on a song this long before its cover picture is asked for (scrolling past asks for nothing).
+ const THUMB_DELAY_MS: u32 = 10;
+ /// A picture that has not come after this long is asked for again.
+ const THUMB_RETRY_MS: u32 = 1200; // a lost piece used to leave the pulse up for 4 s
+ /// While a cover loads, a rounded square pulses in its place: one full fade in and out takes this long,
+ /// redrawn this often.
+ const PULSE_PERIOD_MS: u32 = 1600;
+ const PULSE_MS: u32 = 100;
+ /// A crown click on the list takes the picture off at once, and no picture comes back for this long after the
+ /// last click (the list's own "new centre row" report arrives later than the crown event).
+ const CROWN_HOLD_MS: u32 = 250;
+
+ static mut MODEL: Model = Model::new();
+ static mut STORE: [u8; 2560] = [0; 2560];
+ static mut PHOTOS: Photos = Photos::new();
+ /// Block pictures, for a watch whose App Loader cannot draw real ones.
+ static mut THUMBS: Thumbs = Thumbs::new();
+ static mut PHOTO_WORK: photo::Work = photo::Work::new();
+ /// The pixels of the real picture on show; an LVGL image draws them in place.
+ static mut PHOTO_PX: [u16; photo::PIXELS] = [0; photo::PIXELS];
+
+ // ---- music on the watch's speaker ----
+ /// three presses of the speaker button, each no later than this after the one before
+ const SPK_TAP_GAP_MS: u32 = 500;
+ /// after the request the phone has this long to start (it may ask for a screen-capture permission)
+ const SPK_WAIT_MS: u32 = 25_000;
+ /// one ADPCM block of 122 code bytes decodes to this many bytes of 16-bit PCM (244 samples)
+ const SPK_BLOCK: usize = 488;
+ /// a block as it arrives: 3 header bytes and 122 code bytes
+ const SPK_COMP: usize = 125;
+ /// blocks kept (about 30 ms each, so about 1.5 s of sound) while the speaker's own queue is full; kept packed
+ const SPK_SLOTS: usize = 48;
+ /// the sound starts once this many blocks are here (about 1 s), and after it ran dry once this many: a slow
+ /// moment on the link is then not heard
+ const SPK_PRIME_FIRST: u8 = 32;
+ const SPK_PRIME_AGAIN: u8 = 24;
+ /// how soon the loop looks again while decoded sound waits for room in the speaker's queue
+ const SPK_PUMP_MS: u32 = 8;
+ /// the decoded sound; `audio_write` needs it to be a `static`
+ static mut SPK_RING: [[u8; SPK_COMP]; SPK_SLOTS] = [[0; SPK_COMP]; SPK_SLOTS];
+ static mut SPK_LEN: [u8; SPK_SLOTS] = [0; SPK_SLOTS];
+ /// the block being played, decoded
+ static mut SPK_PCM: [u8; SPK_BLOCK] = [0; SPK_BLOCK];
+
+ // The speaker through the loader's AUDIO record (docs/abi-1.4.md, "Audio"). The SDK this app is built with has no
+ // methods for it, so the records are sent here, the way the SDK's own `audio_*` methods do. The buffers are
+ // statics: the loader reads only inside the app block. Each returns the loader's answer (0 / bytes taken / <0).
+ const PTR: usize = core::mem::size_of::();
+ static mut SPK_REC: [u8; 6] = [0x18, 2, 0, 0, 1, 0];
+ static SPK_CLOSE: [u8; 5] = [0x18, 1, 0, 0, 3];
+ static mut SPK_WRITE: [u8; 9 + PTR] = [0; 9 + PTR];
+
+ fn audio_open(api: &Api, khz: u8) -> i32 {
+ let buf = unsafe { &mut *&raw mut SPK_REC };
+ buf[..5].copy_from_slice(&[0x18, 2, 0, 0, 1]);
+ buf[5] = khz;
+ (api.lv_submit)(buf.as_ptr(), buf.len())
+ }
+
+ fn audio_volume(api: &Api, percent: u8) -> i32 {
+ let buf = unsafe { &mut *&raw mut SPK_REC };
+ buf[..5].copy_from_slice(&[0x18, 2, 0, 0, 4]);
+ buf[5] = percent.min(100);
+ (api.lv_submit)(buf.as_ptr(), buf.len())
+ }
+
+ fn audio_close(api: &Api) -> i32 {
+ (api.lv_submit)(SPK_CLOSE.as_ptr(), SPK_CLOSE.len())
+ }
+
+ /// `pcm` (16-bit mono, an even length) must lie in a `static`. Returns the bytes taken, 0 when the queue is full.
+ fn audio_write(api: &Api, pcm: &[u8]) -> i32 {
+ let buf = unsafe { &mut *&raw mut SPK_WRITE };
+ buf[..5].copy_from_slice(&[0x18, (5 + PTR) as u8, 0, 0, 2]);
+ buf[5..5 + PTR].copy_from_slice(&(pcm.as_ptr() as usize).to_le_bytes());
+ buf[5 + PTR..].copy_from_slice(&(pcm.len() as u32).to_le_bytes());
+ (api.lv_submit)(buf.as_ptr(), buf.len())
+ }
+
+ fn after(now: u32, t: u32) -> bool {
+ (now.wrapping_sub(t) as i32) >= 0
+ }
+
+ #[allow(dead_code)]
+ struct App {
+ api: &'static Api,
+ lv: Lv,
+ b: Batch,
+ s: Screen,
+ motor: Motor,
+ m: &'static mut Model,
+ /// when the phone's progress (`pos`) was received
+ prog_at: u32,
+ /// what the ring and the clock show now (so nothing is sent to the screen when they did not change)
+ last_pct: i32,
+ last_min: u16,
+ /// true when this app instance is running as a page beside the watch face
+ page: bool,
+ /// the phone has answered the last hello (no more hellos until PAUSE or a new choice)
+ heard: bool,
+ /// the tide of the player background: asleep while the page is paused, next frame's time
+ paused: bool,
+ tide_next: u32,
+ /// the light of the player background
+ glow: screens::Glow,
+ next_hello: u32,
+ /// identifies one logical hello exchange; retries keep this ID, a new exchange gets a new ID
+ hello_id: u32,
+ /// when to ask again for a restore that has not arrived (0 = none pending)
+ resume_at: u32,
+ /// a tap on a start-screen row is ignored until then (a second tap on Back must not land on a row)
+ tap_guard: u32,
+ /// the phone has answered the last start-screen hello with its catalog
+ got_catalog: bool,
+ /// the volume is on the crown until this time (`None`: it is not)
+ vol_until: Option,
+ quiet_until: u32,
+ last_tick: u32,
+ /// checksum of the list last written to flash (0: none yet this run)
+ saved_sum: u32,
+ /// a crown turn has not been sent to the phone yet
+ vol_dirty: bool,
+ vol_sent_at: u32,
+ /// the last crown turn: the phone's echo of our own change is ignored for a moment
+ vol_local_at: u32,
+ /// logical row currently centred in Home/Menu; page mode includes Back as index 0
+ menu_anchor: usize,
+ /// The latest valid native FOCUSED row, committed only after a short quiet period so fast swipes settle cleanly.
+ pending_focus_row: i16,
+ pending_focus_handle: u16,
+ pending_focus_at: u32,
+ /// Do not accept native FOCUSED events immediately after rebuilding a page; queued events can belong to its predecessor.
+ focus_accept_at: u32,
+ /// true only until the first phone response on a fresh app launch. This lets the phone restore
+ /// a Watch Music song/podcast without confusing a deliberate return to Home with a relaunch.
+ fresh_launch: bool,
+ /// A phone-restored Music/Podcast row; open its track-specific player after the list arrives.
+ resume_player: Option,
+ /// RESUME started a new player-page handshake; the phone may restore a different live row.
+ resume_request_pending: bool,
+ /// true only until the first category catalog is received for a fresh app launch
+ auto_pick_pending: bool,
+ /// when the phone last moved the watch to another screen by itself (`None`: not yet)
+ auto_at: Option,
+ /// how many hellos went out since the last answer (the gap between them grows)
+ hello_tries: u8,
+ /// what the screen on show was built from: the category flags, the list, and whether Wait said "nothing"
+ home_built: u8,
+ menu_fp: u32,
+ wait_empty: bool,
+ /// the half of the player tapped last (its handle) and when, for the double tap
+ last_tap_zone: u16,
+ last_tap_at: u32,
+ /// taps are ignored until this time after a long press went back
+ long_guard: u32,
+ /// the real pictures held (compressed), and the unpacker's working memory
+ photos: &'static mut Photos,
+ thumbs: &'static mut Thumbs,
+ /// The loader refused a real picture: covers are asked for as blocks from then on.
+ blocks: bool,
+ work: &'static mut photo::Work,
+ /// of the real picture on show: how many bytes and pixel groups are drawn, and which version it is
+ drawn_version: (u16, bool),
+ /// the list the pictures belong to (its fingerprint); another list empties them
+ thumbs_fp: u32,
+ /// the song the list is resting on (`NONE`: none, or still scrolling)
+ thumb_want: u8,
+ /// when its picture is asked for (0: not waiting to ask), and when a picture that has not come is asked for again
+ thumb_ask_at: u32,
+ thumb_retry_at: u32,
+ /// speaker music: 0 off, 1 asked (waiting for the phone), 2 playing
+ spk_state: u8,
+ /// while asked: when to give up waiting for the phone
+ spk_until: u32,
+ /// the oldest block in `SPK_RING`, how many are in it, and how many bytes of the oldest were taken already
+ spk_head: u8,
+ spk_count: u8,
+ spk_off: u16,
+ /// enough blocks came to start the sound
+ spk_primed: bool,
+ /// the sound started once already (after a dry spell it waits for fewer blocks)
+ spk_started: bool,
+ /// bytes in `SPK_PCM` (the block being played); `spk_off` of them are taken
+ spk_pcm: u16,
+ /// the quick presses of the speaker button
+ spk_taps: MultiTap,
+ /// no cover picture (or pulse) until this time: the crown is turning the list (0: no hold)
+ crown_hold_until: u32,
+ /// when the pulse on show started, and when it is redrawn next
+ pulse_start: u32,
+ pulse_next: u32,
+ }
+
+ impl App {
+ fn flush(&mut self) -> Result<(), LvError> {
+ self.b.submit(&self.lv)
+ }
+
+ fn clock(&self, buf: &mut [u8; 5]) -> u16 {
+ match self.api.time() {
+ Some(t) => {
+ screens::clock_text(t.hour, t.minute, buf);
+ t.hour as u16 * 60 + t.minute as u16
+ }
+ None => {
+ *buf = *b"--:--";
+ u16::MAX
+ }
+ }
+ }
+
+ /// Replaces the screen by the one of `kind`, built from the model.
+ fn go(&mut self, kind: Kind) {
+ self.vol_flush(true);
+ self.vol_until = None;
+ // `Batch` reuses freed LVGL handles. A FOCUSED event from the old screen can therefore carry the same
+ // handle as the new one. Clear the pending row and briefly reject queued focus events after each rebuild.
+ self.pending_focus_row = -1;
+ self.pending_focus_handle = 0;
+ self.focus_accept_at = self.api.now().wrapping_add(FOCUS_REBUILD_GUARD_MS);
+ if kind == Kind::Home {
+ self.tap_guard = self.api.now().wrapping_add(TAP_GUARD_MS);
+ }
+ self.quiet_until = self.api.now().wrapping_add(QUIET_MS);
+ let mut clock = [0u8; 5];
+ let min = self.clock(&mut clock);
+ let App { b, lv, s, m, page, menu_anchor, .. } = self;
+ let mut flush = |b: &mut Batch| b.submit(lv);
+ let text = core::str::from_utf8(&clock).unwrap_or("");
+ let r = screens::leave(b, s).and_then(|_| match kind {
+ Kind::Wait => screens::wait(b, &mut flush, m.mode, m.empty, *page),
+ Kind::Home => screens::home(b, &mut flush, m.home_flags, *menu_anchor),
+ Kind::Menu => {
+ // The list always starts in its natural order (Back, then the songs from the first). Starting it
+ // at the row last chosen put every row before it, and the Back arrow, at the end of the list.
+ *menu_anchor = 0;
+ screens::menu(b, &mut flush, m, *page, 0)
+ }
+ Kind::Player => screens::player(b, &mut flush, m, text, *page),
+ });
+ if let Ok(next) = r {
+ *s = next;
+ let _ = self.flush();
+ }
+ self.home_built = self.m.home_flags & 0x0F;
+ self.menu_fp = self.m.fingerprint();
+ self.wait_empty = self.m.empty;
+ // the new screen has no cover picture; another list means other songs' pictures
+ self.thumb_want = NONE;
+ self.thumb_ask_at = 0;
+ self.thumb_retry_at = 0;
+ if kind == Kind::Menu && self.thumbs_fp != self.menu_fp {
+ self.photos.clear();
+ self.thumbs.clear();
+ self.thumbs_fp = self.menu_fp;
+ }
+ if kind == Kind::Player {
+ self.glow.start(self.api.now());
+ self.tide_next = self.api.now();
+ self.last_min = min;
+ self.refresh(true);
+ }
+ }
+
+ fn since(&self) -> u32 {
+ self.api.now().wrapping_sub(self.prog_at)
+ }
+
+ /// The ring (when its percent changed) and the clock (when the minute changed), in one batch.
+ fn refresh(&mut self, force: bool) {
+ if self.s.kind != Kind::Player {
+ return;
+ }
+ let mut dirty = false;
+ let secs = self.m.elapsed(self.since());
+ let pct = permille(secs, self.m.dur) / 10;
+ if force || pct != self.last_pct {
+ self.last_pct = pct;
+ dirty |= screens::show_progress(&mut self.b, &self.s, pct).is_ok();
+ }
+ let mut clock = [0u8; 5];
+ let min = self.clock(&mut clock);
+ if min != self.last_min {
+ self.last_min = min;
+ let text = core::str::from_utf8(&clock).unwrap_or("");
+ dirty |= screens::show_clock(&mut self.b, &self.s, text).is_ok();
+ }
+ if dirty {
+ let _ = self.flush();
+ }
+ }
+
+ /// The song, the artist, play / pause and the tint, after the model changed.
+ fn redraw_now(&mut self) {
+ let _ = screens::show_now(&mut self.b, &self.s, self.m);
+ let _ = self.flush();
+ }
+
+ fn send(&self, data: &[u8]) {
+ self.api.send(data);
+ }
+
+ // ---- music on the watch's speaker ----
+
+ /// Three quick presses of the speaker button: start the phone's music on the watch's speaker, or stop it.
+ fn spk_toggle(&mut self) {
+ if self.spk_state == 0 {
+ self.spk_state = 1;
+ self.spk_until = self.api.now().wrapping_add(SPK_WAIT_MS);
+ self.motor.play(DOUBLE);
+ self.send(&[b'e', 1]);
+ } else {
+ self.spk_stop(true);
+ }
+ }
+
+ /// Closes the speaker and forgets what waited for it; `tell`: the phone stops sending too.
+ fn spk_stop(&mut self, tell: bool) {
+ if self.spk_state == 2 {
+ let _ = audio_close(self.api);
+ }
+ let was = self.spk_state;
+ self.spk_state = 0;
+ self.spk_head = 0;
+ self.spk_count = 0;
+ self.spk_off = 0;
+ self.spk_primed = false;
+ self.spk_started = false;
+ self.spk_pcm = 0;
+ if tell {
+ self.send(&[b'e', 0]);
+ }
+ if was != 0 {
+ self.motor.play(TICK);
+ }
+ }
+
+ /// `o khz`: the phone is ready and the speaker opens.
+ fn spk_open(&mut self, msg: &[u8]) {
+ if self.spk_state == 0 {
+ // nobody here asked for it (an old request): tell the phone to stop
+ self.send(&[b'e', 0]);
+ return;
+ }
+ let khz = if msg.len() >= 2 { msg[1] } else { 8 };
+ if audio_open(self.api, khz) != 0 {
+ self.spk_stop(true);
+ return;
+ }
+ let _ = audio_volume(self.api, 100);
+ self.spk_state = 2;
+ self.spk_head = 0;
+ self.spk_count = 0;
+ self.spk_off = 0;
+ self.spk_primed = false;
+ self.spk_started = false;
+ self.spk_pcm = 0;
+ }
+
+ /// `d seq:u16 block`: one block of the stream goes into the ring, still packed.
+ fn spk_data(&mut self, msg: &[u8]) {
+ if self.spk_state != 2 || msg.len() < 7 || self.spk_count as usize >= SPK_SLOTS {
+ return;
+ }
+ let block = &msg[3..];
+ if block.len() > SPK_COMP {
+ return;
+ }
+ let slot = (self.spk_head as usize + self.spk_count as usize) % SPK_SLOTS;
+ let ring = unsafe { &mut *&raw mut SPK_RING };
+ let lens = unsafe { &mut *&raw mut SPK_LEN };
+ ring[slot][..block.len()].copy_from_slice(block);
+ lens[slot] = block.len() as u8;
+ self.spk_count += 1;
+ }
+
+ /// Gives the speaker the sound while its queue has room (called every turn of the loop): the next block is
+ /// decoded when the one before it is all taken. A dry ring waits for a fresh supply before it goes on.
+ fn spk_pump(&mut self) {
+ if self.spk_state != 2 {
+ return;
+ }
+ if !self.spk_primed {
+ let need = if self.spk_started { SPK_PRIME_AGAIN } else { SPK_PRIME_FIRST };
+ if self.spk_count < need {
+ return;
+ }
+ self.spk_primed = true;
+ self.spk_started = true;
+ }
+ let ring = unsafe { &*&raw const SPK_RING };
+ let lens = unsafe { &*&raw const SPK_LEN };
+ let pcm = unsafe { &mut *&raw mut SPK_PCM };
+ loop {
+ if self.spk_off >= self.spk_pcm {
+ if self.spk_count == 0 {
+ self.spk_primed = false;
+ return;
+ }
+ let h = self.spk_head as usize;
+ let n = ima_decode_block(&ring[h][..lens[h] as usize], pcm);
+ self.spk_head = ((h + 1) % SPK_SLOTS) as u8;
+ self.spk_count -= 1;
+ self.spk_off = 0;
+ self.spk_pcm = n as u16;
+ if n == 0 {
+ continue;
+ }
+ }
+ let off = self.spk_off as usize;
+ let len = self.spk_pcm as usize;
+ let n = audio_write(self.api, &pcm[off..len]);
+ if n < 0 {
+ self.spk_stop(true);
+ return;
+ }
+ let n = (n as usize) & !1;
+ if n == 0 {
+ return; // the speaker's queue is full: try again shortly
+ }
+ self.spk_off = (off + n).min(len) as u16;
+ }
+ }
+
+ /// The phone did not start the stream in time: back to normal.
+ fn spk_watch(&mut self) {
+ if self.spk_state == 1 && after(self.api.now(), self.spk_until) {
+ self.spk_stop(true);
+ }
+ }
+
+ /// Tells the phone what the watch shows (count and version of its list, and the mode). The fifth byte marks
+ /// only the first, untouched hello after a cold launch; the sixth marks a paused track-specific player page.
+ /// These let the phone restore the last watch-selected song/show instead of opening a generic media controller.
+ /// Repeated until the phone answers.
+ fn hello(&mut self) {
+ let player_resume = self.s.kind == Kind::Player
+ && (self.m.mode == MODE_MUSIC || self.m.mode == MODE_PODCAST)
+ && self.m.now != NONE;
+ let id = self.hello_id.to_le_bytes();
+ self.send(&[
+ b'h', self.m.count, self.m.version, self.m.mode,
+ if self.fresh_launch { 1 } else { 0 },
+ if player_resume { 1 } else { 0 },
+ id[0], id[1], id[2], id[3],
+ ]);
+ self.heard = false;
+ let gap = (HELLO_MS << self.hello_tries.min(3)).min(HELLO_MAX_MS);
+ self.hello_tries = self.hello_tries.saturating_add(1);
+ self.next_hello = self.api.now().wrapping_add(gap);
+ }
+
+ /// A new question to the phone (not a retry): the gaps start short again.
+ fn hello_now(&mut self) {
+ // A new question is a new exchange. All retries inside hello() retain this ID so the phone can
+ // collapse the queued copies into one response instead of replaying a complete restoration.
+ self.hello_id = self.hello_id.wrapping_add(1);
+ if self.hello_id == 0 { self.hello_id = 1; }
+ self.hello_tries = 0;
+ self.hello();
+ }
+
+ /// The start screen's choice: the list of that mode, the saved one at once for music.
+ fn pick(&mut self, mode: u8) {
+ self.fresh_launch = false;
+ self.resume_player = None;
+ self.auto_pick_pending = false;
+ self.menu_anchor = 0;
+ self.m.pick(mode);
+ if mode == MODE_MUSIC {
+ let buf = unsafe { &mut *&raw mut STORE };
+ let n = self.api.load(buf);
+ if n > 0 {
+ self.m.load(&buf[..n as usize]);
+ }
+ }
+ self.go(if self.m.count > 0 { Kind::Menu } else { Kind::Wait });
+ self.hello_now();
+ }
+
+ /// Back to the start screen.
+ fn home(&mut self) {
+ // A deliberate Back should show the selector even if only one category exists; it must not trigger
+ // the cold-launch resume path on the next hello.
+ self.fresh_launch = false;
+ self.resume_player = None;
+ self.auto_pick_pending = false;
+ self.menu_anchor = 0;
+ self.m.pick(MODE_NONE);
+ self.got_catalog = false;
+ self.go(Kind::Home);
+ self.hello_now();
+ }
+
+ /// The phone sent the set of categories with real content.
+ /// The same set again changes nothing on screen, so nothing is rebuilt: a rebuild throws the list back to the
+ /// top, blanks the icons for a moment and moves the Back arrow (that was the twitching). The phone moves the
+ /// watch by itself only until the first choice, and not more often than `AUTO_GAP_MS`; the controls stay open
+ /// while they are open, because the media session comes and goes with every pause (that was the flicker).
+ fn home_catalog(&mut self, refreshed: bool) {
+ self.got_catalog = true;
+ let flags = self.m.home_flags;
+ let shown = flags & 0x0F;
+ let now = self.api.now();
+ let calm = self.auto_at.map_or(true, |t| now.wrapping_sub(t) >= AUTO_GAP_MS);
+ if self.s.kind == Kind::Home {
+ // Cold launch while something plays: straight to its controls, no start screen in between.
+ if flags & 0x10 != 0 && !refreshed && flags & 0x08 != 0 && calm {
+ self.auto_pick_pending = false;
+ self.auto_at = Some(now);
+ self.return_to_controls();
+ return;
+ }
+ if shown == self.home_built {
+ return;
+ }
+ self.menu_anchor = 0;
+ if refreshed {
+ self.auto_pick_pending = true;
+ }
+ if self.auto_pick_pending && calm {
+ let mut only = MODE_NONE;
+ let mut count = 0usize;
+ for (mode, bit) in [(MODE_MUSIC, 0x01), (MODE_PODCAST, 0x02), (MODE_CUSTOM, 0x04)] {
+ if flags & bit != 0 { only = mode; count += 1; }
+ }
+ if count == 1 {
+ self.auto_at = Some(now);
+ self.pick(only);
+ return;
+ }
+ if count == 0 && flags & 0x08 != 0 {
+ self.auto_pick_pending = false;
+ self.auto_at = Some(now);
+ self.return_to_controls();
+ return;
+ }
+ }
+ self.go(Kind::Home);
+ return;
+ }
+ let available = match self.m.mode {
+ MODE_MUSIC => flags & 0x01 != 0,
+ MODE_PODCAST => flags & 0x02 != 0,
+ MODE_CUSTOM => flags & 0x04 != 0,
+ // The controls stay while they are open. Back leaves them.
+ MODE_EXTERNAL => true,
+ _ => true,
+ };
+ if !available {
+ self.m.pick(MODE_NONE);
+ self.menu_anchor = 0;
+ // Home stays: no automatic jump into another screen from here.
+ self.auto_pick_pending = false;
+ self.go(Kind::Home);
+ self.hello_now();
+ }
+ }
+
+ /// Opens the controls for whatever media session Android currently considers active.
+ /// The phone returns the live title, artist, state and progress; this is not a playlist pick.
+ fn return_to_controls(&mut self) {
+ self.fresh_launch = false;
+ self.resume_player = None;
+ self.m.pick(MODE_EXTERNAL);
+ self.m.count = 1;
+ self.m.now = 0;
+ self.m.playing = false;
+ self.m.pos = 0;
+ self.m.dur = 0;
+ self.go(Kind::Player);
+ // Mode 2 uses the existing hello/retry handshake, so a dropped request is retried.
+ self.hello_now();
+ }
+
+ // ---- the volume on the crown ----
+
+ /// Sends the last crown turn to the phone (now, or when the gap since the last send has passed).
+ fn vol_flush(&mut self, force: bool) {
+ if !self.vol_dirty {
+ return;
+ }
+ let now = self.api.now();
+ if force || now.wrapping_sub(self.vol_sent_at) >= VOL_GAP_MS {
+ self.send(&[b'v', self.m.level]);
+ self.vol_sent_at = now;
+ self.vol_dirty = false;
+ }
+ }
+
+ /// The button, the "Vol 65%" text and the sound wave follow the state.
+ fn vol_show(&mut self) {
+ let on = self.vol_until.is_some();
+ let _ = screens::show_volume(&mut self.b, &self.s, on, self.m.level, self.m.muted);
+ let _ = self.flush();
+ }
+
+ /// A press on the volume button: the crown is the volume for 30 s, or it is not any more.
+ fn vol_toggle(&mut self) {
+ if self.vol_until.is_some() {
+ self.vol_flush(true);
+ self.vol_until = None;
+ } else {
+ self.vol_until = Some(self.api.now().wrapping_add(VOL_MS));
+ }
+ self.vol_show();
+ }
+
+ /// One crown click while the volume is on.
+ fn crown(&mut self, delta: i16) {
+ if delta != 0 { self.fresh_launch = false; }
+ if delta != 0 && self.s.kind == Kind::Menu {
+ self.crown_scroll();
+ return;
+ }
+ if self.s.kind != Kind::Player || self.vol_until.is_none() || delta == 0 {
+ return;
+ }
+ let now = self.api.now();
+ self.vol_until = Some(now.wrapping_add(VOL_MS));
+ self.vol_local_at = now;
+ let level = step_volume(self.m.level, delta);
+ if level != self.m.level {
+ self.m.level = level;
+ self.vol_dirty = true;
+ self.vol_flush(false);
+ }
+ self.vol_show();
+ }
+
+ /// The crown is scrolling the list: the picture and the pulse go at once, before the list starts to move
+ /// (each picture is many small objects that would otherwise have to move with the row), and stay away
+ /// until the crown has been still for a moment.
+ fn crown_scroll(&mut self) {
+ let now = self.api.now();
+ self.crown_hold_until = now.wrapping_add(CROWN_HOLD_MS) | 1;
+ if self.s.thumb == ROOT && self.s.pulse == ROOT {
+ return;
+ }
+ let App { b, s, .. } = self;
+ let a = screens::hide_thumb(b, s);
+ let p = screens::hide_pulse(b, s);
+ if a.is_ok() || p.is_ok() {
+ let _ = self.flush();
+ }
+ }
+
+ fn crown_holding(&self) -> bool {
+ self.crown_hold_until != 0 && !after(self.api.now(), self.crown_hold_until)
+ }
+
+ /// Every turn of the loop: a held-back volume goes out, and the 30 s end.
+ fn vol_tick(&mut self) {
+ self.vol_flush(false);
+ if let Some(t) = self.vol_until {
+ if after(self.api.now(), t) {
+ self.vol_flush(true);
+ self.vol_until = None;
+ self.vol_show();
+ }
+ }
+ }
+
+ /// How long the loop may sleep for the volume (the end of the 30 s, a held-back send).
+ fn vol_wait(&self) -> Option {
+ let now = self.api.now();
+ let mut w = self.vol_until.map(|t| (t.wrapping_sub(now) as i32).max(0) as u32);
+ if self.vol_dirty {
+ let d = VOL_GAP_MS.saturating_sub(now.wrapping_sub(self.vol_sent_at));
+ w = Some(w.map_or(d, |x| x.min(d)));
+ }
+ w
+ }
+
+ fn save(&mut self) {
+ let buf = unsafe { &mut *&raw mut STORE };
+ let n = self.m.save(buf);
+ // The phone sends the same list after every hello. Writing it again is a flash write that stalls the
+ // loop (and scrolling with it) for nothing, so an identical list is not saved twice.
+ let sum = buf[..n].iter().fold(0x811c_9dc5u32, |h, &x| (h ^ x as u32).wrapping_mul(0x0100_0193)) | 1;
+ if sum == self.saved_sum {
+ return;
+ }
+ self.saved_sum = sum;
+ self.api.save(&buf[..n]);
+ }
+
+ /// One phone message.
+ /// A scroll tick for a new centre row: soft, sparse, and never while nothing is being scrolled.
+ /// `focus_obj` must be the current focus-page handle. The SDK reports the index in the rendered child order;
+ /// the current screen's list_anchor converts that order back to the stable logical row.
+ fn focus_tick(&mut self, focus_obj: u16, focused_row: i16) {
+ if !matches!(self.s.kind, Kind::Home | Kind::Menu)
+ || focus_obj != self.s.page.0
+ || !after(self.api.now(), self.focus_accept_at)
+ {
+ return;
+ }
+ let total = match self.s.kind {
+ Kind::Home => self.s.home_count as usize,
+ Kind::Menu => self.m.count as usize + if self.page { 1 } else { 0 },
+ _ => 0,
+ };
+ // Do not modulo an invalid/stale index into a valid row. That was able to turn an old list's last row
+ // into the new list's first/last choice after a fast swipe or a page rebuild.
+ let Some(anchor) = screens::focused_anchor(self.s.list_anchor, focused_row, total) else {
+ return;
+ };
+ // the rows coming into view get their texts at once, while the list still moves
+ if self.s.kind == Kind::Menu {
+ // A real move: take the cover picture (and pulse) off FIRST. The picture is ~100 objects; while it
+ // was still there the new rows' texts could not be created (the watch's object limit) and those
+ // songs showed up blank until a later scroll event.
+ if anchor != self.menu_anchor || self.pending_focus_row >= 0 {
+ let App { b, s, .. } = self;
+ let had = s.thumb != ROOT || s.pulse != ROOT;
+ let _ = screens::hide_thumb(b, s);
+ let _ = screens::hide_pulse(b, s);
+ if had {
+ let _ = self.flush();
+ }
+ }
+ let slot = if self.page { anchor.saturating_sub(1) } else { anchor };
+ let App { b, lv, s, m, .. } = self;
+ let mut flush = |b: &mut Batch| b.submit(lv);
+ if let Ok(true) = screens::labels_around(b, &mut flush, s, m, slot) {
+ let _ = self.flush();
+ }
+ }
+ // A changed centre row is a real user navigation action; do not let a delayed cold-launch
+ // restore replace a menu the user has already started browsing.
+ if anchor != self.menu_anchor {
+ self.fresh_launch = false;
+ }
+ let now = self.api.now();
+ // The list announcing the row it already rests on (as it may when a row gets a cover picture) is not a
+ // scroll: it must not take the picture off again.
+ if anchor != self.menu_anchor || self.pending_focus_row >= 0 {
+ self.pending_focus_row = focused_row;
+ self.pending_focus_handle = focus_obj;
+ self.pending_focus_at = now;
+ }
+ if !after(now, self.quiet_until) || now.wrapping_sub(self.last_tick) < TICK_GAP_MS {
+ return;
+ }
+ self.last_tick = now;
+ self.motor.play(SOFT);
+ }
+
+ /// Commit the last valid native focus event after the on-watch scroll has settled.
+ fn commit_focus(&mut self, force: bool) {
+ if self.pending_focus_row < 0 {
+ return;
+ }
+ let now = self.api.now();
+ if !force && now.wrapping_sub(self.pending_focus_at) < FOCUS_SETTLE_MS {
+ return;
+ }
+ let total = match self.s.kind {
+ Kind::Home => self.s.home_count as usize,
+ Kind::Menu => self.m.count as usize + if self.page { 1 } else { 0 },
+ _ => 0,
+ };
+ if self.pending_focus_handle == self.s.page.0 {
+ if let Some(anchor) = screens::focused_anchor(self.s.list_anchor, self.pending_focus_row, total) {
+ self.menu_anchor = anchor;
+ }
+ }
+ self.pending_focus_row = -1;
+ self.pending_focus_handle = 0;
+ }
+
+ /// The song of the row the Music / Podcast list rests on: not while it still scrolls, not Back, not Custom.
+ fn focused_track(&self) -> Option {
+ if self.s.kind != Kind::Menu
+ || self.pending_focus_row >= 0
+ || self.crown_holding()
+ || !(self.m.mode == MODE_MUSIC || self.m.mode == MODE_PODCAST)
+ {
+ return None;
+ }
+ let total = self.m.count as usize + if self.page { 1 } else { 0 };
+ if total == 0 {
+ return None;
+ }
+ let logical = self.menu_anchor % total;
+ let idx = if self.page {
+ if logical == 0 {
+ return None;
+ }
+ logical - 1
+ } else {
+ logical
+ };
+ if idx < self.m.count as usize { Some(idx as u8) } else { None }
+ }
+
+ /// The cover picture of the song the list rests on: taken off a row the list has left, asked for from the
+ /// phone a moment after the list stopped (so scrolling past songs asks for nothing), drawn once it is here.
+ fn thumb_tick(&mut self) {
+ if self.crown_hold_until != 0 && !self.crown_holding() {
+ self.crown_hold_until = 0;
+ }
+ self.thumb_logic();
+ self.pulse_sync();
+ }
+
+ /// The pulsing square: on show while the cover of the row the list rests on is being fetched, gone the moment
+ /// the list moves, the picture arrives, or the song turns out to have no cover.
+ fn pulse_sync(&mut self) {
+ let now = self.api.now();
+ let mut desired: Option = None;
+ if self.s.thumb == ROOT {
+ if let Some(idx) = self.focused_track() {
+ if matches!(self.picture_status(idx), Status::Unknown | Status::Waiting) {
+ let count = self.s.row_count as usize;
+ desired = (0..count).find(|&k| self.s.row_indices[k] == idx);
+ }
+ }
+ }
+ if self.s.pulse != ROOT && desired != Some(self.s.pulse_slot as usize) {
+ let App { b, s, .. } = self;
+ if screens::hide_pulse(b, s).is_ok() {
+ let _ = self.flush();
+ }
+ }
+ if let Some(slot) = desired {
+ if self.s.pulse == ROOT {
+ let App { b, lv, s, .. } = self;
+ let mut flush = |b: &mut Batch| b.submit(lv);
+ if screens::show_pulse(b, &mut flush, s, slot).is_err() {
+ let _ = screens::hide_pulse(b, s);
+ }
+ let _ = self.flush();
+ self.pulse_start = now;
+ self.pulse_next = now.wrapping_add(PULSE_MS);
+ return;
+ }
+ }
+ if self.s.pulse != ROOT && after(now, self.pulse_next) {
+ // a triangle wave: brighter for half the period, then dimmer (starts dim)
+ let half = PULSE_PERIOD_MS / 2;
+ let phase = now.wrapping_sub(self.pulse_start) % PULSE_PERIOD_MS;
+ let tri = if phase < half { phase } else { PULSE_PERIOD_MS - phase };
+ let span = (screens::PULSE_OPA_MAX - screens::PULSE_OPA_MIN) as u32;
+ let opa = screens::PULSE_OPA_MIN + (span * tri / half) as i32;
+ if screens::pulse_level(&mut self.b, &self.s, opa).is_ok() {
+ let _ = self.flush();
+ }
+ self.pulse_next = now.wrapping_add(PULSE_MS);
+ }
+ }
+
+ fn thumb_logic(&mut self) {
+ let now = self.api.now();
+ let want = self.focused_track();
+ if self.s.thumb != ROOT {
+ let shown = self.s.row_indices[self.s.thumb_slot as usize];
+ if want != Some(shown) {
+ let App { b, s, .. } = self;
+ if screens::hide_thumb(b, s).is_ok() {
+ let _ = self.flush();
+ }
+ }
+ }
+ let Some(idx) = want else {
+ self.thumb_want = NONE;
+ self.thumb_ask_at = 0;
+ self.thumb_retry_at = 0;
+ return;
+ };
+ if self.thumb_want != idx {
+ // a picture left half-way keeps what arrived (its preview shows at once) and is asked for again
+ if self.blocks && self.thumbs.status(idx) == thumb::Status::Waiting {
+ self.thumbs.forget(idx); // half a block picture cannot be continued
+ }
+ self.thumb_want = idx;
+ self.thumb_ask_at = now.wrapping_add(THUMB_DELAY_MS);
+ self.thumb_retry_at = 0;
+ }
+ match self.picture_status(idx) {
+ Status::NoCover => {
+ self.thumb_ask_at = 0;
+ return;
+ }
+ // in RAM already: no wait
+ Status::Ready => self.thumb_ask_at = 0,
+ st => {
+ let due = (self.thumb_ask_at != 0 && after(now, self.thumb_ask_at))
+ || (st == Status::Waiting && self.thumb_retry_at != 0 && after(now, self.thumb_retry_at));
+ if due {
+ if self.blocks {
+ self.thumbs.begin(idx);
+ let rows = self.rows_on_screen();
+ self.send(&[b'a', idx, thumb::EDGE, thumb::budget(rows) as u8, thumb::WIDE_OK]);
+ } else {
+ self.photos.begin(idx);
+ self.send(&photo::request(idx));
+ }
+ self.thumb_ask_at = 0;
+ self.thumb_retry_at = now.wrapping_add(THUMB_RETRY_MS);
+ }
+ }
+ }
+ if !self.blocks {
+ self.photo_update(idx);
+ } else if self.s.thumb == ROOT && self.thumbs.status(idx) == thumb::Status::Ready {
+ self.blocks_show(idx);
+ }
+ }
+
+ fn picture_status(&self, idx: u8) -> Status {
+ if !self.blocks {
+ return self.photos.status(idx);
+ }
+ match self.thumbs.status(idx) {
+ thumb::Status::Unknown => Status::Unknown,
+ thumb::Status::Waiting => Status::Waiting,
+ thumb::Status::Ready => Status::Ready,
+ thumb::Status::NoCover => Status::NoCover,
+ }
+ }
+
+ fn rows_on_screen(&self) -> usize {
+ self.m.count as usize + if self.page { 1 } else { 0 }
+ }
+
+ fn blocks_show(&mut self, idx: u8) {
+ let count = self.s.row_count as usize;
+ let Some(slot) = (0..count).find(|&k| self.s.row_indices[k] == idx) else { return };
+ let rows = self.rows_on_screen();
+ // the picture needs the row's texts in place, so that they move aside for it
+ {
+ let App { b, lv, s, m, .. } = self;
+ let mut flush = |b: &mut Batch| b.submit(lv);
+ if screens::labels_around(b, &mut flush, s, m, slot).is_err() {
+ return;
+ }
+ }
+ let App { b, lv, s, thumbs, .. } = self;
+ let Some(pic) = thumbs.ready(idx) else { return };
+ let mut flush = |b: &mut Batch| b.submit(lv);
+ // never half a picture: one with too many squares is not started, and a failed one is taken off again
+ if thumb::count(pic) > thumb::budget(rows) {
+ return;
+ }
+ if screens::show_thumb(b, &mut flush, s, slot, pic).is_err() {
+ let _ = screens::hide_thumb(b, s); // failed: the pulse stays
+ } else {
+ let _ = screens::hide_pulse(b, s);
+ }
+ let _ = self.flush();
+ }
+
+ /// Draws what has arrived of song `idx`'s real picture: first the soft preview, then it sharpens in place.
+ /// Puts the picture on its row once all of it is here, so it appears whole.
+ fn photo_update(&mut self, idx: u8) {
+ if self.photos.status(idx) != Status::Ready {
+ return;
+ }
+ let Some(held) = self.photos.held(idx) else { return };
+ let version = (held.q, held.wide);
+ if self.s.thumb != ROOT {
+ if version == self.drawn_version {
+ return;
+ }
+ // the cover changed under the one on show: take it off before its pixels are written again
+ let App { b, s, .. } = self;
+ if screens::hide_thumb(b, s).is_err() || self.flush().is_err() {
+ return;
+ }
+ }
+ let count = self.s.row_count as usize;
+ let Some(slot) = (0..count).find(|&k| self.s.row_indices[k] == idx) else { return };
+ let Some(held) = self.photos.held(idx) else { return };
+ // SAFETY: the only mutable use of the buffer, and no picture is on show
+ let px = unsafe { &mut *&raw mut PHOTO_PX };
+ if photo::draw(self.work, held.wide, held.q, held.data, 0, px).is_none() {
+ return;
+ }
+ self.drawn_version = version;
+ let (w, h) = photo::size(version.1);
+ // SAFETY: the buffer lives as long as the app
+ let px: &'static [u16] = unsafe { core::slice::from_raw_parts((&raw const PHOTO_PX).cast::(), w * h) };
+ self.photo_show(slot, px, w, h);
+ }
+
+ fn photo_show(&mut self, slot: usize, px: &'static [u16], w: usize, h: usize) {
+ // the picture needs the row's texts in place, so that they move aside for it
+ {
+ let App { b, lv, s, m, .. } = self;
+ let mut flush = |b: &mut Batch| b.submit(lv);
+ if screens::labels_around(b, &mut flush, s, m, slot).is_err() {
+ return;
+ }
+ }
+ // what is already waiting goes out first, so a refusal below can only be about the picture
+ let _ = self.flush();
+ let drawn = {
+ let App { b, lv, s, .. } = self;
+ let mut flush = |b: &mut Batch| b.submit(lv);
+ screens::show_photo(b, &mut flush, s, slot, px, w, h)
+ };
+ if drawn.and_then(|_| self.flush()).is_ok() {
+ let _ = screens::hide_pulse(&mut self.b, &mut self.s);
+ } else {
+ // Refused: an older App Loader cannot draw pictures, and has taken none of this batch. Forget the
+ // objects here as well, without sending anything, and ask for this cover as blocks. The pulse stays.
+ let _ = screens::hide_thumb(&mut self.b, &mut self.s);
+ self.b.clear();
+ self.blocks = true;
+ self.photos.clear();
+ self.thumb_ask_at = self.api.now().wrapping_add(THUMB_DELAY_MS);
+ self.thumb_retry_at = 0;
+ }
+ let _ = self.flush();
+ }
+
+ /// How long the loop may sleep before the picture logic has something to do (`None`: nothing).
+ fn thumb_wait(&self) -> Option {
+ let now = self.api.now();
+ let left = |at: u32| if after(now, at) { 1 } else { at.wrapping_sub(now) };
+ let mut extra: Option = None;
+ if self.s.pulse != ROOT {
+ extra = Some(left(self.pulse_next));
+ }
+ if self.crown_hold_until != 0 {
+ let w = left(self.crown_hold_until);
+ extra = Some(extra.map_or(w, |x| x.min(w)));
+ }
+ let base = self.thumb_wait_fetch();
+ match (base, extra) {
+ (Some(a), Some(b)) => Some(a.min(b)),
+ (a, b) => a.or(b),
+ }
+ }
+
+ fn thumb_wait_fetch(&self) -> Option {
+ if self.thumb_want == NONE {
+ return None;
+ }
+ let at = match self.picture_status(self.thumb_want) {
+ Status::Unknown => self.thumb_ask_at,
+ Status::Waiting if self.thumb_ask_at != 0 => self.thumb_ask_at,
+ Status::Waiting => self.thumb_retry_at,
+ _ => 0,
+ };
+ if at == 0 {
+ return None;
+ }
+ let now = self.api.now();
+ Some(if after(now, at) { 1 } else { at.wrapping_sub(now) })
+ }
+
+ fn phone(&mut self, msg: &[u8]) {
+ if msg.is_empty() { return; }
+ // speaker music: `o` open, `d` a block of sound, `c` the phone stopped
+ if msg[0] == b'd' {
+ self.spk_data(msg);
+ return;
+ }
+ if msg[0] == b'o' {
+ self.spk_open(msg);
+ return;
+ }
+ if msg[0] == b'c' {
+ self.spk_stop(false);
+ return;
+ }
+ // A piece of a cover picture. While pieces keep coming, the picture is not asked for again.
+ // A piece of a block picture. thumb_tick draws it once all of it is here.
+ if msg[0] == b'I' {
+ if self.blocks {
+ self.thumbs.apply(msg);
+ }
+ return;
+ }
+ if msg[0] == b'P' {
+ if self.photos.apply(msg) && msg[1] == self.thumb_want {
+ self.thumb_retry_at = self.api.now().wrapping_add(THUMB_RETRY_MS);
+ }
+ return;
+ }
+ // `E`: what plays on the phone is not what this screen shows (or something started to play while the
+ // start screen was up): open its controls. A list the person is looking through stays.
+ if msg[0] == b'E' {
+ let on_track = self.s.kind == Kind::Player
+ && (self.m.mode == MODE_MUSIC || self.m.mode == MODE_PODCAST);
+ if on_track || self.s.kind == Kind::Home {
+ self.resume_at = 0;
+ self.return_to_controls();
+ }
+ return;
+ }
+ // `A`: the phone does not know which screen this is (it restarted, or the link dropped): tell it.
+ if msg[0] == b'A' {
+ self.resume_request_pending = self.s.kind == Kind::Player;
+ self.hello_now();
+ return;
+ }
+ // Capture this before clearing it: W is allowed once for a cold launch, but a late W must not
+ // pull the user back into Player after they deliberately pressed Back to the list or Home.
+ let cold_launch = self.fresh_launch;
+ if msg.first() != Some(&b'W') { self.resume_request_pending = false; }
+ self.fresh_launch = false;
+ // `W mode index playing`: restore the exact Music/Podcast selection that was last opened
+ // from this watch. The phone sends the matching list, title, progress and cover colours next.
+ if msg.first() == Some(&b'W') && msg.len() >= 4 {
+ let mode = msg[1];
+ let index = msg[2];
+ if (mode == MODE_MUSIC || mode == MODE_PODCAST) && (index as usize) < MAX_TRACKS {
+ let same_pending = self.resume_player == Some(index)
+ && self.m.mode == mode && self.m.now == index;
+ let same_player = self.s.kind == Kind::Player
+ && self.m.mode == mode && self.m.now == index;
+ let page_resume = self.resume_request_pending
+ && self.s.kind == Kind::Player && self.m.mode == mode;
+
+ // A duplicate restore must never rebuild the same player. A new page-resume exchange may
+ // legitimately select a different row if the podcast/music session advanced while hidden.
+ if same_pending || same_player {
+ self.resume_request_pending = false;
+ let playing = msg[3] != 0;
+ if self.m.playing != playing {
+ self.m.playing = playing;
+ self.prog_at = self.api.now();
+ if same_player { self.redraw_now(); }
+ }
+ return;
+ }
+ if !cold_launch && !page_resume {
+ return; // stale W from a previous launch/restore after the user navigated away
+ }
+
+ self.resume_request_pending = false;
+ self.resume_player = Some(index);
+ self.auto_pick_pending = false;
+ self.menu_anchor = 0;
+ self.m.pick(mode);
+ self.m.now = index;
+ self.m.playing = msg[3] != 0;
+ // if the rest of it never arrives, ask again instead of waiting for ever
+ self.resume_at = self.api.now().wrapping_add(RESUME_MS);
+ }
+ return;
+ }
+ // A live-media update that was already on its way when the user pressed Back must not pull the
+ // model back into Control media (it only counts while that mode is the one being shown).
+ if msg.first() == Some(&b'X') && self.m.mode != MODE_EXTERNAL {
+ return;
+ }
+ let refreshed = msg.first() == Some(&b'R');
+ let level = self.m.level;
+ self.quiet_until = self.api.now().wrapping_add(QUIET_MS);
+ let fx = self.m.apply(msg);
+ if fx.home {
+ self.home_catalog(refreshed);
+ return;
+ }
+ // the phone's echo of a volume we just set by the crown: the crown is ahead of it
+ let local = self.api.now().wrapping_sub(self.vol_local_at) < 1500;
+ if msg.first() == Some(&b'V') && self.vol_until.is_some() && (local || self.vol_dirty) {
+ self.m.level = level;
+ }
+ // only the music list is kept on the watch; the podcasts come from the phone every time
+ if fx.saved && self.m.mode == MODE_MUSIC {
+ self.m.fix_order();
+ self.save();
+ }
+ // The restored player opens as soon as its own row has arrived, not after the whole list.
+ if let Some(index) = self.resume_player {
+ if index < self.m.count && self.m.tracks[index as usize].tlen > 0 && !fx.saved {
+ self.resume_player = None;
+ self.resume_at = 0;
+ self.m.now = index;
+ self.go(Kind::Player);
+ }
+ }
+ if fx.list && self.m.count > 0 && fx.saved {
+ self.resume_at = 0;
+ if let Some(index) = self.resume_player.take() {
+ if index < self.m.count {
+ // Open the track-specific player, not the generic active-session controller. K/Q cover
+ // colours and G progress continue arriving afterwards and update its matching background.
+ self.m.now = index;
+ self.go(Kind::Player);
+ } else if matches!(self.s.kind, Kind::Home | Kind::Wait | Kind::Menu) {
+ self.go(Kind::Menu);
+ }
+ } else if self.s.kind == Kind::Wait
+ || (self.s.kind == Kind::Menu && self.m.fingerprint() != self.menu_fp)
+ {
+ // The phone sends the whole list again after every hello; the same list is not rebuilt.
+ self.go(Kind::Menu);
+ }
+ }
+ if fx.list && self.m.count == 0 && self.m.empty && self.s.kind == Kind::Wait && !self.wait_empty {
+ self.go(Kind::Wait); // the same screen again, now saying that there is nothing to show
+ }
+ if msg.first() == Some(&b'V') && self.vol_until.is_some() && self.s.kind == Kind::Player {
+ self.vol_show();
+ }
+ if fx.colours {
+ match self.s.kind {
+ Kind::Menu => {
+ let App { b, lv, s, m, .. } = self;
+ let mut flush = |b: &mut Batch| b.submit(lv);
+ // restyle only the rows whose colour changed, and send nothing when none did
+ if let Ok(true) = screens::recolour(b, &mut flush, s, m) {
+ let _ = self.flush();
+ }
+ }
+ // the next frame of the glow takes them
+ Kind::Player | Kind::Wait | Kind::Home => {}
+ }
+ }
+ if self.s.kind == Kind::Player && fx.now {
+ self.redraw_now();
+ }
+ if self.s.kind == Kind::Player && fx.liked {
+ let _ = screens::show_liked(&mut self.b, &self.s, self.m.liked);
+ let _ = self.flush();
+ }
+ if fx.progress {
+ self.prog_at = self.api.now();
+ self.refresh(true);
+ }
+ if fx.now && self.s.kind == Kind::Player {
+ self.refresh(true);
+ }
+ }
+
+ /// Long press anywhere on the player: back, the same as the crown button.
+ fn long_press(&mut self, h: u16) {
+ if self.s.kind != Kind::Player || h == 0 {
+ return;
+ }
+ self.fresh_launch = false;
+ self.long_guard = self.api.now().wrapping_add(LONG_GUARD_MS);
+ self.last_tap_zone = 0;
+ self.motor.play(TICK);
+ if self.m.mode == MODE_EXTERNAL { self.home() } else { self.go(Kind::Menu) }
+ }
+
+ /// A tap on the empty left / right half of the player: a second one soon after seeks -5 s / +5 s.
+ fn zone_tap(&mut self, h: u16) {
+ let now = self.api.now();
+ if self.last_tap_zone == h && now.wrapping_sub(self.last_tap_at) <= DOUBLE_TAP_MS {
+ self.last_tap_zone = 0;
+ let delta = if h == self.s.seek_right.0 { SEEK_S } else { -SEEK_S };
+ let elapsed = self.m.elapsed(self.since());
+ if let Some((permille, target)) = self.m.seek_permille(elapsed, delta) {
+ self.motor.play(TICK);
+ self.send(&[b'k', (permille & 0xFF) as u8, (permille >> 8) as u8]);
+ self.m.pos = target;
+ self.prog_at = now;
+ self.refresh(true);
+ }
+ } else {
+ self.last_tap_zone = h;
+ self.last_tap_at = now;
+ }
+ }
+
+ fn click(&mut self, h: u16) {
+ if !after(self.api.now(), self.long_guard) {
+ return; // the release of a long press
+ }
+ self.fresh_launch = false;
+ // A page cannot rely on the watch's normal back action, so each inner screen owns a visible back target.
+ if h != 0 && h == self.s.back.0 {
+ self.motor.play(TICK);
+ match self.s.kind {
+ Kind::Player if self.m.mode == MODE_EXTERNAL => self.home(),
+ Kind::Player => self.go(Kind::Menu),
+ Kind::Menu | Kind::Wait => self.home(),
+ Kind::Home => {}
+ }
+ return;
+ }
+ if self.s.kind == Kind::Home {
+ if !after(self.api.now(), self.tap_guard) {
+ return;
+ }
+ if let Some(slot) = self.s.rows.iter().take(self.s.home_count as usize).position(|r| r.0 == h) {
+ self.motor.play(TICK);
+ match self.s.home_modes[slot] {
+ MODE_MUSIC => self.pick(MODE_MUSIC),
+ MODE_PODCAST => self.pick(MODE_PODCAST),
+ MODE_CUSTOM => self.pick(MODE_CUSTOM),
+ MODE_EXTERNAL => self.return_to_controls(),
+ _ => {}
+ }
+ }
+ return;
+ }
+ if self.s.kind == Kind::Menu {
+ if let Some(slot) = self.s.rows.iter().take(self.s.row_count as usize).position(|r| r.0 == h) {
+ self.motor.play(TICK);
+ let index = self.s.row_indices[slot];
+ self.send(&[b's', index]);
+ if self.m.mode == MODE_CUSTOM {
+ // Custom entries execute their phone-side URL action; there is no media player screen.
+ return;
+ }
+ // The song/show that already plays: open its controls without restarting it.
+ if self.m.now != index {
+ self.m.now = index;
+ self.m.playing = true;
+ self.m.pos = 0;
+ self.m.dur = 0;
+ self.prog_at = self.api.now();
+ }
+ self.go(Kind::Player);
+ }
+ return;
+ }
+ if self.s.kind != Kind::Player || h == 0 {
+ return;
+ }
+ if h == self.s.seek_left.0 || h == self.s.seek_right.0 {
+ self.zone_tap(h);
+ return;
+ }
+ self.last_tap_zone = 0;
+ if h == self.s.heart.0 {
+ if self.m.toggle_liked() {
+ self.motor.play(TICK);
+ self.send(b"l");
+ let _ = screens::show_liked(&mut self.b, &self.s, self.m.liked);
+ let _ = self.flush();
+ }
+ } else if h == self.s.vol.0 {
+ // Three quick presses start (or stop) the music on the watch's speaker. The first two presses toggle
+ // the crown volume as always (so it is back as it was); the third one does that instead.
+ let n = self.spk_taps.tap(self.api.now(), SPK_TAP_GAP_MS);
+ if n >= 3 {
+ self.spk_taps.reset();
+ self.spk_toggle();
+ } else {
+ self.motor.play(TICK);
+ self.vol_toggle();
+ }
+ } else if h == self.s.play.0 {
+ self.motor.play(TICK);
+ self.m.pos = self.m.elapsed(self.since()).min(u16::MAX as u32) as u16;
+ self.prog_at = self.api.now();
+ self.m.playing = !self.m.playing;
+ self.send(b"p");
+ self.redraw_now();
+ } else if h == self.s.next.0 || h == self.s.prev.0 {
+ self.motor.play(TICK);
+ let fwd = h == self.s.next.0;
+ self.send(if fwd { b"n" } else { b"b" });
+ if self.m.mode == MODE_PODCAST || self.m.mode == MODE_EXTERNAL {
+ // The phone plays the next/previous podcast episode or active system media item
+ // and sends fresh metadata when Android reports the new item.
+ return;
+ }
+ let c = self.m.count;
+ if c > 0 && self.m.now != NONE {
+ self.m.now = if fwd { (self.m.now + 1) % c } else { (self.m.now + c - 1) % c };
+ self.m.playing = true;
+ self.m.pos = 0;
+ self.m.dur = 0;
+ self.prog_at = self.api.now();
+ self.redraw_now();
+ self.refresh(true);
+ }
+ }
+ }
+ }
+
+ fn main(api: &'static Api) -> i32 {
+ let Some(lv) = api.lv() else { return -95 }; // loader older than ABI 1.2
+ let Some(b) = Batch::new() else { return -1 };
+ let initial_hello_id = api.now().max(1);
+ let mut app = App {
+ api,
+ lv,
+ b,
+ s: Screen::empty(),
+ motor: Motor::new(api),
+ m: unsafe { &mut *&raw mut MODEL },
+ prog_at: api.now(),
+ last_pct: -1,
+ last_min: u16::MAX,
+ page: api.on_page(),
+ heard: false,
+ paused: false,
+ tide_next: api.now(),
+ glow: screens::Glow::new(),
+ next_hello: api.now(),
+ hello_id: initial_hello_id,
+ resume_at: 0,
+ tap_guard: 0,
+ got_catalog: false,
+ vol_until: None,
+ quiet_until: 0,
+ last_tick: 0,
+ saved_sum: 0,
+ vol_dirty: false,
+ vol_sent_at: api.now(),
+ vol_local_at: api.now(),
+ menu_anchor: 0,
+ pending_focus_row: -1,
+ pending_focus_handle: 0,
+ pending_focus_at: api.now(),
+ focus_accept_at: api.now(),
+ fresh_launch: true,
+ resume_player: None,
+ resume_request_pending: false,
+ auto_pick_pending: true,
+ auto_at: None,
+ hello_tries: 0,
+ home_built: 0xFF,
+ menu_fp: 0,
+ wait_empty: false,
+ last_tap_zone: 0,
+ last_tap_at: 0,
+ long_guard: 0,
+ thumbs_fp: 0,
+ photos: unsafe { &mut *&raw mut PHOTOS },
+ thumbs: unsafe { &mut *&raw mut THUMBS },
+ blocks: false,
+ work: unsafe { &mut *&raw mut PHOTO_WORK },
+ drawn_version: (0, false),
+ thumb_want: NONE,
+ thumb_ask_at: 0,
+ crown_hold_until: 0,
+ pulse_start: 0,
+ pulse_next: 0,
+ thumb_retry_at: 0,
+ spk_state: 0,
+ spk_until: 0,
+ spk_head: 0,
+ spk_count: 0,
+ spk_off: 0,
+ spk_primed: false,
+ spk_started: false,
+ spk_pcm: 0,
+ spk_taps: MultiTap::new(),
+ };
+ // A new app instance starts from Home even if the loader reuses the process and static allocation.
+ // Reset field-by-field: constructing a temporary Model here would put the full 50-track table
+ // (several KB) on the watch's small app stack and can reset the watch before the UI opens.
+ app.m.reset();
+ app.photos.clear();
+ app.thumbs.clear();
+ if screens::fonts(&mut app.b).and_then(|_| app.flush()).is_err() {
+ return 1;
+ }
+ if screens::theme(&mut app.b).is_err() {
+ return 2;
+ }
+ api.own_back(true);
+ // The phone will return a dynamic category catalog; a single available category opens automatically.
+ app.go(Kind::Home);
+ let mut msg = [0u8; MSG_MAX];
+ loop {
+ let now = api.now();
+ if !app.heard && after(now, app.next_hello) {
+ app.hello();
+ }
+ if app.resume_at != 0 && after(now, app.resume_at) {
+ if app.resume_player.is_some() {
+ app.resume_at = now.wrapping_add(RESUME_MS);
+ app.hello();
+ } else {
+ app.resume_at = 0;
+ }
+ }
+ app.motor.update();
+ app.spk_pump();
+ app.spk_watch();
+ // wake for the motor, the next second of the song, the clock, the volume, or the next hello
+ let mut wait = if app.heard { u32::MAX } else { app.next_hello.wrapping_sub(now).min(HELLO_MAX_MS) };
+ if app.resume_at != 0 {
+ wait = wait.min(app.resume_at.wrapping_sub(now).min(RESUME_MS));
+ }
+ if app.s.kind == Kind::Player {
+ wait = wait.min(if app.m.playing { 1000 - app.since() % 1000 } else { IDLE_MS });
+ }
+ if let Some(w) = app.motor.wait() {
+ wait = wait.min(w);
+ }
+ if app.s.kind == Kind::Player && !app.paused {
+ wait = wait.min(app.tide_next.wrapping_sub(now).min(TIDE_MS));
+ }
+ if let Some(w) = app.vol_wait() {
+ wait = wait.min(w);
+ }
+ if app.spk_state == 2 && app.spk_count > 0 {
+ wait = wait.min(SPK_PUMP_MS);
+ }
+ if app.spk_state == 1 {
+ wait = wait.min(app.spk_until.wrapping_sub(now).min(1000));
+ }
+ if app.pending_focus_row >= 0 {
+ let elapsed = now.wrapping_sub(app.pending_focus_at);
+ let remaining = FOCUS_SETTLE_MS.saturating_sub(elapsed);
+ wait = wait.min(remaining.max(1));
+ }
+ if let Some(w) = app.thumb_wait() {
+ wait = wait.min(w);
+ }
+ let ev = api.event(wait.max(1));
+ app.motor.update();
+ app.refresh(false);
+ app.vol_tick();
+ if app.s.kind == Kind::Player && !app.paused && after(api.now(), app.tide_next) {
+ let t = api.now();
+ if app.glow.frame(&mut app.b, &app.s, app.m, t).is_ok() && !app.b.bytes().is_empty() {
+ let _ = app.flush();
+ }
+ app.tide_next = api.now().wrapping_add(TIDE_MS);
+ }
+ let Some(e) = ev else {
+ app.commit_focus(false);
+ app.thumb_tick();
+ continue;
+ };
+ match e.kind {
+ BUTTON => {
+ app.fresh_launch = false;
+ match app.s.kind {
+ Kind::Player if app.m.mode == MODE_EXTERNAL => app.home(),
+ Kind::Player => app.go(Kind::Menu),
+ Kind::Menu | Kind::Wait => app.home(),
+ Kind::Home => break,
+ }
+ }
+ PAUSE => {
+ app.paused = true;
+ app.motor.off();
+ // The loader rejects host messages while paused. Do not keep asking the phone (and
+ // accumulating stale replies); RESUME starts one fresh, identified exchange instead.
+ app.heard = true;
+ app.hello_tries = 0;
+ app.resume_at = 0;
+ app.resume_request_pending = false;
+ }
+ RESUME => {
+ // the speaker stopped with the pause, and the phone does not know: stop the stream
+ if app.spk_state != 0 {
+ app.spk_stop(true);
+ }
+ app.paused = false;
+ app.tide_next = api.now();
+ app.glow.resume(api.now());
+ app.hello_id = app.hello_id.wrapping_add(1);
+ if app.hello_id == 0 { app.hello_id = 1; }
+ app.resume_request_pending = app.s.kind == Kind::Player;
+ app.heard = false;
+ app.hello_tries = 0;
+ app.next_hello = api.now();
+ }
+ CROWN => app.crown(e.delta),
+ LV => {
+ let h = e.x as u16;
+ match e.y {
+ CLICKED => app.click(h),
+ LONG_PRESSED => app.long_press(h),
+ FOCUSED => app.focus_tick(e.x as u16, e.delta),
+ _ => {}
+ }
+ }
+ MESSAGE => {
+ app.heard = true;
+ app.hello_tries = 0;
+ // Keep fresh_launch set until phone() examines the first payload. Android sends W first
+ // for a saved player restore; phone() captures the cold-launch permission exactly once.
+ while let Some(m) = api.recv(&mut msg) {
+ app.phone(m);
+ }
+ app.spk_pump();
+ // any message counts as an answer, except while the start screen still waits for its catalog:
+ // the phone has to hear the hello that tells it the watch left Control media
+ if app.s.kind == Kind::Home && !app.got_catalog {
+ app.heard = false;
+ }
+ }
+ _ => {}
+ }
+ app.commit_focus(false);
+ app.thumb_tick();
+ }
+ if app.spk_state != 0 {
+ app.spk_stop(true);
+ }
+ app.motor.off();
+ 0
+ }
+}
diff --git a/apps/watch-music/src/model.rs b/apps/watch-music/src/model.rs
new file mode 100644
index 0000000..7df8e81
--- /dev/null
+++ b/apps/watch-music/src/model.rs
@@ -0,0 +1,1047 @@
+//! The music app's state and its message protocol. No `Api` in here, so `cargo test` runs it on the computer.
+//!
+//! Phone -> watch (first byte = kind, 1..=128 bytes):
+//! `C` count version a new list starts: `count` songs, list `version`
+//! `T` start n (tlen title alen artist)* songs `start..start+n`, UTF-8
+//! `K` start n (c1 c2)* the colour of songs `start..start+n` (two RGB565 LE; the pill uses `c1`)
+//! `Q` start n (4 x u16)* the cover's four quarter colours (top-left, top-right, bottom-left, bottom-right;
+//! RGB565 LE) of songs `start..start+n`, for the player's background
+//! `N` index playing the song that plays now (`0xFF` = none) and whether it plays
+//! `S` playing play / pause changed
+//! `V` level muted volume 0..=100
+//! `G` pos dur seconds played and song length (u16 LE each); dur 0 = unknown
+//! `X` playing tlen title alen artist current external media metadata for Return to controls
+//! `H` flags home catalog: bit 0 Music, bit 1 Podcasts, bit 2 Custom, bit 3 active media,
+//! bit 4 open the active media's controls right now (cold launch while it plays)
+//! `R` flags refreshed home catalog (same flags, also asks the watch to re-evaluate its home)
+//! `W` mode index playing restore the last watch-selected Music/Podcast row into its track-specific player
+//! `A` legacy "hello" acknowledgement
+//! `L` liked the song on the player is in the phone's saved songs (1) or not (0); sent after
+//! every song change and after `l`. A phone that never sends it: no heart.
+//! Watch -> phone:
+//! `h` count version mode fresh player_resume launch_id:u32le
+//! hello; retries keep the same ID, a new launch or resume gets a new ID.
+//! `mode` = 0 music, 1 podcasts, 2 active media, 0xFF = the start screen.
+//! `fresh` marks a cold launch; `player_resume` marks a paused track-specific player.
+//! Choosing a category asks the phone for the matching list and controls
+//! `s` idx play this song (podcasts: the show, its last episode)
+//! `p` `n` `b` `m` play-pause / next / previous / mute (podcasts: next / previous episode)
+//! `v` level volume set to level 0..=100
+//! `k` lo hi seek to lo|hi<<8 thousandths of the song (double tap: -5 s / +5 s)
+//! `l` save / unsave the song on the player (the heart); the phone answers `L`
+//! `e` on speaker music: 1 = start it (three quick presses of the speaker button), 0 = stop it
+//! Phone -> watch, speaker music (the watch plays what the phone captures, 8 kHz mono IMA ADPCM):
+//! `o` khz open the speaker (8)
+//! `d` seq:u16le block one ADPCM block (3-byte header, 122 code bytes = 244 samples)
+//! `c` the phone stopped (or could not start): the speaker closes
+
+pub const MAX_TRACKS: usize = 50;
+pub const TEXT_BYTES: usize = 40;
+pub const NONE: u8 = 0xFF;
+/// what the list on the watch is
+pub const MODE_MUSIC: u8 = 0;
+pub const MODE_PODCAST: u8 = 1;
+/// the phone's currently active media session (not limited to a saved playlist)
+pub const MODE_EXTERNAL: u8 = 2;
+/// custom URL actions
+pub const MODE_CUSTOM: u8 = 3;
+/// the start screen (music or podcasts not chosen yet)
+pub const MODE_NONE: u8 = 0xFF;
+/// one crown click changes the volume by this many percent
+pub const VOL_STEP: i16 = 5;
+/// bytes of a song kept in the saved list
+const SAVED_TEXT: usize = 24;
+/// The phone sends "title, artist" in this order; `true` shows the first text as the artist and the second as the
+/// song (the setting that matches the names as the phone app sends them today). Flip it if they look reversed.
+/// Podcasts are never swapped: the phone sends the episode first and the show second.
+pub const SWAP_NAMES: bool = false;
+/// Turn the rows round that the phone could not decide (see `fix_order`).
+pub const SWAP_UNSURE: bool = true;
+pub const DEFAULT_C1: u16 = 0x2966;
+pub const DEFAULT_C2: u16 = 0x4229;
+
+#[derive(Clone, Copy)]
+pub struct Track {
+ pub tlen: u8,
+ pub alen: u8,
+ pub title: [u8; TEXT_BYTES],
+ pub artist: [u8; TEXT_BYTES],
+ pub c1: u16,
+ pub c2: u16,
+ /// the cover's quarters (top-left, top-right, bottom-left, bottom-right); `has_q` once the phone sent them
+ pub q: [u16; 4],
+ pub has_q: bool,
+}
+
+fn text(b: &[u8], len: u8) -> &str {
+ core::str::from_utf8(&b[..len as usize]).unwrap_or("?")
+}
+
+impl Track {
+ pub const EMPTY: Track =
+ Track {
+ tlen: 0,
+ alen: 0,
+ title: [0; TEXT_BYTES],
+ artist: [0; TEXT_BYTES],
+ c1: DEFAULT_C1,
+ c2: DEFAULT_C2,
+ q: [DEFAULT_C1; 4],
+ has_q: false,
+ };
+
+ pub fn title(&self) -> &str {
+ text(&self.title, self.tlen)
+ }
+
+ pub fn artist(&self) -> &str {
+ text(&self.artist, self.alen)
+ }
+}
+
+#[derive(Default, Clone, Copy, PartialEq, Debug)]
+pub struct Effect {
+ pub list: bool,
+ pub colours: bool,
+ pub now: bool,
+ pub volume: bool,
+ pub progress: bool,
+ pub saved: bool,
+ /// The phone sent a refreshed home-category catalog.
+ pub home: bool,
+ /// The saved (heart) state of the song on the player changed.
+ pub liked: bool,
+}
+
+pub struct Model {
+ pub tracks: [Track; MAX_TRACKS],
+ pub count: u8,
+ pub version: u8,
+ pub now: u8,
+ pub playing: bool,
+ pub level: u8,
+ pub muted: bool,
+ /// seconds played when `G` arrived, and the song length (0 = unknown)
+ pub pos: u16,
+ pub dur: u16,
+ /// `MODE_MUSIC`, `MODE_PODCAST`, `MODE_CUSTOM`, `MODE_EXTERNAL` or `MODE_NONE` (the start screen)
+ pub mode: u8,
+ /// the phone said the list is empty (nothing to show yet)
+ pub empty: bool,
+ /// bit 0 Music, bit 1 Podcasts, bit 2 Custom, bit 3 an active external media session
+ pub home_flags: u8,
+ /// the song on the player is saved on the phone: [`LIKED_NO`], [`LIKED_YES`] or [`LIKED_UNKNOWN`] (the phone
+ /// never said, so it has no saved songs: the heart stays hidden)
+ pub liked: u8,
+}
+
+pub const LIKED_NO: u8 = 0;
+pub const LIKED_YES: u8 = 1;
+pub const LIKED_UNKNOWN: u8 = 0xFF;
+
+fn clip_text(src: &[u8], max: usize) -> usize {
+ // never cut a UTF-8 character in half
+ let mut cut = src.len().min(max);
+ while cut < src.len() && cut > 0 && (src[cut] & 0xC0) == 0x80 {
+ cut -= 1;
+ }
+ cut
+}
+
+impl Model {
+ pub const fn new() -> Model {
+ Model {
+ tracks: [Track::EMPTY; MAX_TRACKS],
+ count: 0,
+ version: 0,
+ now: NONE,
+ playing: false,
+ level: 50,
+ muted: false,
+ pos: 0,
+ dur: 0,
+ mode: MODE_NONE,
+ empty: false,
+ home_flags: 0,
+ liked: LIKED_UNKNOWN,
+ }
+ }
+
+ /// Clears the large track table in place. Do not replace it with
+ /// `self.tracks = [Track::EMPTY; MAX_TRACKS]`: on the watch that can
+ /// materialize a multi-kilobyte temporary on the small app stack.
+ fn clear_tracks(&mut self) {
+ for track in self.tracks.iter_mut() {
+ *track = Track::EMPTY;
+ }
+ }
+
+ /// Resets a reused app instance without constructing a second full Model on the stack.
+ pub fn reset(&mut self) {
+ self.clear_tracks();
+ self.count = 0;
+ self.version = 0;
+ self.now = NONE;
+ self.playing = false;
+ self.level = 50;
+ self.muted = false;
+ self.pos = 0;
+ self.dur = 0;
+ self.mode = MODE_NONE;
+ self.empty = false;
+ self.home_flags = 0;
+ self.liked = LIKED_UNKNOWN;
+ }
+
+ /// The heart was tapped: flip it at once (the phone confirms with `L`). False if the phone has no saved songs.
+ pub fn toggle_liked(&mut self) -> bool {
+ match self.liked {
+ LIKED_NO => self.liked = LIKED_YES,
+ LIKED_YES => self.liked = LIKED_NO,
+ _ => return false,
+ }
+ true
+ }
+
+ /// Where to seek for a double tap: `delta` seconds from `elapsed`, as thousandths of the song.
+ /// `None` when the length is unknown (live streams, some players), so nothing is sent.
+ pub fn seek_permille(&self, elapsed: u32, delta: i32) -> Option<(u16, u16)> {
+ if self.dur == 0 {
+ return None;
+ }
+ let dur = self.dur as i32;
+ let target = (elapsed as i32 + delta).clamp(0, dur);
+ Some(((target as i64 * 1000 / dur as i64) as u16, target as u16))
+ }
+
+ /// Switches to `mode` with an empty list: the phone sends the list of that mode next.
+ pub fn pick(&mut self, mode: u8) {
+ self.mode = mode;
+ self.clear_tracks();
+ self.count = 0;
+ self.version = 0;
+ self.now = NONE;
+ self.playing = false;
+ self.pos = 0;
+ self.dur = 0;
+ self.empty = false;
+ }
+
+ /// Whether the first text of a name pair is the artist (music) or the song (podcasts).
+ fn swap(&self) -> bool {
+ SWAP_NAMES && self.mode == MODE_MUSIC
+ }
+
+ pub fn title(&self, i: u8) -> &str {
+ if i < self.count { self.tracks[i as usize].title() } else { "" }
+ }
+
+ pub fn artist(&self, i: u8) -> &str {
+ if i < self.count { self.tracks[i as usize].artist() } else { "" }
+ }
+
+ /// The four quarter colours of song `i`'s cover; its pill colour in all four quarters until the phone sends them.
+ pub fn quarters(&self, i: u8) -> [u16; 4] {
+ if i >= self.count {
+ return [DEFAULT_C1; 4];
+ }
+ let t = &self.tracks[i as usize];
+ if t.has_q { t.q } else { [t.c1; 4] }
+ }
+
+ /// Whether the phone has sent the cover colours of song `i`.
+ pub fn has_quarters(&self, i: u8) -> bool {
+ i < self.count && self.tracks[i as usize].has_q
+ }
+
+ /// A cheap hash of what the list screen shows (mode, count, titles, artists). When the phone sends the same list
+ /// again, the screen is not rebuilt.
+ pub fn fingerprint(&self) -> u32 {
+ fn put(h: u32, b: u8) -> u32 {
+ (h ^ b as u32).wrapping_mul(16_777_619)
+ }
+ let mut h = put(put(2_166_136_261, self.mode), self.count);
+ for t in &self.tracks[..self.count as usize] {
+ for &c in &t.title[..t.tlen as usize] {
+ h = put(h, c);
+ }
+ h = put(h, 0);
+ for &c in &t.artist[..t.alen as usize] {
+ h = put(h, c);
+ }
+ h = put(h, 1);
+ }
+ h
+ }
+
+ /// Applies one phone message.
+ pub fn apply(&mut self, m: &[u8]) -> Effect {
+ let mut fx = Effect::default();
+ let Some(&kind) = m.first() else { return fx };
+ match kind {
+ b'L' if m.len() >= 2 => {
+ let v = if m[1] != 0 { LIKED_YES } else { LIKED_NO };
+ fx.liked = v != self.liked;
+ self.liked = v;
+ }
+ b'H' | b'R' if m.len() >= 2 => {
+ self.home_flags = m[1] & 0x1F;
+ fx.home = true;
+ }
+ b'C' if m.len() >= 3 => {
+ self.count = m[1].min(MAX_TRACKS as u8);
+ self.version = m[2];
+ self.empty = self.count == 0;
+ for t in self.tracks.iter_mut() {
+ *t = Track::EMPTY;
+ }
+ if self.now != NONE && self.now >= self.count {
+ self.now = NONE;
+ }
+ fx.list = true;
+ }
+ b'T' if m.len() >= 3 => {
+ let mut i = m[1] as usize;
+ let mut n = m[2] as usize;
+ let mut p = 3;
+ let swap = self.swap();
+ let mut touched = false;
+ while n > 0 && p < m.len() {
+ let tl = m[p] as usize;
+ if p + 1 + tl >= m.len() {
+ break;
+ }
+ let al = m[p + 1 + tl] as usize;
+ if p + 2 + tl + al > m.len() {
+ break;
+ }
+ if i < MAX_TRACKS {
+ let first = &m[p + 1..p + 1 + tl];
+ let second = &m[p + 2 + tl..p + 2 + tl + al];
+ let (ts, as_) = if swap { (second, first) } else { (first, second) };
+ let (tc, ac) = (clip_text(ts, TEXT_BYTES), clip_text(as_, TEXT_BYTES));
+ let t = &mut self.tracks[i];
+ t.title[..tc].copy_from_slice(&ts[..tc]);
+ t.tlen = tc as u8;
+ t.artist[..ac].copy_from_slice(&as_[..ac]);
+ t.alen = ac as u8;
+ touched |= i == self.now as usize;
+ }
+ p += 2 + tl + al;
+ i += 1;
+ n -= 1;
+ }
+ fx.list = true;
+ // the song that plays now got a new title (a podcast moved to another episode)
+ fx.now |= touched;
+ if i >= self.count as usize && self.count > 0 {
+ fx.saved = true;
+ }
+ }
+ b'K' if m.len() >= 3 => {
+ let mut i = m[1] as usize;
+ let mut n = m[2] as usize;
+ let mut p = 3;
+ while n > 0 && p + 4 <= m.len() {
+ if i < MAX_TRACKS {
+ self.tracks[i].c1 = u16::from_le_bytes([m[p], m[p + 1]]);
+ self.tracks[i].c2 = u16::from_le_bytes([m[p + 2], m[p + 3]]);
+ }
+ p += 4;
+ i += 1;
+ n -= 1;
+ }
+ fx.colours = true;
+ }
+ b'Q' if m.len() >= 3 => {
+ let mut i = m[1] as usize;
+ let mut n = m[2] as usize;
+ let mut p = 3;
+ while n > 0 && p + 8 <= m.len() {
+ if i < MAX_TRACKS {
+ for k in 0..4 {
+ self.tracks[i].q[k] = u16::from_le_bytes([m[p + 2 * k], m[p + 2 * k + 1]]);
+ }
+ self.tracks[i].has_q = true;
+ }
+ p += 8;
+ i += 1;
+ n -= 1;
+ }
+ fx.colours = true;
+ }
+ b'N' if m.len() >= 3 => {
+ let idx = if m[1] < self.count { m[1] } else { NONE };
+ let playing = m[2] != 0;
+ if idx != self.now || playing != self.playing {
+ fx.now = true;
+ }
+ self.now = idx;
+ self.playing = playing;
+ }
+ b'S' if m.len() >= 2 => {
+ let p = m[1] != 0;
+ if p != self.playing {
+ self.playing = p;
+ fx.now = true;
+ }
+ }
+ b'V' if m.len() >= 4 => {
+ self.level = m[1].min(100);
+ self.muted = m[2] != 0;
+ fx.volume = m[3] != 0;
+ }
+ b'G' if m.len() >= 5 => {
+ self.pos = u16::from_le_bytes([m[1], m[2]]);
+ self.dur = u16::from_le_bytes([m[3], m[4]]);
+ fx.progress = true;
+ }
+ // The selected system media session can be a video, browser tab, or any other player.
+ // Unlike T, X is a single live item and must never be saved as part of the playlist.
+ b'X' if m.len() >= 4 => {
+ let playing = m[1] != 0;
+ let tl = m[2] as usize;
+ let title_start: usize = 3;
+ let artist_len_at = title_start.saturating_add(tl);
+ if artist_len_at < m.len() {
+ let al = m[artist_len_at] as usize;
+ let artist_start = artist_len_at + 1;
+ if artist_start + al <= m.len() {
+ let title = &m[title_start..title_start + tl];
+ let artist = &m[artist_start..artist_start + al];
+ let (tc, ac) = (clip_text(title, TEXT_BYTES), clip_text(artist, TEXT_BYTES));
+ // X status snapshots arrive repeatedly while the active session is open. Preserve its
+ // album palette for the same item; clear it only when the active title/artist changes.
+ let same_item = self.mode == MODE_EXTERNAL
+ && self.count == 1
+ && self.tracks[0].tlen as usize == tc
+ && self.tracks[0].alen as usize == ac
+ && self.tracks[0].title[..tc] == title[..tc]
+ && self.tracks[0].artist[..ac] == artist[..ac];
+ let t = &mut self.tracks[0];
+ t.title = [0; TEXT_BYTES];
+ t.artist = [0; TEXT_BYTES];
+ t.title[..tc].copy_from_slice(&title[..tc]);
+ t.artist[..ac].copy_from_slice(&artist[..ac]);
+ t.tlen = tc as u8;
+ t.alen = ac as u8;
+ if !same_item {
+ t.c1 = DEFAULT_C1;
+ t.c2 = DEFAULT_C2;
+ t.q = [DEFAULT_C1; 4];
+ t.has_q = false;
+ }
+ self.count = 1;
+ self.now = 0;
+ self.playing = playing;
+ self.mode = MODE_EXTERNAL;
+ fx.list = true;
+ fx.now = true;
+ }
+ }
+ }
+ _ => {}
+ }
+ fx
+ }
+
+ /// The list as a blob for `Api::save` (at most 2560 bytes).
+ pub fn save(&self, out: &mut [u8]) -> usize {
+ out[0] = b'W';
+ out[1] = b'M';
+ out[2] = 4;
+ out[3] = self.count;
+ out[4] = self.version;
+ let mut p = 5;
+ for t in &self.tracks[..self.count as usize] {
+ for (len, src) in [(t.tlen, &t.title), (t.alen, &t.artist)] {
+ let n = clip_text(&src[..len as usize], SAVED_TEXT);
+ out[p] = n as u8;
+ out[p + 1..p + 1 + n].copy_from_slice(&src[..n]);
+ p += 1 + n;
+ }
+ }
+ p
+ }
+
+ /// Music names come as "Song - Artist" or "Artist - Song". The phone decides when a name comes back in other
+ /// rows (an artist has several songs); the rows it could not decide arrive as (artist, song) and are turned
+ /// round here: a row whose artist text occurs only once in the list is swapped.
+ pub fn fix_order(&mut self) {
+ if !SWAP_UNSURE || self.mode == MODE_PODCAST {
+ return;
+ }
+ let n = self.count as usize;
+ let same = |a: &str, b: &str| a.trim().eq_ignore_ascii_case(b.trim());
+ let mut swap = [false; MAX_TRACKS];
+ for (i, flag) in swap.iter_mut().enumerate().take(n) {
+ let a = self.tracks[i].artist();
+ if a.is_empty() {
+ continue;
+ }
+ let mut seen = 0;
+ for t in &self.tracks[..n] {
+ seen += same(a, t.artist()) as u32 + same(a, t.title()) as u32;
+ }
+ *flag = seen < 2;
+ }
+ for (i, &sw) in swap.iter().enumerate().take(n) {
+ if sw {
+ let t = &mut self.tracks[i];
+ core::mem::swap(&mut t.title, &mut t.artist);
+ core::mem::swap(&mut t.tlen, &mut t.alen);
+ }
+ }
+ }
+
+ pub fn load(&mut self, b: &[u8]) {
+ if b.len() < 5 || &b[..3] != b"WM\x04" || b[3] as usize > MAX_TRACKS {
+ return;
+ }
+ let count = b[3] as usize;
+ // Validate the entire blob first so a truncated save never partially replaces a good list.
+ // This first pass deliberately uses only scalars; a local `[Track; 50]` is several KB on the watch stack.
+ let mut check = 5usize;
+ for _ in 0..count {
+ for _ in 0..2 {
+ let Some(&n) = b.get(check) else { return };
+ let n = n as usize;
+ if n > TEXT_BYTES || check + 1 + n > b.len() {
+ return;
+ }
+ check += 1 + n;
+ }
+ }
+
+ self.clear_tracks();
+ let mut p: usize = 5;
+ for i in 0..count {
+ let track = &mut self.tracks[i];
+ let title_len = b[p] as usize;
+ p += 1;
+ track.title[..title_len].copy_from_slice(&b[p..p + title_len]);
+ track.tlen = title_len as u8;
+ p += title_len;
+
+ let artist_len = b[p] as usize;
+ p += 1;
+ track.artist[..artist_len].copy_from_slice(&b[p..p + artist_len]);
+ track.alen = artist_len as u8;
+ p += artist_len;
+ }
+ self.count = count as u8;
+ self.version = b[4];
+ self.empty = false;
+ }
+}
+
+impl Model {
+ /// Seconds played now: the phone's number plus the `since_ms` that passed since it came.
+ pub fn elapsed(&self, since_ms: u32) -> u32 {
+ let e = self.pos as u32 + if self.playing { since_ms / 1000 } else { 0 };
+ if self.dur > 0 { e.min(self.dur as u32) } else { e }
+ }
+}
+
+/// Position of `secs` in a song of `dur` seconds, 0..=1000 (0 when the length is unknown).
+pub fn permille(secs: u32, dur: u16) -> i32 {
+ if dur == 0 { 0 } else { (secs.min(dur as u32) * 1000 / dur as u32) as i32 }
+}
+
+/// The volume after one crown click (`delta` is +1 or -1): `VOL_STEP` percent, kept in 0..=100.
+pub fn step_volume(level: u8, delta: i16) -> u8 {
+ (level as i16 + delta.signum() * VOL_STEP).clamp(0, 100) as u8
+}
+
+/// "Vol 65%".
+pub fn volume_text(level: u8, buf: &mut [u8; 8]) -> &str {
+ let v = level.min(100);
+ buf[..4].copy_from_slice(b"Vol ");
+ let mut p = 4;
+ if v >= 100 {
+ buf[4..7].copy_from_slice(b"100");
+ p += 3;
+ } else if v >= 10 {
+ buf[p] = b'0' + v / 10;
+ buf[p + 1] = b'0' + v % 10;
+ p += 2;
+ } else {
+ buf[p] = b'0' + v;
+ p += 1;
+ }
+ buf[p] = b'%';
+ core::str::from_utf8(&buf[..p + 1]).unwrap_or("")
+}
+
+const IMA_STEPS: [i32; 89] = [
+ 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97,
+ 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
+ 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871,
+ 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623,
+ 27086, 29794, 32767,
+];
+const IMA_INDEX: [i32; 8] = [-1, -1, -1, -1, 2, 4, 6, 8];
+
+/// One IMA ADPCM block (the speaker stream; the same blocks as the SDK's adpcm.rs): predictor i16 LE, step index u8,
+/// then 4-bit codes, low nibble first. Writes little-endian 16-bit samples into `out` and returns the bytes written
+/// (4 per code byte), or 0 for a bad header or an `out` that is too short.
+pub fn ima_decode_block(block: &[u8], out: &mut [u8]) -> usize {
+ if block.len() < 3 || block[2] > 88 {
+ return 0;
+ }
+ let codes = &block[3..];
+ if out.len() < codes.len() * 4 {
+ return 0;
+ }
+ let mut predictor = i32::from(i16::from_le_bytes([block[0], block[1]]));
+ let mut index = i32::from(block[2]);
+ for (i, &byte) in codes.iter().enumerate() {
+ for half in 0..2 {
+ let code = if half == 0 { byte & 0xF } else { byte >> 4 };
+ let step = IMA_STEPS[index as usize];
+ let mut diff = step >> 3;
+ if code & 4 != 0 {
+ diff += step;
+ }
+ if code & 2 != 0 {
+ diff += step >> 1;
+ }
+ if code & 1 != 0 {
+ diff += step >> 2;
+ }
+ predictor = (predictor + if code & 8 != 0 { -diff } else { diff }).clamp(-32768, 32767);
+ index = (index + IMA_INDEX[(code & 7) as usize]).clamp(0, 88);
+ let at = 4 * i + 2 * half;
+ out[at..at + 2].copy_from_slice(&(predictor as i16).to_le_bytes());
+ }
+ }
+ codes.len() * 4
+}
+
+/// Counts presses that follow each other quickly: a press more than `gap` ms after the one before starts again at 1.
+#[derive(Clone, Copy)]
+pub struct MultiTap {
+ n: u8,
+ last: u32,
+}
+
+impl MultiTap {
+ pub const fn new() -> MultiTap {
+ MultiTap { n: 0, last: 0 }
+ }
+
+ /// A press at `now` (ms): how many quick presses in a row this is, counting it.
+ pub fn tap(&mut self, now: u32, gap: u32) -> u8 {
+ if self.n == 0 || now.wrapping_sub(self.last) > gap {
+ self.n = 1;
+ } else {
+ self.n = self.n.saturating_add(1);
+ }
+ self.last = now;
+ self.n
+ }
+
+ pub fn reset(&mut self) {
+ self.n = 0;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn ima_blocks_decode_like_the_sdks() {
+ // the SDK's shared vector: a 440 Hz sine at 16 kHz, the first block's first samples
+ let block: [u8; 19] = [0x00, 0x00, 0x00, 0x70, 0x77, 0x77, 0x77, 0x77, 0x80, 0x98, 0x98, 0x9a, 0xba, 0xba, 0xba, 0xaa, 0x89, 0x10, 0x42];
+ let want: [i16; 8] = [0, 11, 41, 104, 240, 533, 1164, 2521];
+ let mut out = [0u8; 64];
+ assert_eq!(ima_decode_block(&block, &mut out), 64);
+ for (k, w) in want.iter().enumerate() {
+ assert_eq!(i16::from_le_bytes([out[2 * k], out[2 * k + 1]]), *w);
+ }
+ assert_eq!(ima_decode_block(&[0, 0, 200, 1], &mut out), 0);
+ }
+
+ #[test]
+ fn three_quick_taps_count_three_and_slow_ones_do_not() {
+ let mut t = MultiTap::new();
+ assert_eq!(t.tap(1000, 500), 1);
+ assert_eq!(t.tap(1300, 500), 2);
+ assert_eq!(t.tap(1600, 500), 3);
+ t.reset();
+ assert_eq!(t.tap(2000, 500), 1);
+ assert_eq!(t.tap(2800, 500), 1, "too slow: starts again");
+ assert_eq!(t.tap(3100, 500), 2);
+ assert_eq!(t.tap(3400, 500), 3);
+ // the clock wraps
+ let mut w = MultiTap::new();
+ assert_eq!(w.tap(u32::MAX - 100, 500), 1);
+ assert_eq!(w.tap(100, 500), 2);
+ }
+
+ fn entry(buf: &mut [u8], p: &mut usize, title: &str, artist: &str) {
+ for s in [title, artist] {
+ buf[*p] = s.len() as u8;
+ buf[*p + 1..*p + 1 + s.len()].copy_from_slice(s.as_bytes());
+ *p += 1 + s.len();
+ }
+ }
+
+ fn list(m: &mut Model, songs: &[(&str, &str)]) {
+ m.apply(&[b'C', songs.len() as u8, 7]);
+ let mut msg = [0u8; 128];
+ msg[0] = b'T';
+ msg[2] = songs.len() as u8;
+ let mut p = 3;
+ for (t, a) in songs {
+ entry(&mut msg, &mut p, t, a);
+ }
+ m.apply(&msg[..p]);
+ }
+
+ #[test]
+ fn list_with_artists_arrives_and_saves() {
+ let mut m = Model::new();
+ list(&mut m, &[("One", "Ann"), ("Два", "Борис"), ("Three", "")]);
+ assert_eq!((m.count, m.version), (3, 7));
+ // the phone sends (first, second); SWAP_NAMES decides which one is the song
+ let (song, artist) = if SWAP_NAMES { ("Борис", "Два") } else { ("Два", "Борис") };
+ assert_eq!((m.title(1), m.artist(1)), (song, artist));
+ let mut blob = [0u8; 2560];
+ let n = m.save(&mut blob);
+ let mut again = Model::new();
+ again.load(&blob[..n]);
+ assert_eq!((again.count, again.version, again.title(1), again.artist(1)), (3, 7, song, artist));
+ }
+
+ #[test]
+ fn reset_clears_model_in_place_and_restores_defaults() {
+ let mut m = Model::new();
+ list(&mut m, &[("A song", "An artist"), ("Another", "Artist")]);
+ m.apply(&[b'N', 1, 1]);
+ m.apply(&[b'V', 82, 1, 1]);
+ m.apply(&[b'G', 10, 0, 40, 0]);
+ m.apply(&[b'H', 0x0F]);
+
+ m.reset();
+
+ assert_eq!(m.count, 0);
+ assert_eq!(m.version, 0);
+ assert_eq!(m.now, NONE);
+ assert!(!m.playing);
+ assert_eq!(m.level, 50);
+ assert!(!m.muted);
+ assert_eq!((m.pos, m.dur), (0, 0));
+ assert_eq!(m.mode, MODE_NONE);
+ assert!(!m.empty);
+ assert_eq!(m.home_flags, 0);
+ assert!(m.tracks.iter().all(|t| t.tlen == 0 && t.alen == 0));
+ }
+
+ #[test]
+ fn fifty_songs_fit_the_saved_blob() {
+ let mut m = Model::new();
+ m.count = 50;
+ for t in m.tracks.iter_mut() {
+ t.tlen = 40;
+ t.alen = 40;
+ }
+ let mut blob = [0u8; 2560];
+ assert!(m.save(&mut blob) <= 2560);
+ }
+
+ #[test]
+ fn colours_arrive_for_a_range() {
+ let mut m = Model::new();
+ list(&mut m, &[("A", ""), ("B", ""), ("C", "")]);
+ assert_eq!(m.tracks[1].c1, DEFAULT_C1);
+ let fx = m.apply(&[b'K', 1, 2, 0x34, 0x12, 0x78, 0x56, 0xBC, 0x9A, 0xF0, 0xDE]);
+ assert!(fx.colours);
+ assert_eq!((m.tracks[1].c1, m.tracks[1].c2), (0x1234, 0x5678));
+ assert_eq!((m.tracks[2].c1, m.tracks[2].c2), (0x9ABC, 0xDEF0));
+ assert_eq!(m.tracks[0].c1, DEFAULT_C1);
+ m.apply(&[b'K', 0, 5, 1, 2]); // cut short: nothing breaks
+ }
+
+ #[test]
+ fn quarters_arrive_and_default_to_the_pill_colour() {
+ let mut m = Model::new();
+ list(&mut m, &[("A", ""), ("B", ""), ("C", "")]);
+ assert_eq!(m.quarters(1), [DEFAULT_C1; 4]);
+ let fx = m.apply(&[b'Q', 1, 2, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0]);
+ assert!(fx.colours);
+ assert_eq!(m.quarters(1), [1, 2, 3, 4]);
+ assert_eq!(m.quarters(2), [5, 6, 7, 8]);
+ assert_eq!(m.quarters(0), [DEFAULT_C1; 4]);
+ assert_eq!(m.quarters(9), [DEFAULT_C1; 4]);
+ m.apply(&[b'Q', 0, 3, 1, 2, 3]); // cut short: nothing breaks
+ assert_eq!(m.quarters(0), [DEFAULT_C1; 4]);
+ m.apply(&[b'C', 3, 1]); // a new list forgets them
+ assert_eq!(m.quarters(1), [DEFAULT_C1; 4]);
+ }
+
+ #[test]
+ fn saved_flag_only_when_complete() {
+ let mut m = Model::new();
+ m.apply(&[b'C', 2, 1]);
+ assert!(!m.apply(&[b'T', 0, 1, 1, b'a', 0]).saved);
+ assert!(m.apply(&[b'T', 1, 1, 1, b'b', 0]).saved);
+ }
+
+ #[test]
+ fn repeated_external_status_keeps_album_quarter_colours() {
+ let mut m = Model::new();
+ let title = b"Video title";
+ let artist = b"Video app";
+ let mut x = vec![b'X', 1, title.len() as u8];
+ x.extend_from_slice(title);
+ x.push(artist.len() as u8);
+ x.extend_from_slice(artist);
+ m.apply(&x);
+ let q = [0xF800u16, 0x07E0, 0x001F, 0xFFFF];
+ let mut qm = vec![b'Q', 0, 1];
+ for c in q { qm.extend_from_slice(&c.to_le_bytes()); }
+ m.apply(&qm);
+ assert_eq!(m.quarters(0), q);
+
+ // Same title/artist with a play-state change is only a status update, not a new cover.
+ x[1] = 0;
+ m.apply(&x);
+ assert_eq!(m.quarters(0), q);
+ }
+
+ #[test]
+ fn external_media_message_replaces_the_player_metadata_without_a_playlist() {
+ let mut m = Model::new();
+ m.pick(MODE_EXTERNAL);
+ let title = b"A video playing";
+ let artist = b"Browser";
+ let mut msg = vec![b'X', 1, title.len() as u8];
+ msg.extend_from_slice(title);
+ msg.push(artist.len() as u8);
+ msg.extend_from_slice(artist);
+ let fx = m.apply(&msg);
+ assert!(fx.list && fx.now);
+ assert_eq!(m.mode, MODE_EXTERNAL);
+ assert_eq!(m.count, 1);
+ assert_eq!(m.now, 0);
+ assert_eq!((m.title(0), m.artist(0)), ("A video playing", "Browser"));
+ assert!(m.playing);
+
+ let paused = [b'X', 0, 8, b'N', b'o', b't', b'h', b'i', b'n', b'g', b' ', 0, 0];
+ let fx = m.apply(&paused);
+ assert!(fx.now);
+ assert_eq!(m.title(0), "Nothing ");
+ assert!(!m.playing);
+ }
+
+ #[test]
+ fn home_catalog_messages_preserve_mode_and_decode_category_bits() {
+ let mut m = Model::new();
+ let fx = m.apply(&[b'H', 0x0D]);
+ assert!(fx.home);
+ assert_eq!(m.home_flags, 0x0D);
+ assert_eq!(m.mode, MODE_NONE);
+ m.pick(MODE_CUSTOM);
+ let fx = m.apply(&[b'R', 0x06]);
+ assert!(fx.home);
+ assert_eq!(m.home_flags, 0x06);
+ assert_eq!(m.mode, MODE_CUSTOM);
+ }
+
+ #[test]
+ fn home_catalog_keeps_the_open_controls_bit() {
+ let mut m = Model::new();
+ m.apply(&[b'H', 0x18]);
+ assert_eq!(m.home_flags, 0x18);
+ m.apply(&[b'H', 0xFF]);
+ assert_eq!(m.home_flags, 0x1F);
+ }
+
+ #[test]
+ fn restore_row_arrives_before_the_rest_of_the_list() {
+ let mut m = Model::new();
+ m.apply(&[b'W']); // too short: ignored by the model, handled by main
+ m.pick(MODE_MUSIC);
+ m.apply(&[b'C', 30, 1]);
+ let mut msg = vec![b'T', 17, 1, 1, b'a', 1, b'b'];
+ m.apply(&msg);
+ assert!(m.tracks[17].tlen > 0);
+ assert_eq!(m.tracks[3].tlen, 0);
+ msg.clear();
+ }
+
+ #[test]
+ fn bad_input_is_ignored() {
+ let mut m = Model::new();
+ m.load(b"junk");
+ m.load(&[b'W', b'M', 4, 2, 0, 200]);
+ assert_eq!(m.count, 0);
+ assert_eq!(m.apply(&[]), Effect::default());
+ assert_eq!(m.apply(&[b'Z', 1, 2, 3]), Effect::default());
+ assert_eq!(m.apply(&[b'T', 0]), Effect::default());
+ m.apply(&[b'C', 2, 1]);
+ m.apply(&[b'T', 0, 1, 200, b'a']); // title longer than the message
+ assert_eq!(m.title(0), "");
+ assert_eq!(m.apply(&[b'G', 1, 0]), Effect::default());
+ }
+
+ #[test]
+ fn now_playing_volume_progress_and_play_state() {
+ let mut m = Model::new();
+ list(&mut m, &[("A", ""), ("B", ""), ("C", "")]);
+ assert!(m.apply(&[b'N', 1, 1]).now);
+ assert_eq!((m.now, m.playing), (1, true));
+ assert!(m.apply(&[b'S', 0]).now && !m.playing);
+ assert!(!m.apply(&[b'N', 1, 0]).now);
+ m.apply(&[b'N', 9, 1]);
+ assert_eq!(m.now, NONE);
+ let fx = m.apply(&[b'V', 130, 1, 1]);
+ assert!(fx.volume);
+ assert_eq!((m.level, m.muted), (100, true));
+ assert!(m.apply(&[b'G', 0x2C, 0x01, 0xB4, 0x00]).progress);
+ assert_eq!((m.pos, m.dur), (300, 180));
+ }
+
+ #[test]
+ fn long_titles_are_cut_on_a_character() {
+ let mut m = Model::new();
+ m.apply(&[b'C', 1, 1]);
+ let title = "ы".repeat(30); // 60 bytes
+ let mut msg = vec![b'T', 0, 1, title.len() as u8];
+ msg.extend_from_slice(title.as_bytes());
+ msg.push(0);
+ m.apply(&msg);
+ let long = if SWAP_NAMES { m.artist(0) } else { m.title(0) };
+ assert_eq!(long.chars().count(), 20);
+ }
+
+ #[test]
+ fn podcasts_are_not_swapped_and_a_new_episode_reaches_the_player() {
+ let mut m = Model::new();
+ m.pick(MODE_PODCAST);
+ assert_eq!((m.mode, m.count), (MODE_PODCAST, 0));
+ list(&mut m, &[("Episode 12", "The Show"), ("Other episode", "Other Show")]);
+ // the phone sends the episode first and the show second: the episode is the song line
+ assert_eq!((m.title(0), m.artist(0)), ("Episode 12", "The Show"));
+ m.apply(&[b'N', 0, 1]);
+ assert_eq!(m.now, 0);
+ // the phone moved to another episode of show 0: only that row is sent again
+ let mut msg = [0u8; 64];
+ msg[..3].copy_from_slice(&[b'T', 0, 1]);
+ let mut p = 3;
+ entry(&mut msg, &mut p, "Episode 13", "The Show");
+ let fx = m.apply(&msg[..p]);
+ assert!(fx.now && fx.list);
+ assert_eq!(m.title(0), "Episode 13");
+ // a row that does not play now does not ask for a redraw of the player
+ msg[1] = 1;
+ assert!(!m.apply(&msg[..p]).now);
+ // music is swapped again after `pick`
+ m.pick(MODE_MUSIC);
+ list(&mut m, &[("First", "Second")]);
+ assert_eq!(m.title(0), if SWAP_NAMES { "Second" } else { "First" });
+ }
+
+ #[test]
+ fn empty_list_and_pick() {
+ let mut m = Model::new();
+ assert_eq!(m.mode, MODE_NONE);
+ m.pick(MODE_PODCAST);
+ assert!(!m.empty);
+ m.apply(&[b'C', 0, 3]);
+ assert!(m.empty && m.count == 0);
+ m.apply(&[b'C', 2, 3]);
+ assert!(!m.empty);
+ m.apply(&[b'N', 1, 1]);
+ m.pick(MODE_MUSIC);
+ assert_eq!((m.count, m.now, m.playing), (0, NONE, false));
+ }
+
+ #[test]
+ fn volume_steps_and_text() {
+ assert_eq!(step_volume(50, 1), 55);
+ assert_eq!(step_volume(50, -1), 45);
+ assert_eq!(step_volume(98, 1), 100);
+ assert_eq!(step_volume(2, -1), 0);
+ assert_eq!(step_volume(0, -1), 0);
+ assert_eq!(step_volume(40, 0), 40);
+ let mut b = [0u8; 8];
+ assert_eq!(volume_text(0, &mut b), "Vol 0%");
+ assert_eq!(volume_text(5, &mut b), "Vol 5%");
+ assert_eq!(volume_text(65, &mut b), "Vol 65%");
+ assert_eq!(volume_text(100, &mut b), "Vol 100%");
+ assert_eq!(volume_text(250, &mut b), "Vol 100%");
+ }
+
+ #[test]
+ fn unsure_rows_are_turned_round() {
+ let mut m = Model::new();
+ m.pick(MODE_MUSIC);
+ // phone output: a decided row (artist Ann has two songs), and two undecided ones sent as (artist, song)
+ list(&mut m, &[("Song A", "Ann"), ("Song B", "Ann"), ("Bob", "Lonely Song"), ("Cy", "Other")]);
+ m.fix_order();
+ assert_eq!((m.title(0), m.artist(0)), ("Song A", "Ann"));
+ assert_eq!((m.title(1), m.artist(1)), ("Song B", "Ann"));
+ assert_eq!((m.title(2), m.artist(2)), ("Lonely Song", "Bob"));
+ assert_eq!((m.title(3), m.artist(3)), ("Other", "Cy"));
+ m.pick(MODE_PODCAST);
+ list(&mut m, &[("Episode", "Show")]);
+ m.fix_order();
+ assert_eq!(m.title(0), "Episode");
+ }
+
+ #[test]
+ fn elapsed_and_progress() {
+ let mut m = Model::new();
+ m.apply(&[b'C', 1, 1]);
+ m.apply(&[b'N', 0, 1]);
+ m.apply(&[b'G', 10, 0, 100, 0]);
+ assert_eq!(m.elapsed(2500), 12);
+ assert_eq!(m.elapsed(500_000), 100); // never past the end
+ m.playing = false;
+ assert_eq!(m.elapsed(5000), 10);
+ assert_eq!(permille(50, 100), 500);
+ assert_eq!(permille(5, 0), 0);
+ }
+
+ #[test]
+ fn fingerprint_changes_only_with_what_the_list_shows() {
+ let mut m = Model::new();
+ m.apply(&[b'C', 2, 1]);
+ m.apply(&[b'T', 0, 2, 1, b'a', 1, b'x', 1, b'b', 1, b'y']);
+ let f = m.fingerprint();
+ m.apply(&[b'C', 2, 1]);
+ m.apply(&[b'T', 0, 2, 1, b'a', 1, b'x', 1, b'b', 1, b'y']);
+ assert_eq!(m.fingerprint(), f);
+ m.apply(&[b'K', 0, 1, 1, 0, 2, 0]);
+ assert_eq!(m.fingerprint(), f);
+ m.apply(&[b'T', 1, 1, 1, b'c', 1, b'y']);
+ assert_ne!(m.fingerprint(), f);
+ }
+
+ #[test]
+ fn heart_follows_the_phone_and_flips_on_tap() {
+ let mut m = Model::new();
+ assert_eq!(m.liked, LIKED_UNKNOWN);
+ assert!(!m.toggle_liked(), "no heart until the phone says it keeps saved songs");
+ assert!(m.apply(&[b'L', 1]).liked);
+ assert_eq!(m.liked, LIKED_YES);
+ assert!(!m.apply(&[b'L', 1]).liked, "same state again: nothing to redraw");
+ assert!(m.toggle_liked());
+ assert_eq!(m.liked, LIKED_NO);
+ m.reset();
+ assert_eq!(m.liked, LIKED_UNKNOWN);
+ }
+
+ #[test]
+ fn double_tap_seek_is_clamped_and_needs_a_length() {
+ let mut m = Model::new();
+ assert_eq!(m.seek_permille(10, 5), None);
+ m.dur = 200;
+ assert_eq!(m.seek_permille(100, 5), Some((525, 105)));
+ assert_eq!(m.seek_permille(3, -5), Some((0, 0)));
+ assert_eq!(m.seek_permille(198, 5), Some((1000, 200)));
+ }
+}
diff --git a/apps/watch-music/src/photo.rs b/apps/watch-music/src/photo.rs
new file mode 100644
index 0000000..3043e6d
--- /dev/null
+++ b/apps/watch-music/src/photo.rs
@@ -0,0 +1,650 @@
+//! Cover pictures as real images: compressed by the phone to well under a kilobyte, unpacked on the watch into one
+//! pixel buffer that an LVGL image object draws. No `Api` and no LVGL in here, so `cargo test` runs it on the
+//! computer.
+//!
+//! Watch -> phone: `a` idx 44 150 1 `OK`, the list stopped on song `idx`: send its cover. (The middle bytes are what
+//! an older phone app needs to read the request; `OK` asks for a real picture.)
+//! Phone -> watch (1..=128 bytes):
+//!
+//! `P` idx kind q(u16 LE) offset(u16 LE) total(u16 LE) bytes*
+//! bytes `offset..` of song `idx`'s picture, `total` bytes in all, sent in order. `kind` 0 = square
+//! (`SQUARE` x `SQUARE`), 1 = 16:9 (`WIDE_W` x `WIDE_H`). `q` is the quantiser. `total` 0 = no cover.
+//!
+//! The bytes are one stream of an adaptive binary range coder (as in LZMA) over 8 x 8 cosine-transform blocks of
+//! Y, Cb, Cr (colour at half size), in groups of 16 x 16 pixels, row by row. First come the averages of all blocks
+//! (enough for a soft preview after about the first message), then each group's detail, so the picture sharpens from
+//! the top while the rest is still on its way. The phone's encoder (PhotoCodec.kt) mirrors this file exactly.
+
+/// The watch's request for the cover of song `idx`.
+pub fn request(idx: u8) -> [u8; 6] {
+ [b'a', idx, 44, 150, 1, 1]
+}
+
+/// Where a song's picture stands.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Status {
+ /// never asked for (or pushed out by newer ones)
+ Unknown,
+ /// asked; the picture has not fully arrived
+ Waiting,
+ /// all of it is here
+ Ready,
+ /// the phone has no cover for this song
+ NoCover,
+}
+pub const SQUARE: usize = 88;
+pub const WIDE_W: usize = 128;
+pub const WIDE_H: usize = 72;
+/// The pixel buffer holds the larger of the two.
+pub const PIXELS: usize = WIDE_W * WIDE_H;
+/// The longest picture accepted.
+pub const MAX_BYTES: usize = 840;
+/// How many songs' pictures stay in RAM, so scrolling back to one is instant.
+pub const SLOTS: usize = 6;
+const HEADER: usize = 9;
+const NONE: u8 = 0xFF;
+/// Blocks of the larger picture (padded to whole groups of 16 x 16): 8 x 5 groups of 6.
+const MAX_BLOCKS: usize = 240;
+
+#[derive(Clone, Copy)]
+struct Slot {
+ idx: u8,
+ wide: bool,
+ no_cover: bool,
+ q: u16,
+ have: u16,
+ total: u16,
+ data: [u8; MAX_BYTES],
+}
+
+const EMPTY: Slot = Slot { idx: NONE, wide: false, no_cover: false, q: 0, have: 0, total: 0, data: [0; MAX_BYTES] };
+
+pub struct Photos {
+ slots: [Slot; SLOTS],
+ next: usize,
+}
+
+pub fn size(wide: bool) -> (usize, usize) {
+ if wide { (WIDE_W, WIDE_H) } else { (SQUARE, SQUARE) }
+}
+
+/// What is held of one picture.
+pub struct Held<'a> {
+ pub wide: bool,
+ pub q: u16,
+ pub data: &'a [u8],
+}
+
+impl Photos {
+ pub const fn new() -> Photos {
+ Photos { slots: [EMPTY; SLOTS], next: 0 }
+ }
+
+ /// Forgets every picture (another list is on the watch). Done in place: no second copy on the small stack.
+ pub fn clear(&mut self) {
+ for s in self.slots.iter_mut() {
+ reset(s, NONE);
+ }
+ self.next = 0;
+ }
+
+ fn find(&self, idx: u8) -> Option {
+ if idx == NONE {
+ return None;
+ }
+ self.slots.iter().position(|s| s.idx == idx)
+ }
+
+ /// Song `idx` is asked for: it keeps its slot (and what has arrived), or takes the oldest one.
+ pub fn begin(&mut self, idx: u8) {
+ if idx == NONE || self.find(idx).is_some() {
+ return;
+ }
+ let i = self.next;
+ self.next = (self.next + 1) % SLOTS;
+ reset(&mut self.slots[i], idx);
+ }
+
+ pub fn status(&self, idx: u8) -> Status {
+ match self.find(idx).map(|i| &self.slots[i]) {
+ None => Status::Unknown,
+ Some(s) if s.no_cover => Status::NoCover,
+ Some(s) if s.total != 0 && s.have == s.total => Status::Ready,
+ Some(_) => Status::Waiting,
+ }
+ }
+
+ /// The bytes of song `idx`'s picture so far, if any.
+ pub fn held(&self, idx: u8) -> Option> {
+ let s = &self.slots[self.find(idx)?];
+ if s.have == 0 {
+ return None;
+ }
+ Some(Held { wide: s.wide, q: s.q, data: &s.data[..s.have as usize] })
+ }
+
+ /// Applies one `P` message; true when it added something. Anything unasked, out of order or malformed is ignored.
+ pub fn apply(&mut self, m: &[u8]) -> bool {
+ if m.len() < HEADER || m[0] != b'P' || m[2] > 1 {
+ return false;
+ }
+ let Some(i) = self.find(m[1]) else { return false };
+ let wide = m[2] == 1;
+ let q = u16::from_le_bytes([m[3], m[4]]);
+ let at = u16::from_le_bytes([m[5], m[6]]) as usize;
+ let total = u16::from_le_bytes([m[7], m[8]]) as usize;
+ let bytes = &m[HEADER..];
+ let s = &mut self.slots[i];
+ if total == 0 {
+ reset(s, m[1]);
+ s.no_cover = true;
+ return true;
+ }
+ if q == 0 || q > 2048 || total > MAX_BYTES || bytes.is_empty() || at + bytes.len() > total {
+ return false;
+ }
+ if s.total as usize != total || s.q != q || s.wide != wide {
+ // another picture than the half held (the cover changed): only its first piece starts it
+ if at != 0 {
+ return false;
+ }
+ reset(s, m[1]);
+ s.wide = wide;
+ s.q = q;
+ s.total = total as u16;
+ }
+ let have = s.have as usize;
+ // pieces come in order; one sent again overlaps what is here and adds nothing
+ if at > have || at + bytes.len() <= have {
+ return false;
+ }
+ s.data[at..at + bytes.len()].copy_from_slice(bytes);
+ s.have = (at + bytes.len()) as u16;
+ true
+ }
+}
+
+fn reset(s: &mut Slot, idx: u8) {
+ s.idx = idx;
+ s.wide = false;
+ s.no_cover = false;
+ s.q = 0;
+ s.have = 0;
+ s.total = 0;
+}
+
+// ---- unpacking --------------------------------------------------------------------------------------------------
+
+/// The cosine basis, 12 bits: `BASIS[u][x]`.
+const BASIS: [[i32; 8]; 8] = [
+ [1448, 1448, 1448, 1448, 1448, 1448, 1448, 1448],
+ [2009, 1703, 1138, 400, -400, -1138, -1703, -2009],
+ [1892, 784, -784, -1892, -1892, -784, 784, 1892],
+ [1703, -400, -2009, -1138, 1138, 2009, 400, -1703],
+ [1448, -1448, -1448, 1448, 1448, -1448, -1448, 1448],
+ [1138, -2009, 400, 1703, -1703, -400, 2009, -1138],
+ [784, -1892, 1892, -784, -784, 1892, -1892, 784],
+ [400, -1138, 1703, -2009, 2009, -1703, 1138, -400],
+];
+/// The order of a block's coefficients, from coarse to fine (row * 8 + column).
+const ZIGZAG: [u8; 64] = [
+ 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21,
+ 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61,
+ 54, 47, 55, 62, 63,
+];
+const BAYER: [[i32; 4]; 4] = [[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]];
+const HALF: u16 = 1024;
+const LEVEL_MAX: i32 = 2047;
+
+/// Which group of coefficient positions shares the "bigger than one" odds.
+fn band(p: usize) -> usize {
+ match p {
+ 0..=2 => 0,
+ 3..=5 => 1,
+ 6..=9 => 2,
+ 10..=14 => 3,
+ 15..=21 => 4,
+ 22..=35 => 5,
+ _ => 6,
+ }
+}
+
+/// Working memory of the unpacker, kept off the watch's small stack.
+pub struct Work {
+ /// the average of every block (the preview, and each block's prediction)
+ dc: [i16; MAX_BLOCKS],
+ // the odds
+ dc_zero: [u16; 2],
+ dc_mag: [u16; 24],
+ more: [u16; 128],
+ nonzero: [u16; 128],
+ one: [u16; 14],
+ mag: [u16; 24],
+ block: [i32; 64],
+ pixels: [u8; 6 * 64],
+}
+
+impl Work {
+ pub const fn new() -> Work {
+ Work {
+ dc: [0; MAX_BLOCKS],
+ dc_zero: [HALF; 2],
+ dc_mag: [HALF; 24],
+ more: [HALF; 128],
+ nonzero: [HALF; 128],
+ one: [HALF; 14],
+ mag: [HALF; 24],
+ block: [0; 64],
+ pixels: [0; 6 * 64],
+ }
+ }
+
+ fn start(&mut self) {
+ self.dc_zero = [HALF; 2];
+ self.dc_mag = [HALF; 24];
+ self.more = [HALF; 128];
+ self.nonzero = [HALF; 128];
+ self.one = [HALF; 14];
+ self.mag = [HALF; 24];
+ }
+}
+
+struct Coder<'a> {
+ data: &'a [u8],
+ at: usize,
+ range: u32,
+ code: u32,
+}
+
+impl<'a> Coder<'a> {
+ fn new(data: &'a [u8]) -> Coder<'a> {
+ let mut c = Coder { data, at: 0, range: u32::MAX, code: 0 };
+ for _ in 0..4 {
+ c.code = (c.code << 8) | c.byte();
+ }
+ c
+ }
+
+ fn byte(&mut self) -> u32 {
+ let v = self.data.get(self.at).copied().unwrap_or(0);
+ self.at += 1;
+ v as u32
+ }
+
+ /// Everything read so far had really arrived.
+ fn whole(&self) -> bool {
+ self.at <= self.data.len()
+ }
+
+ fn refill(&mut self) {
+ while self.range < 1 << 24 {
+ self.range <<= 8;
+ self.code = (self.code << 8) | self.byte();
+ }
+ }
+
+ fn bit(&mut self, p: &mut u16) -> bool {
+ let bound = (self.range >> 11) * *p as u32;
+ let one = self.code >= bound;
+ if one {
+ self.code -= bound;
+ self.range -= bound;
+ *p -= *p >> 4;
+ } else {
+ self.range = bound;
+ *p += (2048 - *p) >> 4;
+ }
+ self.refill();
+ one
+ }
+
+ fn flat(&mut self) -> bool {
+ self.range >>= 1;
+ let one = self.code >= self.range;
+ if one {
+ self.code -= self.range;
+ }
+ self.refill();
+ one
+ }
+
+ /// A number from 0 up: its length in ones (with odds), then its bits.
+ fn number(&mut self, p: &mut [u16]) -> i32 {
+ let mut n = 0;
+ while n < 12 && self.bit(&mut p[n.min(11)]) {
+ n += 1;
+ }
+ let mut v = 1i32;
+ for _ in 0..n {
+ v = (v << 1) | self.flat() as i32;
+ }
+ v - 1
+ }
+}
+
+fn step(q: i32, chroma: bool, f: usize) -> i32 {
+ let w = match (f, chroma) {
+ (0, false) => 10,
+ (0, true) => 12,
+ (f, false) => 16 + 3 * f as i32,
+ (f, true) => 14 + 4 * f as i32,
+ };
+ ((q * w + 8) / 16).max(1)
+}
+
+/// The level around the block's average, predicted from its neighbours left and above.
+fn predict(left: Option, top: Option, corner: i32) -> i32 {
+ match (left, top) {
+ (None, None) => 0,
+ (Some(l), None) => l,
+ (None, Some(t)) => t,
+ (Some(l), Some(t)) => {
+ let (hi, lo) = (l.max(t), l.min(t));
+ if corner >= hi { lo } else if corner <= lo { hi } else { l + t - corner }
+ }
+ }
+}
+
+/// Where each plane's averages sit in `Work::dc`: (first, blocks across). Y has 2 x 2 blocks per group.
+fn plane(c: usize, groups: (usize, usize)) -> (usize, usize) {
+ let (gw, gh) = groups;
+ match c {
+ 0 => (0, 2 * gw),
+ 1 => (4 * gw * gh, gw),
+ _ => (5 * gw * gh, gw),
+ }
+}
+
+/// The six blocks of one group: (plane, column, row) of each.
+fn group_blocks(gx: usize, gy: usize) -> [(usize, usize, usize); 6] {
+ [
+ (0, 2 * gx, 2 * gy), (0, 2 * gx + 1, 2 * gy), (0, 2 * gx, 2 * gy + 1), (0, 2 * gx + 1, 2 * gy + 1),
+ (1, gx, gy), (2, gx, gy),
+ ]
+}
+
+/// RGB565 of one pixel, with a fine fixed grain that hides the steps between the screen's colours.
+fn pack(x: usize, y: usize, luma: i32, cb: i32, cr: i32) -> u16 {
+ let (cb, cr) = (cb - 128, cr - 128);
+ let r = luma + ((91881 * cr + 32768) >> 16);
+ let g = luma - ((22554 * cb + 46802 * cr + 32768) >> 16);
+ let b = luma + ((116130 * cb + 32768) >> 16);
+ let t = BAYER[y & 3][x & 3];
+ let r = (r + (t >> 1) - 4).clamp(0, 255) >> 3;
+ let g = (g + (t >> 2) - 2).clamp(0, 255) >> 2;
+ let b = (b + (t >> 1) - 4).clamp(0, 255) >> 3;
+ ((r << 11) | (g << 5) | b) as u16
+}
+
+/// The soft preview: every pixel a smooth mix of the four block averages around it.
+fn preview(w: &Work, q: i32, wide: bool, px: &mut [u16]) {
+ let (width, height) = size(wide);
+ let groups = (width.div_ceil(16), height.div_ceil(16));
+ let value = |c: usize, i: usize| {
+ let st = step(q, c > 0, 0);
+ (((w.dc[i] as i32 * st + 4) >> 3) + 128).clamp(0, 255)
+ };
+ // `at` is a position in units of 1/`unit` of a block, from the first block's centre
+ let mix = |c: usize, at_x: i32, at_y: i32, unit: i32| {
+ let (first, across) = plane(c, groups);
+ let down = if c == 0 { 2 * groups.1 } else { groups.1 };
+ let split = |at: i32, n: usize| {
+ let at = at.clamp(0, (n as i32 - 1) * unit);
+ let i = (at / unit) as usize;
+ (i, (i + 1).min(n - 1), at % unit)
+ };
+ let (x0, x1, fx) = split(at_x, across);
+ let (y0, y1, fy) = split(at_y, down);
+ let row = |y: usize| value(c, first + y * across + x0) * (unit - fx) + value(c, first + y * across + x1) * fx;
+ (row(y0) * (unit - fy) + row(y1) * fy + unit * unit / 2) / (unit * unit)
+ };
+ for y in 0..height {
+ for x in 0..width {
+ let (lx, ly) = (2 * x as i32 - 7, 2 * y as i32 - 7);
+ let (cx, cy) = (2 * x as i32 - 15, 2 * y as i32 - 15);
+ px[y * width + x] = pack(x, y, mix(0, lx, ly, 16), mix(1, cx, cy, 32), mix(2, cx, cy, 32));
+ }
+ }
+}
+
+/// One block's levels in `w.block` to 8 x 8 pixels at `w.pixels[at..]`.
+fn transform(w: &mut Work, at: usize) {
+ let mut t = [0i32; 64];
+ for x in 0..8 {
+ for v in 0..8 {
+ let mut sum = 0i32;
+ for u in 0..8 {
+ sum = sum.wrapping_add(BASIS[u][x].wrapping_mul(w.block[u * 8 + v]));
+ }
+ t[x * 8 + v] = (sum.wrapping_add(64) >> 7).clamp(-100_000, 100_000);
+ }
+ }
+ for x in 0..8 {
+ for y in 0..8 {
+ let mut sum = 0i32;
+ for v in 0..8 {
+ sum = sum.wrapping_add(t[x * 8 + v].wrapping_mul(BASIS[v][y]));
+ }
+ w.pixels[at + x * 8 + y] = ((sum.wrapping_add(1 << 16) >> 17) + 128).clamp(0, 255) as u8;
+ }
+ }
+}
+
+/// Draws group (`gx`, `gy`) from `w.pixels` into the picture.
+fn paint(w: &Work, gx: usize, gy: usize, wide: bool, px: &mut [u16]) {
+ let (width, height) = size(wide);
+ // the colour between four half-size samples, in quarters
+ let colour = |at: usize, x: usize, y: usize| {
+ let split = |v: usize| {
+ let p = (2 * v as i32 - 1).clamp(0, 28) as usize;
+ (p / 4, (p / 4 + 1).min(7), (p % 4) as i32)
+ };
+ let (x0, x1, fx) = split(x);
+ let (y0, y1, fy) = split(y);
+ let row = |r: usize| w.pixels[at + r * 8 + x0] as i32 * (4 - fx) + w.pixels[at + r * 8 + x1] as i32 * fx;
+ (row(y0) * (4 - fy) + row(y1) * fy + 8) / 16
+ };
+ for y in 0..16 {
+ let py = gy * 16 + y;
+ if py >= height {
+ break;
+ }
+ for x in 0..16 {
+ let px_x = gx * 16 + x;
+ if px_x >= width {
+ break;
+ }
+ let luma = w.pixels[(y / 8 * 2 + x / 8) * 64 + (y % 8) * 8 + x % 8] as i32;
+ px[py * width + px_x] = pack(px_x, py, luma, colour(4 * 64, x, y), colour(5 * 64, x, y));
+ }
+ }
+}
+
+/// How far a picture has been drawn: whole groups of 16 x 16 pixels, from the top left.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub struct Drawn {
+ pub groups: usize,
+ pub all: bool,
+}
+
+/// Unpacks what has arrived of a picture into `px` (`size(wide)`, row by row). `None` while not even the preview is
+/// there. With `done` 0 the preview is drawn first; with the groups already on show, only the later ones are written,
+/// so a picture on the screen never goes back to the blur.
+pub fn draw(w: &mut Work, wide: bool, q: u16, data: &[u8], done: usize, px: &mut [u16]) -> Option {
+ let (width, height) = size(wide);
+ let groups = (width.div_ceil(16), height.div_ceil(16));
+ let q = q as i32;
+ if px.len() < width * height {
+ return None;
+ }
+ w.start();
+ let mut c = Coder::new(data);
+ for gy in 0..groups.1 {
+ for gx in 0..groups.0 {
+ for (p, x, y) in group_blocks(gx, gy) {
+ let k = (p > 0) as usize;
+ let (first, across) = plane(p, groups);
+ let at = first + y * across + x;
+ let mut diff = 0;
+ if c.bit(&mut w.dc_zero[k]) {
+ let negative = c.flat();
+ diff = c.number(&mut w.dc_mag[k * 12..k * 12 + 12]) + 1;
+ if negative {
+ diff = -diff;
+ }
+ }
+ let left = (x > 0).then(|| w.dc[at - 1] as i32);
+ let top = (y > 0).then(|| w.dc[at - across] as i32);
+ let corner = if x > 0 && y > 0 { w.dc[at - across - 1] as i32 } else { 0 };
+ w.dc[at] = (predict(left, top, corner) + diff).clamp(-LEVEL_MAX, LEVEL_MAX) as i16;
+ }
+ }
+ }
+ if !c.whole() {
+ return None;
+ }
+ if done == 0 {
+ preview(w, q, wide, px);
+ }
+ let mut count = 0;
+ for gy in 0..groups.1 {
+ for gx in 0..groups.0 {
+ for (n, (p, x, y)) in group_blocks(gx, gy).into_iter().enumerate() {
+ let k = (p > 0) as usize;
+ let (first, across) = plane(p, groups);
+ w.block = [0; 64];
+ w.block[0] = w.dc[first + y * across + x] as i32 * step(q, p > 0, 0);
+ let mut i = 1;
+ let mut ask = true;
+ while i < 64 {
+ if ask && !c.bit(&mut w.more[k * 64 + i]) {
+ break;
+ }
+ // the last place needs no "is it zero": something was promised, so it is there
+ if i < 63 && !c.bit(&mut w.nonzero[k * 64 + i]) {
+ i += 1;
+ ask = false;
+ continue;
+ }
+ let negative = c.flat();
+ let mut v = 1;
+ if c.bit(&mut w.one[k * 7 + band(i)]) {
+ v = (c.number(&mut w.mag[k * 12..k * 12 + 12]) + 2).min(LEVEL_MAX);
+ }
+ if negative {
+ v = -v;
+ }
+ let z = ZIGZAG[i] as usize;
+ w.block[z] = (v * step(q, p > 0, z / 8 + z % 8)).clamp(-2048, 2048);
+ i += 1;
+ ask = true;
+ }
+ if !c.whole() {
+ return Some(Drawn { groups: count, all: false });
+ }
+ if count >= done {
+ transform(w, n * 64);
+ }
+ }
+ if count >= done {
+ paint(w, gx, gy, wide, px);
+ }
+ count += 1;
+ }
+ }
+ Some(Drawn { groups: count, all: true })
+}
+
+#[cfg(test)]
+mod tests {
+ extern crate std;
+ use super::*;
+ use std::{boxed::Box, vec, vec::Vec};
+
+ fn msg(idx: u8, kind: u8, q: u16, at: u16, total: u16, bytes: &[u8]) -> Vec {
+ let mut m = vec![b'P', idx, kind];
+ for v in [q, at, total] {
+ m.extend_from_slice(&v.to_le_bytes());
+ }
+ m.extend_from_slice(bytes);
+ m
+ }
+
+ #[test]
+ fn pieces_collect_in_order() {
+ let mut p = Box::new(Photos::new());
+ // never asked for
+ assert!(!p.apply(&msg(3, 0, 20, 0, 6, &[1, 2, 3])));
+ p.begin(3);
+ assert!(p.status(3) == Status::Waiting && p.held(3).is_none());
+ // a gap
+ assert!(!p.apply(&msg(3, 0, 20, 3, 6, &[4, 5, 6])));
+ assert!(p.apply(&msg(3, 0, 20, 0, 6, &[1, 2, 3])));
+ // sent again: nothing new; asked again: what arrived stays
+ assert!(!p.apply(&msg(3, 0, 20, 0, 6, &[1, 2, 3])));
+ p.begin(3);
+ assert_eq!(p.status(3), Status::Waiting);
+ assert!(p.apply(&msg(3, 0, 20, 3, 6, &[4, 5, 6])));
+ assert_eq!(p.status(3), Status::Ready);
+ assert_eq!(p.held(3).unwrap().data, &[1, 2, 3, 4, 5, 6]);
+ // longer than said, or than the buffer
+ p.begin(4);
+ assert!(!p.apply(&msg(4, 0, 20, 0, 2, &[1, 2, 3])));
+ assert!(!p.apply(&msg(4, 0, 20, 0, MAX_BYTES as u16 + 1, &[1])));
+ assert!(p.apply(&msg(4, 0, 1, 0, 0, &[])));
+ assert_eq!(p.status(4), Status::NoCover);
+ }
+
+ #[test]
+ fn the_oldest_slot_is_reused_and_clear_forgets() {
+ let mut p = Box::new(Photos::new());
+ for i in 0..=SLOTS as u8 {
+ p.begin(i);
+ }
+ assert!(p.status(0) == Status::Unknown && p.status(SLOTS as u8) == Status::Waiting);
+ p.clear();
+ assert_eq!(p.status(1), Status::Unknown);
+ }
+
+ #[test]
+ fn noise_and_cut_off_bytes_never_break_it() {
+ let mut w = Box::new(Work::new());
+ let mut px = vec![0u16; PIXELS];
+ let mut seed = 7u32;
+ for round in 0..300 {
+ let data: Vec = (0..1 + round * 7 % MAX_BYTES)
+ .map(|_| {
+ seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
+ (seed >> 24) as u8
+ })
+ .collect();
+ draw(&mut w, round % 2 == 0, 1 + (round * 31 % 2048) as u16, &data, round % 9, &mut px);
+ }
+ assert_eq!(draw(&mut w, false, 20, &[1], 0, &mut px), None);
+ }
+
+ /// The phone's encoder and this unpacker agree: pictures made by PhotoCodec.kt come out as expected, whole and
+ /// piece by piece.
+ #[test]
+ fn pictures_from_the_phone_unpack() {
+ for (wide, q, data, sum) in crate::photo_vectors::VECTORS {
+ let mut w = Box::new(Work::new());
+ let (width, height) = size(*wide);
+ let mut whole = vec![0u16; width * height];
+ assert!(draw(&mut w, *wide, *q, data, 0, &mut whole).unwrap().all);
+ let hash = whole.iter().fold(0u32, |h, &v| h.wrapping_mul(31).wrapping_add(v as u32));
+ assert_eq!(hash, *sum);
+ let mut grown = vec![0u16; width * height];
+ let mut done = 0;
+ let mut previews = 0;
+ for end in (119..data.len() + 119).step_by(119) {
+ let Some(d) = draw(&mut w, *wide, *q, &data[..end.min(data.len())], done, &mut grown) else { continue };
+ assert!(d.groups >= done);
+ previews += (done == 0) as usize;
+ done = d.groups;
+ }
+ assert!(previews >= 1);
+ assert_eq!(grown, whole);
+ }
+ }
+}
diff --git a/apps/watch-music/src/photo_vectors.rs b/apps/watch-music/src/photo_vectors.rs
new file mode 100644
index 0000000..e4bd99b
--- /dev/null
+++ b/apps/watch-music/src/photo_vectors.rs
@@ -0,0 +1,10 @@
+//! Pictures packed by the phone app's PhotoCodec.kt, for the unpacker's tests: (wide, q, bytes, checksum of pixels).
+
+#[rustfmt::skip]
+pub const VECTORS: &[(bool, u16, &[u8], u32)] = &[
+ (false, 39, &[253, 23, 53, 122, 173, 94, 33, 170, 19, 142, 179, 69, 104, 85, 234, 24, 193, 168, 249, 159, 15, 99, 146, 150, 92, 111, 32, 98, 128, 201, 39, 249, 80, 29, 250, 141, 143, 21, 206, 143, 19, 173, 150, 180, 146, 110, 238, 198, 31, 133, 43, 146, 235, 86, 188, 22, 74, 46, 188, 164, 199, 136, 131, 176, 217, 141, 65, 67, 235, 177, 134, 88, 42, 123, 198, 73, 171, 161, 190, 123, 58, 205, 53, 250, 199, 232, 42, 0, 147, 218, 95, 127, 136, 158, 149, 75, 183, 205, 164, 27, 229, 255, 97, 250, 226, 11, 62, 140, 233, 127, 17, 171, 110, 179, 129, 145, 211, 25, 14, 18, 52, 24, 218, 22, 32, 113, 223, 207, 228, 152, 172, 72, 11, 137, 161, 100, 214, 244, 176, 242, 15, 103, 163, 227, 226, 39, 235, 186, 2, 38, 100, 9, 255, 29, 168, 213, 199, 133, 243, 105, 36, 133, 114, 114, 156, 232, 76, 253, 205, 140, 52, 165, 162, 174, 171, 96, 229, 153, 184, 48, 51, 64, 3, 113, 88, 94, 163, 69, 190, 209, 186, 40, 177, 69, 135, 185, 237, 86, 171, 178, 184, 167, 212, 161, 4, 67, 41, 193, 61, 66, 108, 158, 243, 32, 46, 51, 91, 65, 230, 43, 131, 1, 158, 161, 137, 83, 138, 250, 29, 212, 145, 134, 198, 116, 25, 2, 36, 60, 192, 17, 33, 68, 146, 185, 201, 179, 26, 103, 33, 155, 202, 51, 47, 142, 155, 49, 79, 248, 184, 174, 248, 232, 228, 212, 87, 168, 233, 52, 4, 109, 66, 201, 39, 244, 69, 125, 191, 41, 28, 150, 10, 190, 83, 62, 133, 100, 181, 189, 163, 227, 107, 134, 215, 36, 32, 172, 158, 58, 17, 109, 103, 116, 157, 212, 26, 92, 203, 80, 168, 91, 61, 155, 244, 222, 214, 68, 97, 141, 104, 50, 93, 17, 188, 198, 108, 113, 184, 162, 5, 15, 216, 236, 104, 110, 98, 215, 196, 141, 239, 128, 3, 178, 248, 241, 123, 25, 27, 195, 131, 143, 114, 108, 96, 63, 4, 143, 216, 86, 112, 227, 68, 254, 178, 105, 77, 44, 170, 46, 192, 243, 68, 119, 41, 231, 138, 99, 18, 243, 240, 164, 235, 205, 148, 149, 32, 131, 136, 211, 199, 79, 228, 55, 1, 187, 211, 57, 30, 218, 235, 186, 122, 57, 185, 109, 140, 212, 49, 15, 52, 95, 80, 33, 153, 171, 206, 145, 16, 7, 118, 174, 25, 39, 86, 164, 172, 221, 52, 121, 96, 52, 166, 224, 124, 157, 253, 58, 24, 213, 208, 212, 78, 245, 64, 78, 228, 236, 233, 130, 220, 215, 14, 161, 175, 203, 93, 207, 138, 29, 138, 236, 112, 42, 68, 214, 134, 8, 102, 196, 36, 87, 100, 54, 7, 120, 114, 17, 131, 79, 191, 75, 124, 29, 225, 14, 8, 49, 52, 129, 186, 206, 65, 227, 160, 119, 12, 215, 24, 215, 113, 168, 52, 221, 117, 2, 73, 204, 200, 84, 46, 92, 84, 7, 191, 128, 224, 80, 165, 182, 51, 9, 130, 69, 249, 113, 99, 46, 43, 68, 136, 208, 120, 112, 19, 13, 37, 148, 185, 185, 217, 138, 229, 167, 202, 141, 144, 30, 47, 54, 208, 248, 174, 227, 182, 14, 181, 232, 208, 200, 93, 213, 58, 227, 61, 121, 70, 96, 24, 179, 7, 27, 111, 98, 191, 6, 5, 145, 172, 237, 75, 187, 15, 29, 242, 177, 23, 116, 150, 59, 39, 95, 106, 176, 143, 180, 236, 88, 46, 98, 227, 51, 252, 246, 43, 245, 99, 29, 253, 84, 187, 219, 43, 209, 49, 87, 16, 74, 155, 164, 162, 98, 14, 73, 45, 51, 127, 223, 52, 111, 243, 30, 63, 223, 185, 215, 158, 160, 226, 69, 172, 201, 79, 68, 60, 217, 207, 144, 189, 112, 112, 177, 143, 61, 168, 48, 128, 226, 223, 178, 251, 75, 84, 207, 241, 218, 196, 45, 48, 50, 188, 146, 32, 157, 217, 139, 204, 98, 42, 133, 238, 202, 248, 82, 167, 205, 27, 107, 254, 239, 23, 84, 87, 172, 99, 19, 43, 125, 14, 91, 32, 79, 56, 44, 148, 21, 221, 210, 84, 141, 64, 159, 209, 221, 21, 229, 167, 156, 70, 77, 88, 236, 156, 141, 176, 136, 183, 151, 124, 87, 34, 240, 150, 227, 48, 248, 20, 230, 73, 146, 91, 191, 72, 71, 37, 236, 5, 89, 32, 27, 0, 137, 45, 250, 62, 220, 94, 38, 140, 133, 84, 248, 124, 105, 247, 20, 1, 146, 181, 204, 228, 134, 159, 82, 96, 64, 216, 222, 102, 122, 154, 10, 190, 95, 53, 249, 252, 95, 87, 93, 48, 18, 52, 153, 49, 26, 20, 134, 18, 124, 179, 205, 255, 89, 34, 171, 150, 80, 89, 86, 235, 189, 82, 14, 145, 204, 31, 23, 186, 94, 44, 241, 39, 66, 134, 175, 161, 196, 41, 204, 0], 789206848),
+ (false, 16, &[255, 29, 104, 105, 117, 220, 162, 86, 137, 176, 56, 10, 238, 80, 102, 171, 58, 3, 164, 165, 76, 175, 31, 150, 9, 22, 204, 172, 16, 253, 178, 176, 168, 217, 193, 112, 16, 233, 55, 69, 111, 82, 118, 221, 63, 124, 219, 5, 187, 69, 110, 217, 205, 234, 250, 24, 26, 148, 213, 137, 199, 64, 129, 81, 200, 123, 83, 56, 6, 231, 28, 235, 182, 187, 199, 83, 195, 69, 28, 136, 25, 10, 222, 124, 159, 213, 4, 102, 76, 170, 62, 57, 8, 7, 223, 142, 12, 127, 72, 87, 128, 121, 117, 221, 230, 199, 172, 75, 54, 157, 254, 36, 123, 18, 142, 134, 109, 77, 89, 88, 101, 90, 96, 203, 94, 235, 168, 242, 112, 33, 85, 181, 161, 31, 232, 127, 142, 70, 35, 123, 157, 224, 13, 13, 207, 170, 31, 217, 219, 163, 109, 93, 84, 39, 195, 228, 195, 186, 239, 201, 13, 53, 241, 5, 24, 129, 203, 82, 57, 153, 174, 225, 117, 4, 180, 16, 226, 164, 207, 20, 171, 221, 187, 224, 95, 218, 23, 215, 40, 238, 104, 175, 158, 10, 46, 221, 163, 26, 217, 70, 12, 227, 230, 111, 43, 126, 95, 75, 0, 59, 10, 53, 186, 181, 251, 134, 99, 185, 89, 245, 105, 243, 68, 241, 7, 142, 24, 242, 145, 209, 147, 82, 227, 21, 224, 20, 247, 160, 58, 138, 204, 166, 251, 139, 116, 166, 106, 113, 14, 204, 115, 67, 198, 141, 189, 180, 26, 177, 144, 178, 58, 205, 156, 93, 47, 58, 125, 30, 13, 206, 166, 233, 248, 184, 137, 5, 15, 14, 177, 239, 157, 175, 120, 74, 125, 47, 38, 100, 93, 194, 244, 149, 119, 205, 69, 80, 132, 201, 3, 131, 197, 144, 71, 138, 206, 70, 199, 10, 107, 133, 36, 126, 26, 124, 75, 215, 10, 112, 248, 212, 121, 137, 70, 177, 255, 55, 120, 237, 195, 152, 198, 231, 140, 247, 249, 233, 127, 53, 225, 54, 71, 26, 104, 139, 64, 27, 203, 9, 148, 32, 101, 220, 48, 195, 221, 239, 76, 222, 13, 37, 240, 73, 154, 162, 66, 228, 180, 14, 38, 211, 197, 85, 103, 205, 31, 135, 184, 172, 126, 67, 73, 45, 111, 183, 181, 124, 95, 184, 93, 34, 196, 53, 2, 47, 63, 35, 169, 13, 195, 3, 204, 52, 23, 59, 249, 84, 62, 66, 196, 47, 238, 171, 183, 57, 120, 238, 200, 88, 10, 141, 198, 117, 169, 77, 83, 151, 30, 14, 224, 232, 192, 161, 93, 208, 240, 155, 18, 66, 22, 25, 214, 43, 16, 211, 165, 28, 234, 127, 161, 147, 37, 132, 87, 200, 57, 95, 127, 18, 28, 64, 196, 32, 29, 40, 147, 201, 199, 152, 104, 11, 250, 107, 26, 75, 147, 67, 159, 74, 214, 131, 170, 11, 208, 208, 172, 170, 141, 75, 39, 40, 100, 61, 118, 7, 165, 175, 155, 198, 204, 117, 120, 26, 184, 92, 129, 220, 97, 30, 167, 203, 207, 217, 146, 150, 39, 28, 221, 21, 27, 60, 70, 155, 105, 228, 138, 219, 82, 204, 75, 40, 203, 66, 207, 62, 137, 27, 27, 148, 171, 117, 0, 56, 132, 214, 217, 124, 26, 101, 68, 121, 89, 121, 141, 222, 156, 108, 40, 182, 1, 251, 207, 27, 52, 93, 103, 62, 71, 181, 202, 204, 121, 208, 64, 92, 175, 142, 4, 140, 156, 204, 180, 140, 215, 70, 12, 109, 221, 13, 99, 206, 85, 93, 154, 149, 253, 210, 208, 215, 226, 10, 36, 185, 44, 218, 249, 191, 137, 190, 135, 226, 75, 75, 59, 234, 163, 114, 58, 148, 188, 126, 253, 25, 127, 208, 90, 141, 219, 4, 128, 242, 8, 106, 236, 64, 81, 76, 16, 9, 71, 28, 47, 85, 89, 161, 121, 128, 66, 145, 85, 102, 100, 165, 26, 211, 204, 133, 58, 11, 7, 215, 245, 226, 52, 211, 62, 62, 72, 69, 144, 15, 249, 58, 240, 141, 133, 52, 76, 23, 90, 203, 131, 62, 124, 66, 210, 96, 158, 4, 254, 213, 199, 246, 187, 118, 134, 102, 205, 215, 211, 75, 108, 68, 180, 240, 174, 48, 107, 8, 187, 248, 203, 252, 32, 229, 213, 27, 184, 168, 65, 134, 98, 223, 197, 22, 229, 214, 2, 52, 1, 63, 229, 140, 192, 2, 171, 74, 70, 15, 22, 248, 225, 211, 104, 133, 52, 21, 107, 72, 203, 201, 153, 6, 95, 89, 254, 191, 195, 184, 210, 243, 80, 141, 43, 113, 156, 254, 153, 186, 255, 6, 184, 166, 122, 167, 43, 90, 110, 181, 161, 146, 139, 149, 238, 118, 218, 31, 14, 32, 62, 148, 16, 75, 180, 101, 181, 174, 101, 39, 0, 0, 0], 1258578467),
+ (false, 18, &[175, 118, 6, 35, 65, 105, 203, 92, 242, 62, 29, 3, 231, 116, 164, 69, 144, 64, 252, 187, 28, 254, 30, 212, 131, 40, 36, 118, 240, 6, 133, 109, 104, 13, 148, 115, 2, 22, 178, 182, 139, 53, 79, 35, 132, 155, 162, 100, 135, 201, 128, 250, 12, 21, 121, 195, 210, 68, 51, 6, 128, 1, 127, 213, 144, 1, 156, 235, 140, 131, 16, 137, 35, 186, 255, 125, 247, 209, 45, 229, 27, 162, 77, 31, 109, 161, 147, 201, 54, 99, 166, 69, 85, 76, 29, 199, 164, 35, 166, 29, 132, 77, 247, 211, 179, 182, 31, 145, 183, 106, 82, 149, 203, 83, 63, 108, 23, 249, 196, 149, 63, 45, 121, 233, 28, 53, 7, 209, 12, 208, 139, 247, 82, 190, 54, 53, 245, 29, 183, 102, 140, 113, 71, 32, 151, 198, 149, 176, 129, 128, 30, 122, 184, 232, 155, 233, 35, 173, 20, 74, 212, 138, 227, 165, 151, 92, 241, 179, 125, 141, 251, 110, 225, 243, 183, 111, 154, 105, 95, 167, 31, 167, 208, 253, 55, 158, 67, 84, 18, 55, 119, 250, 126, 199, 89, 254, 75, 243, 154, 165, 19, 18, 216, 14, 67, 121, 192, 107, 9, 71, 212, 0, 168, 249, 69, 229, 247, 40, 75, 11, 248, 55, 89, 117, 173, 169, 22, 60, 97, 202, 63, 68, 102, 201, 212, 176, 143, 139, 156, 73, 92, 206, 32, 34, 172, 86, 47, 162, 32, 187, 131, 55, 167, 69, 112, 217, 209, 12, 78, 135, 188, 127, 75, 152, 40, 105, 222, 98, 201, 133, 225, 156, 167, 139, 159, 128, 61, 139, 210, 74, 204, 97, 237, 89, 128, 246, 112, 127, 109, 13, 193, 52, 70, 206, 9, 161, 0, 186, 182, 70, 174, 196, 42, 14, 68, 26, 233, 174, 252, 122, 5, 85, 212, 2, 74, 52, 53, 147, 9, 252, 195, 246, 155, 103, 187, 84, 63, 2, 67, 31, 104, 26, 39, 225, 235, 63, 172, 180, 165, 241, 72, 30, 119, 143, 110, 79, 41, 186, 31, 14, 167, 146, 138, 21, 13, 147, 215, 243, 158, 217, 43, 135, 10, 230, 78, 91, 12, 184, 183, 106, 22, 3, 68, 23, 139, 114, 212, 51, 39, 186, 22, 153, 112, 109, 223, 193, 182, 185, 91, 180, 72, 117, 151, 189, 127, 217, 173, 232, 170, 160, 5, 236, 167, 4, 65, 206, 25, 73, 53, 85, 30, 106, 174, 38, 118, 140, 149, 145, 200, 192, 246, 173, 40, 214, 89, 110, 16, 204, 152, 228, 169, 70, 198, 22, 116, 121, 223, 136, 116, 131, 137, 203, 189, 74, 46, 179, 237, 28, 244, 50, 237, 129, 58, 149, 31, 220, 20, 90, 198, 3, 63, 46, 99, 133, 184, 178, 194, 79, 231, 153, 194, 114, 15, 92, 246, 176, 152, 189, 60, 39, 96, 154, 107, 243, 149, 58, 113, 39, 251, 104, 145, 194, 206, 45, 184, 134, 180, 43, 254, 94, 211, 137, 151, 71, 77, 54, 144, 240, 0, 206, 220, 131, 63, 10, 184, 243, 32, 63, 157, 71, 79, 28, 207, 200, 248, 147, 92, 16, 192, 115, 1, 179, 154, 205, 218, 52, 193, 217, 27, 98, 0, 199, 83, 30, 157, 60, 214, 130, 193, 221, 91, 40, 20, 123, 27, 235, 163, 167, 8, 128, 198, 108, 43, 245, 114, 192, 122, 44, 0, 181, 47, 69, 106, 225, 244, 155, 25, 11, 27, 63, 174, 219, 41, 218, 81, 71, 203, 220, 184, 65, 204, 8, 170, 26, 247, 49, 236, 5, 215, 186, 29, 187, 6, 4, 161, 159, 193, 236, 39, 172, 115, 203, 159, 198, 207, 46, 183, 227, 32, 168, 119, 21, 143, 85, 237, 83, 253, 230, 26, 8, 155, 252, 25, 234, 37, 68, 248, 163, 59, 91, 155, 148, 172, 56, 208, 91, 97, 217, 150, 202, 178, 169, 86, 193, 145, 148, 205, 242, 6, 29, 178, 18, 173, 9, 101, 34, 254, 137, 168, 240, 33, 91, 126, 63, 180, 201, 183, 35, 105, 192, 132, 177, 20, 49, 173, 197, 71, 5, 220, 67, 85, 127, 82, 50, 224, 255, 16, 176, 218, 133, 155, 120, 145, 217, 223, 193, 105, 30, 207, 43, 163, 157, 137, 169, 229, 188, 144, 87, 15, 92, 103, 174, 140, 248, 229, 202, 184, 81, 178, 148, 139, 106, 194, 120, 252, 12, 12, 96, 160, 97, 11, 166, 138, 184, 137, 232, 192, 15, 149, 128, 209, 192, 173, 48, 137, 85, 59, 13, 14, 186, 208, 248, 139, 17, 184, 156, 192, 60, 32, 233, 167, 122, 30, 132, 163, 170, 42, 91, 211, 190, 229, 42, 56, 125, 100, 76, 76, 40, 30, 8, 185, 9, 160, 190, 225, 230, 99, 121, 137, 44, 86, 85, 74, 97, 21, 246, 178, 106, 212, 231, 0], 3152110496),
+ (true, 40, &[253, 118, 203, 3, 245, 131, 239, 5, 42, 253, 113, 101, 195, 94, 192, 14, 240, 25, 142, 141, 31, 26, 123, 87, 74, 96, 191, 246, 107, 25, 106, 138, 195, 98, 205, 134, 25, 232, 203, 40, 204, 57, 167, 126, 196, 14, 163, 248, 11, 178, 206, 231, 67, 22, 103, 234, 94, 183, 54, 102, 147, 95, 127, 4, 94, 88, 115, 180, 50, 215, 252, 173, 34, 181, 115, 165, 72, 73, 119, 8, 154, 118, 153, 245, 195, 87, 183, 117, 4, 64, 79, 227, 82, 66, 64, 22, 211, 68, 42, 0, 60, 116, 172, 64, 183, 74, 157, 28, 197, 178, 251, 80, 244, 235, 67, 99, 135, 113, 117, 168, 4, 63, 45, 191, 22, 145, 145, 157, 227, 32, 56, 100, 122, 149, 226, 118, 193, 107, 208, 120, 16, 214, 214, 28, 223, 249, 113, 145, 156, 154, 165, 164, 116, 242, 117, 139, 137, 247, 20, 23, 82, 51, 0, 115, 232, 217, 71, 97, 237, 95, 124, 246, 163, 130, 113, 233, 165, 170, 170, 32, 31, 32, 248, 250, 5, 140, 94, 239, 25, 229, 42, 133, 14, 178, 134, 119, 42, 16, 163, 229, 207, 173, 92, 168, 53, 132, 101, 57, 59, 164, 116, 224, 129, 157, 32, 103, 134, 91, 120, 149, 106, 242, 219, 238, 173, 74, 165, 144, 80, 68, 150, 180, 175, 150, 216, 142, 90, 205, 88, 39, 218, 149, 177, 57, 108, 99, 229, 104, 128, 180, 29, 58, 24, 197, 78, 51, 232, 19, 177, 230, 121, 92, 240, 87, 188, 184, 228, 15, 187, 114, 28, 123, 247, 31, 172, 23, 216, 14, 7, 67, 184, 80, 32, 22, 184, 55, 102, 82, 239, 75, 25, 32, 211, 148, 243, 123, 64, 97, 83, 162, 178, 111, 66, 67, 214, 123, 149, 104, 236, 250, 37, 247, 247, 199, 183, 51, 208, 183, 193, 135, 71, 60, 210, 198, 129, 11, 111, 186, 172, 154, 194, 223, 75, 78, 13, 146, 155, 59, 233, 181, 167, 228, 151, 132, 103, 177, 201, 11, 137, 145, 22, 152, 16, 59, 232, 223, 237, 8, 28, 107, 111, 103, 156, 179, 74, 37, 95, 124, 127, 192, 214, 219, 71, 96, 124, 90, 151, 227, 138, 11, 34, 103, 90, 10, 69, 1, 23, 44, 67, 9, 77, 144, 221, 53, 74, 177, 249, 32, 218, 223, 36, 204, 178, 247, 170, 196, 55, 96, 196, 50, 118, 206, 44, 185, 54, 255, 216, 132, 40, 171, 74, 201, 151, 213, 174, 51, 222, 149, 104, 31, 227, 34, 151, 148, 237, 147, 239, 135, 92, 233, 70, 174, 21, 66, 187, 58, 183, 226, 189, 123, 19, 28, 3, 32, 132, 75, 227, 52, 247, 47, 164, 38, 34, 242, 25, 243, 31, 228, 111, 127, 236, 65, 215, 179, 211, 179, 7, 213, 16, 176, 87, 102, 3, 234, 19, 246, 179, 25, 166, 14, 36, 71, 226, 204, 240, 227, 186, 75, 26, 24, 88, 51, 177, 196, 128, 109, 112, 21, 245, 83, 171, 108, 78, 97, 80, 95, 87, 14, 187, 188, 247, 139, 130, 197, 220, 42, 0, 32, 194, 141, 44, 101, 185, 244, 137, 189, 144, 143, 156, 61, 40, 213, 237, 165, 78, 67, 27, 197, 3, 99, 179, 222, 102, 39, 177, 220, 69, 178, 8, 26, 138, 128, 255, 41, 208, 66, 196, 38, 152, 201, 99, 20, 188, 170, 133, 241, 1, 204, 197, 79, 58, 64, 77, 82, 56, 124, 144, 111, 108, 184, 181, 221, 115, 238, 222, 166, 149, 16, 232, 127, 158, 82, 221, 148, 61, 212, 50, 161, 94, 64, 23, 70, 97, 9, 108, 73, 48, 77, 231, 186, 204, 202, 84, 139, 35, 232, 72, 148, 131, 31, 52, 126, 5, 77, 233, 231, 128, 202, 29, 148, 146, 244, 23, 144, 44, 144, 195, 54, 210, 99, 133, 222, 162, 172, 41, 106, 156, 210, 76, 149, 196, 10, 43, 96, 26, 225, 68, 249, 128, 19, 100, 104, 26, 9, 218, 55, 34, 134, 8, 57, 26, 109, 85, 167, 101, 226, 165, 176, 67, 157, 147, 103, 1, 35, 225, 122, 92, 231, 8, 41, 95, 105, 107, 159, 204, 168, 128, 227, 1, 164, 179, 139, 208, 218, 10, 221, 106, 18, 250, 105, 196, 50, 173, 80, 157, 14, 26, 165, 112, 77, 174, 174, 102, 183, 194, 89, 48, 228, 160, 156, 6, 140, 117, 229, 33, 145, 10, 91, 160, 4, 210, 234, 55, 14, 60, 141, 86, 28, 164, 170, 60, 38, 187, 185, 86, 68, 203, 190, 132, 63, 227, 88, 231, 6, 159, 192, 22, 34, 222, 55, 76, 118, 26, 201, 103, 106, 124, 196, 132, 114, 212, 65, 240, 81, 9, 146, 86, 179, 133, 69, 219, 47, 122, 193, 192, 208, 199, 83, 94, 90, 15, 202, 12, 0], 749843493),
+ (true, 64, &[85, 64, 215, 134, 25, 225, 95, 89, 176, 177, 19, 12, 9, 153, 129, 118, 114, 132, 40, 67, 99, 159, 215, 141, 37, 205, 206, 248, 233, 137, 248, 59, 136, 97, 20, 135, 35, 184, 160, 34, 53, 181, 208, 97, 33, 92, 246, 128, 157, 33, 111, 107, 41, 229, 98, 156, 174, 120, 69, 20, 241, 250, 52, 163, 66, 180, 90, 171, 9, 51, 126, 244, 86, 84, 126, 192, 13, 90, 185, 177, 93, 241, 147, 33, 11, 133, 207, 44, 36, 2, 104, 56, 86, 45, 71, 199, 193, 252, 51, 218, 71, 200, 74, 229, 110, 104, 10, 164, 66, 78, 49, 228, 111, 84, 12, 4, 220, 216, 123, 215, 112, 91, 178, 103, 65, 173, 248, 40, 67, 235, 49, 8, 1, 117, 203, 162, 8, 120, 244, 9, 24, 161, 20, 169, 183, 170, 227, 239, 99, 152, 92, 127, 91, 174, 51, 218, 94, 211, 234, 175, 132, 135, 53, 43, 82, 151, 228, 144, 17, 98, 162, 122, 54, 168, 200, 119, 128, 228, 247, 21, 205, 134, 74, 140, 149, 124, 173, 188, 9, 196, 249, 99, 196, 8, 112, 190, 222, 142, 93, 110, 65, 250, 16, 243, 15, 176, 102, 41, 108, 192, 177, 22, 220, 243, 231, 195, 79, 70, 120, 156, 49, 140, 67, 17, 125, 153, 200, 211, 128, 123, 201, 10, 106, 130, 16, 48, 40, 142, 45, 100, 241, 151, 99, 221, 124, 36, 29, 96, 24, 29, 194, 137, 145, 75, 83, 234, 42, 186, 20, 150, 80, 140, 148, 175, 113, 235, 150, 39, 148, 38, 154, 133, 226, 250, 69, 41, 66, 204, 248, 112, 77, 118, 220, 158, 61, 51, 64, 246, 178, 34, 134, 218, 81, 141, 14, 169, 226, 23, 43, 121, 139, 166, 190, 133, 29, 30, 95, 97, 205, 62, 104, 25, 155, 85, 45, 222, 88, 106, 34, 51, 255, 215, 161, 66, 103, 52, 55, 155, 176, 83, 222, 117, 130, 122, 6, 108, 237, 160, 212, 178, 42, 19, 198, 11, 147, 101, 229, 251, 84, 51, 158, 214, 178, 254, 165, 231, 177, 198, 239, 184, 34, 44, 84, 116, 83, 141, 32, 135, 248, 102, 239, 206, 250, 123, 6, 51, 255, 113, 92, 12, 190, 40, 147, 132, 175, 52, 114, 186, 112, 154, 210, 203, 175, 196, 159, 49, 92, 19, 12, 251, 87, 131, 50, 236, 51, 52, 180, 196, 119, 100, 177, 100, 227, 38, 16, 63, 93, 211, 243, 185, 78, 0, 117, 41, 122, 52, 216, 12, 157, 115, 79, 70, 41, 129, 136, 240, 22, 195, 130, 171, 240, 228, 54, 100, 28, 74, 110, 235, 99, 12, 195, 92, 255, 208, 159, 177, 66, 174, 228, 153, 143, 28, 146, 77, 17, 158, 52, 12, 228, 233, 3, 34, 81, 69, 131, 142, 138, 244, 97, 194, 109, 216, 198, 196, 16, 139, 74, 7, 59, 190, 204, 32, 22, 229, 3, 104, 2, 115, 180, 86, 120, 104, 130, 137, 30, 152, 39, 224, 91, 40, 31, 191, 191, 252, 217, 190, 25, 145, 160, 164, 84, 92, 74, 109, 46, 39, 7, 200, 90, 47, 13, 231, 194, 70, 56, 250, 196, 145, 244, 58, 4, 197, 242, 0, 104, 219, 191, 22, 226, 56, 254, 170, 144, 56, 233, 166, 57, 76, 121, 10, 105, 58, 251, 106, 67, 206, 167, 230, 75, 66, 254, 77, 200, 38, 198, 82, 144, 239, 67, 201, 168, 222, 163, 112, 194, 3, 77, 120, 145, 246, 253, 139, 217, 136, 84, 122, 33, 251, 216, 128, 123, 195, 246, 27, 251, 43, 22, 87, 236, 243, 14, 241, 39, 251, 76, 100, 230, 91, 42, 137, 191, 32, 27, 86, 45, 134, 13, 191, 230, 132, 171, 119, 194, 232, 47, 26, 91, 117, 32, 137, 40, 120, 124, 70, 5, 21, 150, 235, 114, 45, 209, 43, 111, 20, 253, 41, 241, 233, 194, 86, 196, 151, 246, 236, 23, 175, 34, 176, 135, 81, 167, 14, 74, 240, 143, 22, 39, 160, 253, 231, 22, 70, 0, 31, 58, 180, 55, 154, 152, 67, 116, 75, 205, 210, 170, 171, 161, 147, 160, 159, 138, 15, 224, 182, 86, 117, 57, 200, 52, 190, 252, 161, 199, 209, 185, 241, 120, 46, 216, 247, 199, 155, 78, 25, 200, 105, 245, 61, 218, 185, 112, 112, 236, 245, 33, 214, 192, 235, 155, 84, 134, 158, 93, 83, 22, 176, 71, 220, 63, 136, 110, 134, 222, 88, 143, 38, 12, 101, 185, 67, 223, 17, 233, 219, 147, 78, 239, 3, 225, 169, 218, 239, 115, 67, 162, 244, 136, 3, 198, 132, 155, 27, 169, 88, 86, 110, 78, 140, 147, 176, 131, 161, 248, 70, 227, 239, 66, 166, 21, 234, 173, 153, 187, 107, 16, 14, 249, 166, 127, 79, 99, 151, 215, 103, 124, 82, 211, 16, 0], 3242310133),
+];
diff --git a/apps/watch-music/src/screens.rs b/apps/watch-music/src/screens.rs
new file mode 100644
index 0000000..1cb26f0
--- /dev/null
+++ b/apps/watch-music/src/screens.rs
@@ -0,0 +1,1883 @@
+//! Watch Music's screens, built from the watch's own LVGL widgets in the stock look (the way ui-gallery does):
+//! a dynamic start screen (Control media / Music / Podcasts / Custom), a stock focus list of the songs or shows (the fisheye, the crown, the round
+//! scroll bar), and a media-control player: the cover's colours as a soft blurred background, the clock, the artist
+//! and the song, prev / play / next, one smooth ring that touches the play button and shows how much of the song
+//! is done, and a volume button (press it, then the crown changes the volume). Leaving a screen deletes its page
+//! and everything on it. The stock widgets cannot draw pictures, so the cover is shown by its colours.
+
+use crate::model::*;
+use crate::thumb::{self, Pic};
+use cmf_wp2_app::lv::*;
+use cmf_wp2_app::stock::{self, CIRCLE, GREY, ICON, LETTER_BG, ROW_PRESSED, ROW_W, SCREEN, WHITE};
+
+/// Font slots besides the system font (slot 0).
+pub const F24: u8 = 1;
+// bytes one widget group can take: flush first when fewer are left
+const GROUP: usize = 560;
+
+/// Light grey of the artist on the player (readable on every tint).
+const SOFT: i32 = 0xC618;
+
+// player geometry, as offsets from the screen centre
+const RING: i32 = 176;
+const RING_W: i32 = 10;
+/// The play button fills the ring exactly, so the ring touches it.
+const PLAY: i32 = RING - 2 * RING_W;
+const SIDE: i32 = 80;
+const CY: i16 = 0;
+const SIDE_X: i16 = 124;
+
+/// The volume button under the ring, and how long it stays lit after the last touch is decided in main.rs.
+const VOL: i32 = 72;
+const VOL_Y: i16 = 176;
+/// On a page, volume and back share the lower control row symmetrically.
+const SIDE_BTN_X: i16 = 96;
+const PAGE_VOL_Y: i16 = 162;
+const BACK_PILL_W: i32 = 148;
+const BACK_PILL_H: i32 = 58;
+/// Red used only for the Back arrow in the music/podcast item list.
+const BACK_RED: i32 = 0xF800;
+/// The heart: saved (a warm red) and not saved (soft grey, like the secondary text).
+const HEART_ON: i32 = 0xF9CB;
+const HEART_OFF: i32 = SOFT;
+/// The player's bottom row: volume on the left, the heart on the right (where page mode's back arrow was).
+const BOTTOM_X: i16 = SIDE_BTN_X;
+const BOTTOM_Y: i16 = PAGE_VOL_Y;
+/// The song name sits where the clock was: the clock is gone so the name has room near the top.
+const TITLE_Y: i16 = 58;
+/// The artist sits right under the song name: smaller (the small font) and light grey.
+const ARTIST_Y: i16 = TITLE_Y + 41;
+
+/// The cover picture of the song the list has stopped on: THUMB_PX square (a 16:9 one is wider and lower), THUMB_X
+/// from the left edge of its row; the song's two texts move aside for it.
+const THUMB_PX: i32 = 88;
+/// A 16:9 picture.
+const WIDE_PX: i32 = 128;
+const WIDE_PY: i32 = 72;
+const THUMB_X: i16 = 35;
+/// The gap between a picture and the row's texts.
+const THUMB_GAP: i16 = 12;
+/// The picture's rounded corners: their radius, and the width of the ring in the row's colour that hides what lies
+/// outside it (it has to be more than 0.42 x the radius to reach the very corner).
+const THUMB_R: i32 = 14;
+const THUMB_RING: i32 = 7;
+/// Only the rows this close to the centred one have their two texts: every object counts against the watch's limit,
+/// and the squares of the cover picture need the room. (4 each way: more than the screen shows.)
+const LABEL_REACH: usize = 4;
+/// `Screen::thumb_slot` when no picture is on show
+const NO_SLOT: u8 = 0xFF;
+
+/// The background: the cover's average colour glows in the middle and fades to black at the edge, as a stack of
+/// opaque discs, each a little brighter than the one under it (a smooth radial gradient).
+const RINGS: usize = 110;
+const R_MAX: i32 = 222;
+/// the glow's strongest channel, of 255 (not so bright that the white text suffers)
+const GLOW_MAX: u32 = 235;
+const BLOBS: usize = RINGS;
+
+/// Bars that make the play triangle.
+pub const PLAY_BARS: usize = 22;
+
+/// Heights of the player's play triangle: the start screen's rounded play icon (`PLAY_COLS`) at 46 px tall, as 22 bars
+/// 2 px apart and 3 px wide (they overlap and leave no seams), so its corners are round like the icon's. Fewer, wider
+/// bars than 1 px columns: every shape is something the watch must create before the player can show.
+const PLAY_SMALL: [u8; PLAY_BARS] = [33, 41, 43, 45, 46, 46, 45, 43, 41, 38, 36, 34, 32, 29, 27, 24, 22, 19, 18, 16, 12, 5];
+
+#[derive(Clone, Copy, PartialEq, Debug)]
+pub enum Kind {
+ Wait,
+ /// the dynamic category chooser: Music, Podcasts, Custom and active controls
+ Home,
+ Menu,
+ Player,
+}
+
+/// What the app reacts to on the current screen; unused handles are `ROOT` (never an event target).
+#[derive(Clone, Copy)]
+pub struct Screen {
+ pub kind: Kind,
+ pub page: Obj,
+ pub rows: [Obj; MAX_TRACKS],
+ /// For each visible menu row, the underlying track index (rows are rotated around the current focus).
+ pub row_indices: [u8; MAX_TRACKS],
+ pub row_count: u8,
+ /// The pill colour each song row was last given, so a colour message restyles only the rows that changed.
+ pub row_c1: [u16; MAX_TRACKS],
+ /// The two texts of each song row, so the row the list stopped on can move them aside for its cover picture.
+ pub row_title: [Obj; MAX_TRACKS],
+ pub row_artist: [Obj; MAX_TRACKS],
+ /// The cover picture on show (its box; `ROOT` = none) and the row slot it sits in.
+ pub thumb: Obj,
+ pub thumb_slot: u8,
+ /// the image object of a real picture (`ROOT` for a block picture)
+ pub thumb_image: Obj,
+ /// The four arcs that round the picture's corners (valid while `thumb` is not `ROOT`).
+ pub thumb_corners: [Obj; 4],
+ /// The pulsing rounded square shown where the cover will appear while it loads (`ROOT` = none), and its row slot.
+ pub pulse: Obj,
+ pub pulse_slot: u8,
+ /// the pulse's inner square (its brightness changes) and its four smooth corner covers
+ pub pulse_inner: Obj,
+ pub pulse_corners: [Obj; 4],
+ /// The home row's selected watch mode: Music, Podcasts, External, or Custom.
+ pub home_modes: [u8; 4],
+ pub home_count: u8,
+ /// Rotation used when this page was built; FOCUSED row indices map through this stable origin.
+ pub list_anchor: usize,
+ pub prev: Obj,
+ pub play: Obj,
+ pub next: Obj,
+ pub pause_bars: [Obj; 2],
+ pub play_bars: [Obj; PLAY_BARS],
+ pub title: Obj,
+ pub artist: Obj,
+ pub clock: Obj,
+ pub arc: Obj,
+ /// Visible back target on page mode (unused in the regular app).
+ pub back: Obj,
+ pub blobs: [Obj; BLOBS],
+ /// the volume button, its "Vol 65%" text (shown instead of the clock while it is on) and its sound wave
+ pub vol: Obj,
+ pub vol_label: Obj,
+ pub wave: [Obj; 2],
+ /// the heart button and its three shapes (two lobes and the point), and the double-tap halves
+ pub heart: Obj,
+ pub heart_parts: [Obj; 3],
+ pub seek_left: Obj,
+ pub seek_right: Obj,
+}
+
+const EMPTY: Screen = Screen {
+ kind: Kind::Wait,
+ page: ROOT,
+ rows: [ROOT; MAX_TRACKS],
+ row_indices: [0; MAX_TRACKS],
+ row_count: 0,
+ row_c1: [0; MAX_TRACKS],
+ row_title: [ROOT; MAX_TRACKS],
+ row_artist: [ROOT; MAX_TRACKS],
+ thumb: ROOT,
+ thumb_slot: NO_SLOT,
+ thumb_image: ROOT,
+ thumb_corners: [ROOT; 4],
+ pulse: ROOT,
+ pulse_slot: NO_SLOT,
+ pulse_inner: ROOT,
+ pulse_corners: [ROOT; 4],
+ home_modes: [MODE_NONE; 4],
+ home_count: 0,
+ list_anchor: 0,
+ prev: ROOT,
+ play: ROOT,
+ next: ROOT,
+ pause_bars: [ROOT; 2],
+ play_bars: [ROOT; PLAY_BARS],
+ title: ROOT,
+ artist: ROOT,
+ clock: ROOT,
+ arc: ROOT,
+ back: ROOT,
+ blobs: [ROOT; BLOBS],
+ vol: ROOT,
+ vol_label: ROOT,
+ wave: [ROOT; 2],
+ heart: ROOT,
+ heart_parts: [ROOT; 3],
+ seek_left: ROOT,
+ seek_right: ROOT,
+};
+
+impl Screen {
+ pub const fn empty() -> Screen {
+ EMPTY
+ }
+}
+
+type Flush<'a> = &'a mut dyn FnMut(&mut Batch) -> Result<(), LvError>;
+
+fn room(b: &mut Batch, flush: Flush) -> Result<(), LvError> {
+ if b.bytes().len() + GROUP > BUF { flush(b) } else { Ok(()) }
+}
+
+/// The fonts, in a batch of their own.
+pub fn fonts(b: &mut Batch) -> Result<(), LvError> {
+ stock::font(b)?;
+ b.font(F24, StockFont::F24M)
+}
+
+/// Once, first: the system font and white text for everything.
+pub fn theme(b: &mut Batch) -> Result<(), LvError> {
+ stock::theme(b)
+}
+
+/// Deletes the current screen (its page, with every object and its scroll bar).
+pub fn leave(b: &mut Batch, s: &Screen) -> Result<(), LvError> {
+ if s.page != ROOT { b.del(s.page) } else { Ok(()) }
+}
+
+/// One solid native LVGL shape. The transparent icon slot below contains these pieces,
+/// so the symbol has no badge/circle behind it and never intercepts row selection.
+fn glyph_piece(
+ b: &mut Batch,
+ flush: Flush,
+ parent: Obj,
+ w: i32,
+ h: i32,
+ x: i16,
+ y: i16,
+ radius: i32,
+) -> Result {
+ room(b, flush)?;
+ let piece = b.create(Class::Obj, parent)?;
+ b.size(piece, w, h)?;
+ b.align(piece, Align::Center, x, y)?;
+ b.style(piece, Prop::Radius, 0, radius)?;
+ b.style(piece, Prop::BgColor, 0, WHITE)?;
+ b.style(piece, Prop::BgOpa, 0, 255)?;
+ b.style(piece, Prop::BorderWidth, 0, 0)?;
+ b.flags(piece, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ Ok(piece)
+}
+
+/// Height of each 1 px column of the rounded play triangle (61 px wide, 67 px tall, corners 12 px).
+const PLAY_COLS: [u8; 61] = [48, 53, 56, 59, 60, 62, 63, 64, 65, 66, 66, 67, 67, 67, 67, 66, 66, 65, 64, 63, 62, 61, 60, 59, 58, 56, 55, 54, 53, 52, 51, 49, 48, 47, 46, 45, 44, 42, 41, 40, 39, 38, 37, 35, 34, 33, 32, 31, 30, 28, 27, 26, 25, 24, 23, 21, 20, 18, 16, 12, 8];
+
+/// The lower half of a circle as a thick arc with round ends (a "U"), `size` px across, centred at (x, y).
+fn glyph_arc(b: &mut Batch, flush: Flush, parent: Obj, size: i32, width: i32, x: i16, y: i16) -> Result {
+ room(b, flush)?;
+ let a = b.create(Class::Arc, parent)?;
+ b.size(a, size, size)?;
+ b.align(a, Align::Center, x, y)?;
+ b.angles(a, 0, 180, 0)?;
+ b.value(a, 0, false)?;
+ b.style(a, Prop::ArcWidth, 0, width)?;
+ b.style(a, Prop::ArcRounded, 0, 1)?;
+ b.style(a, Prop::ArcColor, 0, WHITE)?;
+ b.style(a, Prop::ArcOpa, 0, 255)?;
+ b.style(a, Prop::ArcOpa, stock::INDICATOR, 0)?;
+ b.style(a, Prop::BgOpa, stock::KNOB, 0)?;
+ b.flags(a, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ Ok(a)
+}
+
+/// A filled pie slice: an arc as thick as its radius, so LVGL draws it antialiased (no stair steps). Its point is
+/// at (x, y) of `parent`'s centre; it spans `from`..`from + span` degrees (0 = right, 90 = down, clockwise).
+/// Straight edges and a slightly round far side: this is how every triangle (play, prev, next, arrows, speaker
+/// cone, heart point) is drawn now instead of stacks of 1-4 px bars.
+#[allow(clippy::too_many_arguments)]
+fn sector(
+ b: &mut Batch, flush: Flush, parent: Obj, r: i32, x: i16, y: i16, from: u16, span: u16, color: i32,
+) -> Result {
+ room(b, flush)?;
+ let a = b.create(Class::Arc, parent)?;
+ b.size(a, 2 * r, 2 * r)?;
+ b.align(a, Align::Center, x, y)?;
+ for p in [Prop::PadTop, Prop::PadBottom, Prop::PadLeft, Prop::PadRight] {
+ b.style(a, p, 0, 0)?;
+ }
+ b.angles(a, 0, span, from % 360)?;
+ b.value(a, 0, false)?;
+ b.style(a, Prop::ArcWidth, 0, r)?;
+ b.style(a, Prop::ArcRounded, 0, 0)?;
+ b.style(a, Prop::ArcColor, 0, color)?;
+ b.style(a, Prop::ArcOpa, 0, 255)?;
+ b.style(a, Prop::ArcOpa, stock::INDICATOR, 0)?;
+ b.style(a, Prop::BgOpa, stock::KNOB, 0)?;
+ b.style(a, Prop::BgOpa, 0, 0)?;
+ b.flags(a, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ Ok(a)
+}
+
+/// A triangle pointing right (`dir` 1) or left (-1), `h` px tall, its middle at x0 (its visual centre).
+fn triangle(b: &mut Batch, flush: Flush, parent: Obj, h: i32, x0: i16, dir: i16, color: i32) -> Result {
+ // a 60-degree slice: the point sits 0.58 h from the visual centre (centroid of the triangle)
+ let r = h; // edge length = height / sin60 ~ 1.15 h; r = h keeps the far side close to straight
+ let tip = x0 + dir * (h * 58 / 100) as i16;
+ sector(b, flush, parent, r, tip, 0, if dir > 0 { 150 } else { 330 }, 60, color)
+}
+
+/// Category symbols drawn from LVGL primitives so they render consistently with the watch fonts.
+/// Music follows the paired-note app icon; Podcast keeps its clean microphone.
+fn home_icon(b: &mut Batch, flush: Flush, parent: Obj, mode: u8) -> Result<(), LvError> {
+ match mode {
+ MODE_MUSIC => {
+ // Paired eighth notes: two round noteheads, two straight stems and one level beam. Everything is
+ // symmetric and made of whole rounded shapes, so no stair-stepped edges.
+ glyph_piece(b, flush, parent, 22, 22, -18, 26, CIRCLE)?; // left notehead
+ glyph_piece(b, flush, parent, 22, 22, 18, 26, CIRCLE)?; // right notehead
+ glyph_piece(b, flush, parent, 6, 54, -10, -1, 3)?; // left stem
+ glyph_piece(b, flush, parent, 6, 54, 26, -1, 3)?; // right stem
+ glyph_piece(b, flush, parent, 42, 10, 8, -26, 4)?; // beam
+ }
+ MODE_PODCAST => {
+ // Microphone: a capsule, a smooth U-shaped cradle (an arc with round ends), a stem and a base.
+ glyph_piece(b, flush, parent, 26, 44, 0, -17, 13)?;
+ glyph_arc(b, flush, parent, 56, 6, 0, -5)?;
+ glyph_piece(b, flush, parent, 6, 12, 0, 28, 3)?;
+ glyph_piece(b, flush, parent, 30, 6, 0, 35, 3)?;
+ }
+ MODE_EXTERNAL => {
+ // A play triangle with rounded corners: 1 px columns (each 2 px wide, so they overlap and leave no seams)
+ // whose heights follow the rounded outline, so no coarse blocks show.
+ let x0 = -(PLAY_COLS.len() as i16) / 2 + 3;
+ for (i, h) in PLAY_COLS.iter().enumerate() {
+ glyph_piece(b, flush, parent, 2, *h as i32, x0 + i as i16, 0, 0)?;
+ }
+ }
+ MODE_CUSTOM => {
+ // A bold "run" arrow pointing right: a rounded shaft and a smooth head.
+ arrow_shape(b, flush, parent, 0, 1, WHITE, 1)?;
+ }
+ _ => {}
+ }
+ Ok(())
+}
+
+/// The start screen: the stock fisheye focus rows with an unbadged icon and one category name.
+/// Control media is first and categories remain dynamic; only categories with content are shown.
+/// `flags`: bit 0 Music, bit 1 Podcasts, bit 2 Custom, bit 3 active media. `anchor` is the focused row.
+pub fn home(b: &mut Batch, flush: Flush, flags: u8, anchor: usize) -> Result {
+ room(b, flush)?;
+ // This is the same stock focus-page/row layout used by the original V12 start screen.
+ let (page, _bar) = stock::focus_page(b, ICON as u16)?;
+ let mut s = Screen { kind: Kind::Home, page, ..EMPTY };
+ let entries: [(u8, &str); 4] = [
+ (MODE_EXTERNAL, "Control media"),
+ (MODE_MUSIC, "Music"),
+ (MODE_PODCAST, "Podcasts"),
+ (MODE_CUSTOM, "Custom"),
+ ];
+ let mut available = [0usize; 4];
+ let mut n = 0usize;
+ for (i, (mode, _)) in entries.iter().enumerate() {
+ let bit = match *mode {
+ MODE_MUSIC => 0x01,
+ MODE_PODCAST => 0x02,
+ MODE_CUSTOM => 0x04,
+ MODE_EXTERNAL => 0x08,
+ _ => 0,
+ };
+ if flags & bit != 0 {
+ available[n] = i;
+ n += 1;
+ }
+ }
+ if n == 0 {
+ let l = b.create(Class::Label, page)?;
+ b.size(l, ROW_W - 48, 120)?;
+ b.style(l, Prop::TextColor, 0, GREY)?;
+ b.style(l, Prop::TextAlign, 0, 2)?;
+ b.text(l, "Add Music, Podcasts or Custom in the phone app")?;
+ b.align(l, Align::Center, 0, 0)?;
+ s.title = l;
+ return Ok(s);
+ }
+
+ // Focus rows are circular. Rotating the data order keeps the native watch focus on the
+ // selected category while preserving the stock fisheye layout.
+ let shift = anchor % n;
+ s.list_anchor = shift;
+ for slot in 0..n {
+ let idx = available[(shift + slot) % n];
+ let (mode, name) = entries[idx];
+ room(b, flush)?;
+ let row = stock::focus_row(b, page)?;
+
+ // The first child is always the icon slot: the stock fisheye scales it, not the text label.
+ // Its holder is transparent; the glyph itself is drawn from plain LVGL shapes.
+ let icon_slot = b.create(Class::Obj, row)?;
+ b.size(icon_slot, ICON, ICON)?;
+ b.align(icon_slot, Align::LeftMid, 4, 0)?;
+ b.style(icon_slot, Prop::BgOpa, 0, 0)?;
+ b.style(icon_slot, Prop::BorderWidth, 0, 0)?;
+ b.flags(icon_slot, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ home_icon(b, flush, icon_slot, mode)?;
+
+ // One centred, single-line category name. Keep the same icon-aware inset as the song list;
+ // Dot mode guarantees long names never wrap into a second line.
+ let text_width = ROW_W - ICON - 64;
+ let text_x = ICON as i16 + 28;
+ let title = b.create(Class::Label, row)?;
+ b.size(title, text_width, 48)?;
+ b.long_mode(title, LongMode::Dot)?;
+ b.text(title, name)?;
+ b.align(title, Align::LeftMid, text_x, 0)?;
+
+ s.rows[slot] = row;
+ s.home_modes[slot] = mode;
+ s.home_count = (slot + 1) as u8;
+ }
+ Ok(s)
+}
+
+/// Translate a FOCUSED event's row index into the logical index of a rotated focus list.
+/// The SDK reports the focused row index in `delta`; it is not a +/- scroll direction.
+pub fn focused_anchor(anchor: usize, focused_row: i16, total: usize) -> Option {
+ if total == 0 || focused_row < 0 || focused_row as usize >= total {
+ None
+ } else {
+ Some((anchor + focused_row as usize) % total)
+ }
+}
+
+/// Shown until the phone has sent the list (or said that there is none).
+pub fn wait(b: &mut Batch, flush: Flush, mode: u8, empty: bool, page_mode: bool) -> Result {
+ let (page, _bar) = stock::page(b)?;
+ let mut s = Screen { kind: Kind::Wait, page, ..EMPTY };
+ stock::title(b, page, match mode {
+ MODE_PODCAST => "Podcasts",
+ MODE_CUSTOM => "Custom",
+ _ => "Songs",
+ })?;
+ let l = b.create(Class::Label, page)?;
+ b.size(l, ROW_W - 40, 120)?;
+ b.style(l, Prop::TextColor, 0, GREY)?;
+ b.style(l, Prop::TextAlign, 0, 2)?;
+ b.text(l, match (mode == MODE_PODCAST, empty) {
+ (true, true) => "No podcasts yet. Add one in the phone app",
+ (false, true) if mode == MODE_CUSTOM => "No Custom items yet. Add one in the phone app",
+ (false, true) => "Add a Music item in the phone app",
+ _ => "Waiting for your phone",
+ })?;
+ s.title = l;
+ if page_mode {
+ s.back = back_pill(b, flush, page)?;
+ }
+ Ok(s)
+}
+
+/// The stock focus list. In page mode Back participates in the same circular list as the songs.
+/// Rotating the row order puts the chosen entry at the focus-page's centre without changing its stock styling.
+pub fn menu(b: &mut Batch, flush: Flush, m: &Model, page_mode: bool, anchor: usize) -> Result {
+ room(b, flush)?;
+ let (page, _bar) = stock::focus_page(b, 0)?;
+ let mut s = Screen { kind: Kind::Menu, page, ..EMPTY };
+ let total = m.count as usize + if page_mode { 1 } else { 0 };
+ if total == 0 { return Ok(s); }
+ let start = anchor % total;
+ s.list_anchor = start;
+ let mut track_slot = 0usize;
+ for offset in 0..total {
+ let logical = (start + offset) % total;
+ if page_mode && logical == 0 {
+ room(b, flush)?;
+ let row = stock::focus_row(b, page)?;
+ b.style(row, Prop::BgColor, CHECKED, LETTER_BG)?;
+ // the SDK's focus row is transparent when centred; the Back row wants its grey pill
+ b.style(row, Prop::BgOpa, CHECKED, 255)?;
+ // Keep only the back arrow in the row; make it red for a clear navigation cue.
+ arrow_color(b, flush, row, 56 - ROW_W as i16 / 2, BACK_RED)?;
+ s.back = row;
+ continue;
+ }
+ let track_idx = if page_mode { logical - 1 } else { logical };
+ if track_idx >= m.count as usize || track_slot >= MAX_TRACKS { continue; }
+ room(b, flush)?;
+ let t = &m.tracks[track_idx];
+ let row = stock::focus_row(b, page)?;
+ b.style(row, Prop::BgColor, CHECKED, t.c1 as i32)?;
+ // the centred row is filled with its cover's colour (the SDK's focus row is transparent, so ask for it)
+ b.style(row, Prop::BgOpa, CHECKED, 255)?;
+ s.rows[track_slot] = row;
+ s.row_indices[track_slot] = track_idx as u8;
+ s.row_c1[track_slot] = t.c1;
+ track_slot += 1;
+ s.row_count = track_slot as u8;
+ }
+ labels_around(b, flush, &mut s, m, 0)?;
+ Ok(s)
+}
+
+/// Gives the rows near row slot `centre` their song name and artist, and takes them from the rows that are far away.
+/// Returns whether anything changed.
+pub fn labels_around(b: &mut Batch, flush: Flush, s: &mut Screen, m: &Model, centre: usize) -> Result {
+ let mut changed = false;
+ let count = s.row_count as usize;
+ // first free the far ones, so their objects can be used again
+ for i in 0..count {
+ if i.abs_diff(centre) > LABEL_REACH && s.row_title[i] != ROOT {
+ room(b, flush)?;
+ b.del(s.row_title[i])?;
+ b.del(s.row_artist[i])?;
+ s.row_title[i] = ROOT;
+ s.row_artist[i] = ROOT;
+ changed = true;
+ }
+ }
+ for i in 0..count {
+ if i.abs_diff(centre) > LABEL_REACH || s.row_title[i] != ROOT {
+ continue;
+ }
+ let row = s.rows[i];
+ let t = &m.tracks[s.row_indices[i] as usize];
+ room(b, flush)?;
+ let n = b.create(Class::Label, row)?;
+ b.size(n, ROW_W - 90, 40)?;
+ b.long_mode(n, LongMode::Dot)?;
+ b.text(n, t.title())?;
+ b.align(n, Align::LeftMid, 28, -16)?;
+ let a = b.create(Class::Label, row)?;
+ b.size(a, ROW_W - 90, 30)?;
+ b.long_mode(a, LongMode::Dot)?;
+ b.style(a, Prop::TextFont, 0, F24 as i32)?;
+ b.style(a, Prop::TextColor, 0, GREY)?;
+ b.text(a, t.artist())?;
+ b.align(a, Align::LeftMid, 28, 20)?;
+ s.row_title[i] = n;
+ s.row_artist[i] = a;
+ changed = true;
+ }
+ Ok(changed)
+}
+
+/// A song's colours arrived: its pill takes the colour of its cover. Only rows whose colour really changed are
+/// restyled (the phone sends colours in many small messages and again after every hello; restyling all 50 rows
+/// each time stalled the list while it was being scrolled). Returns whether anything was restyled.
+pub fn recolour(b: &mut Batch, flush: Flush, s: &mut Screen, m: &Model) -> Result {
+ let mut changed = false;
+ for i in 0..m.count as usize {
+ if s.rows[i] == ROOT {
+ continue;
+ }
+ let track_idx = s.row_indices[i] as usize;
+ if track_idx < m.count as usize {
+ let c1 = m.tracks[track_idx].c1;
+ if s.row_c1[i] == c1 {
+ continue;
+ }
+ room(b, flush)?;
+ b.style(s.rows[i], Prop::BgColor, CHECKED, c1 as i32)?;
+ s.row_c1[i] = c1;
+ // the picture's corner covers have the row's colour: they follow it
+ if s.thumb != ROOT && s.thumb_slot as usize == i {
+ for &o in &s.thumb_corners {
+ room(b, flush)?;
+ b.style(o, Prop::ArcColor, 0, c1 as i32)?;
+ }
+ }
+ if s.pulse != ROOT && s.pulse_slot as usize == i {
+ for &o in &s.pulse_corners {
+ room(b, flush)?;
+ b.style(o, Prop::ArcColor, 0, c1 as i32)?;
+ }
+ }
+ changed = true;
+ }
+ }
+ Ok(changed)
+}
+
+/// Moves the two texts of row `slot` aside for a cover picture `aside` pixels wide, or back to where they always are.
+fn shift_labels(b: &mut Batch, s: &Screen, slot: usize, aside: Option) -> Result<(), LvError> {
+ let (t, a) = (s.row_title[slot], s.row_artist[slot]);
+ if t == ROOT || a == ROOT {
+ return Ok(());
+ }
+ let (x, w) = match aside {
+ Some(picture) => {
+ let x = THUMB_X + picture as i16 + THUMB_GAP;
+ (x, ROW_W - 90 - (x as i32 - 28))
+ }
+ None => (28, ROW_W - 90),
+ };
+ b.size(t, w, 40)?;
+ b.align(t, Align::LeftMid, x, -16)?;
+ b.size(a, w, 30)?;
+ b.align(a, Align::LeftMid, x, 20)?;
+ Ok(())
+}
+
+/// Puts the cover picture of the song in row `slot` at the left of its row and moves the row's texts aside: `px`
+/// holds `w` x `h` RGB565 pixels that live as long as the app. The picture is a child of the row, so it is removed by
+/// `hide_thumb` (or with the page). Does nothing when a picture is already on show.
+pub fn show_photo(b: &mut Batch, flush: Flush, s: &mut Screen, slot: usize, px: &'static [u16], w: usize, h: usize) -> Result<(), LvError> {
+ if slot >= s.row_count as usize || s.rows[slot] == ROOT || s.thumb != ROOT {
+ return Ok(());
+ }
+ let holder = open_picture(b, flush, s, slot, w as i32, h as i32)?;
+ room(b, flush)?;
+ let img = b.image(holder)?;
+ b.set_image(img, px, w as u16, h as u16)?;
+ b.align(img, Align::Center, 0, 0)?;
+ b.flags(img, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ s.thumb_image = img;
+ close_picture(b, flush, s, slot, holder, w as i32, h as i32)
+}
+
+/// Puts the cover picture of the song in row `slot` at the left of its row, as a mosaic of squares (neighbours of
+/// one colour are one square), and moves the row's texts aside. The picture is a child of the row, so it is removed
+/// by `hide_thumb` (or with the page). Does nothing when a picture is already on show.
+pub fn show_thumb(b: &mut Batch, flush: Flush, s: &mut Screen, slot: usize, pic: &Pic) -> Result<(), LvError> {
+ if slot >= s.row_count as usize || s.rows[slot] == ROOT || s.thumb != ROOT {
+ return Ok(());
+ }
+ let n = pic.edge as i32;
+ if n < 2 {
+ return Ok(());
+ }
+ let rows = pic.rows as usize;
+ let (pw, ph) = if pic.wide() { (WIDE_PX, WIDE_PY) } else { (THUMB_PX, THUMB_PX) };
+ let at_x = |i: usize| thumb::line(i, n as usize, pw as usize) as i32;
+ let at_y = |i: usize| thumb::line(i, rows, ph as usize) as i32;
+ let holder = open_picture(b, flush, s, slot, pw, ph)?;
+ thumb::rects::(pic, &mut |x, y, w, h, colour| {
+ room(b, flush)?;
+ let cw = at_x(x + w) - at_x(x);
+ let ch = at_y(y + h) - at_y(y);
+ let cx = at_x(x) + cw / 2 - pw / 2;
+ let cy = at_y(y) + ch / 2 - ph / 2;
+ let o = b.create(Class::Obj, holder)?;
+ b.size(o, cw, ch)?;
+ b.align(o, Align::Center, cx as i16, cy as i16)?;
+ b.style(o, Prop::Radius, 0, 0)?;
+ b.style(o, Prop::BgColor, 0, colour as i32)?;
+ b.style(o, Prop::BgOpa, 0, 255)?;
+ b.style(o, Prop::BorderWidth, 0, 0)?;
+ b.flags(o, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ Ok(())
+ })?;
+ close_picture(b, flush, s, slot, holder, pw, ph)
+}
+
+/// The empty, still hidden holder of a `pw` x `ph` picture at the left of row `slot`.
+fn open_picture(b: &mut Batch, flush: Flush, s: &mut Screen, slot: usize, pw: i32, ph: i32) -> Result {
+ room(b, flush)?;
+ let holder = b.create(Class::Obj, s.rows[slot])?;
+ // wider than the picture by the corner rings, which would otherwise be clipped
+ b.size(holder, pw + 2 * THUMB_RING, ph + 2 * THUMB_RING)?;
+ b.align(holder, Align::LeftMid, THUMB_X - THUMB_RING as i16, 0)?;
+ for p in [Prop::PadTop, Prop::PadBottom, Prop::PadLeft, Prop::PadRight] {
+ b.style(holder, p, 0, 0)?;
+ }
+ b.style(holder, Prop::BgOpa, 0, 0)?;
+ b.style(holder, Prop::BorderWidth, 0, 0)?;
+ // hidden while it is built: the squares and corners are sent in batches, and the picture appears only when whole
+ b.flags(holder, &[Flag::Hidden], &[Flag::Clickable, Flag::Scrollable])?;
+ s.thumb = holder;
+ s.thumb_slot = slot as u8;
+ Ok(holder)
+}
+
+/// Rounds the corners, shows the finished picture and moves the row's texts aside.
+fn close_picture(b: &mut Batch, flush: Flush, s: &mut Screen, slot: usize, holder: Obj, pw: i32, ph: i32) -> Result<(), LvError> {
+ // rounded corners, drawn over the squares: a quarter ring in the row's colour on each corner (antialiased)
+ let (cx, cy) = ((pw / 2 - THUMB_R) as i16, (ph / 2 - THUMB_R) as i16);
+ let colour = s.row_c1[slot] as i32;
+ for (k, &(x, y, from)) in [(-cx, -cy, 180), (cx, -cy, 270), (cx, cy, 0), (-cx, cy, 90)].iter().enumerate() {
+ let a = sector(b, flush, holder, THUMB_R + THUMB_RING, x, y, from, 90, colour)?;
+ room(b, flush)?;
+ b.style(a, Prop::ArcWidth, 0, THUMB_RING)?;
+ s.thumb_corners[k] = a;
+ }
+ room(b, flush)?;
+ b.flags(holder, &[], &[Flag::Hidden])?; // everything is in place: show the whole picture at once
+ shift_labels(b, s, slot, Some(pw))
+}
+
+/// Takes the cover picture off its row and puts the row's texts back. Does nothing when none is on show.
+pub fn hide_thumb(b: &mut Batch, s: &mut Screen) -> Result<(), LvError> {
+ if s.thumb == ROOT {
+ return Ok(());
+ }
+ let slot = s.thumb_slot as usize;
+ b.del(s.thumb)?;
+ s.thumb = ROOT;
+ s.thumb_slot = NO_SLOT;
+ s.thumb_image = ROOT;
+ if slot < s.row_count as usize {
+ shift_labels(b, s, slot, None)?;
+ }
+ Ok(())
+}
+
+/// The loading pulse's brightness range (white over the row's colour, of 255).
+pub const PULSE_OPA_MIN: i32 = 28;
+pub const PULSE_OPA_MAX: i32 = 105;
+
+/// Puts a rounded square, the size and shape of the cover picture, where the cover of row `slot` will appear, and
+/// moves the row's texts aside for it. `pulse_level` makes it brighten and fade while the cover loads. One object.
+pub fn show_pulse(b: &mut Batch, flush: Flush, s: &mut Screen, slot: usize) -> Result<(), LvError> {
+ if slot >= s.row_count as usize || s.rows[slot] == ROOT || s.pulse != ROOT || s.thumb != ROOT {
+ return Ok(());
+ }
+ room(b, flush)?;
+ // the same holder and corners as the cover picture, so the two line up exactly and the corners are smooth
+ // (a plain LVGL radius is drawn with stair steps on the watch; the arc corner covers are antialiased)
+ let holder = b.create(Class::Obj, s.rows[slot])?;
+ b.size(holder, THUMB_PX + 2 * THUMB_RING, THUMB_PX + 2 * THUMB_RING)?;
+ b.align(holder, Align::LeftMid, THUMB_X - THUMB_RING as i16, 0)?;
+ for p in [Prop::PadTop, Prop::PadBottom, Prop::PadLeft, Prop::PadRight] {
+ b.style(holder, p, 0, 0)?;
+ }
+ b.style(holder, Prop::BgOpa, 0, 0)?;
+ b.style(holder, Prop::BorderWidth, 0, 0)?;
+ b.flags(holder, &[Flag::Hidden], &[Flag::Clickable, Flag::Scrollable])?;
+ s.pulse = holder;
+ s.pulse_slot = slot as u8;
+ room(b, flush)?;
+ let o = b.create(Class::Obj, holder)?;
+ b.size(o, THUMB_PX, THUMB_PX)?;
+ b.align(o, Align::Center, 0, 0)?;
+ b.style(o, Prop::Radius, 0, 0)?;
+ b.style(o, Prop::BgColor, 0, WHITE)?;
+ b.style(o, Prop::BgOpa, 0, PULSE_OPA_MIN)?;
+ b.style(o, Prop::BorderWidth, 0, 0)?;
+ b.flags(o, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ s.pulse_inner = o;
+ let c = (THUMB_PX / 2 - THUMB_R) as i16;
+ let colour = s.row_c1[slot] as i32;
+ for (k, &(x, y, from)) in [(-c, -c, 180), (c, -c, 270), (c, c, 0), (-c, c, 90)].iter().enumerate() {
+ let a = sector(b, flush, holder, THUMB_R + THUMB_RING, x, y, from, 90, colour)?;
+ room(b, flush)?;
+ b.style(a, Prop::ArcWidth, 0, THUMB_RING)?;
+ s.pulse_corners[k] = a;
+ }
+ room(b, flush)?;
+ b.flags(holder, &[], &[Flag::Hidden])?;
+ shift_labels(b, s, slot, Some(THUMB_PX))
+}
+
+/// The pulse's brightness now (`opa` of 255).
+pub fn pulse_level(b: &mut Batch, s: &Screen, opa: i32) -> Result<(), LvError> {
+ if s.pulse == ROOT || s.pulse_inner == ROOT {
+ return Ok(());
+ }
+ b.style(s.pulse_inner, Prop::BgOpa, 0, opa.clamp(0, 255))
+}
+
+/// Takes the pulse off; the row's texts go back unless the cover picture is now on show in that row.
+pub fn hide_pulse(b: &mut Batch, s: &mut Screen) -> Result<(), LvError> {
+ if s.pulse == ROOT {
+ return Ok(());
+ }
+ let slot = s.pulse_slot as usize;
+ b.del(s.pulse)?;
+ s.pulse = ROOT;
+ s.pulse_slot = NO_SLOT;
+ s.pulse_inner = ROOT;
+ if slot < s.row_count as usize && !(s.thumb != ROOT && s.thumb_slot as usize == slot) {
+ shift_labels(b, s, slot, None)?;
+ }
+ Ok(())
+}
+
+// ---- colours of the player -------------------------------------------------------------------------------------
+
+fn channels(c: u16) -> (u32, u32, u32) {
+ (((c >> 11) & 31) as u32, ((c >> 5) & 63) as u32, (c & 31) as u32)
+}
+
+fn pack(r: u32, g: u32, b: u32) -> i32 {
+ ((r.min(31) << 11) | (g.min(63) << 5) | b.min(31)) as i32
+}
+
+/// `c` at `k / 256` of its brightness.
+pub fn shade(c: u16, k: u32) -> i32 {
+ let (r, g, b) = channels(c);
+ pack(r * k / 256, g * k / 256, b * k / 256)
+}
+
+/// `c` moved `k / 256` of the way to white.
+pub fn lighten(c: u16, k: u32) -> i32 {
+ let (r, g, b) = channels(c);
+ pack(r + (31 - r) * k / 256, g + (63 - g) * k / 256, b + (31 - b) * k / 256)
+}
+
+/// The slight dark tint over the cover.
+#[allow(dead_code)]
+pub fn background(c: u16) -> i32 {
+ shade(c, 104)
+}
+
+/// `c` with its colour pushed away from grey, so a pale cover still gives a clear colour.
+pub fn vivid(c: u16) -> u16 {
+ let (r, g, b) = channels(c);
+ // all three on the 0..=31 scale (green has one more bit)
+ let (r, g, b) = (r as i32, (g / 2) as i32, b as i32);
+ let m = (r + g + b) / 3;
+ let up = |v: i32| (m + (v - m) * 3 / 2).clamp(0, 31) as u32;
+ let (r, g, b) = (up(r), up(g), up(b));
+ ((r << 11) | ((g * 2 + g / 16) << 5) | b) as u16
+}
+
+/// What is under the glows: the cover's average colour, dark.
+#[allow(dead_code)]
+pub fn base(q: [u16; 4]) -> i32 {
+ let (mut r, mut g, mut b) = (0, 0, 0);
+ for c in q {
+ let (cr, cg, cb) = channels(c);
+ (r, g, b) = (r + cr, g + cg, b + cb);
+ }
+ shade(pack(r / 4, g / 4, b / 4) as u16, 90)
+}
+
+/// The cover's average colour as 8-bit r, g, b, scaled so its strongest channel is `GLOW_MAX` (a grey or dark cover
+/// still gets a soft glow; a bright one is toned down).
+pub fn glow_centre(q: [u16; 4]) -> (u32, u32, u32) {
+ let (mut r, mut g, mut b) = (0u32, 0u32, 0u32);
+ for c in q {
+ let (cr, cg, cb) = channels(c);
+ (r, g, b) = (r + cr * 255 / 31, g + cg * 255 / 63, b + cb * 255 / 31);
+ }
+ let (r, g, b) = (r / 4, g / 4, b / 4);
+ let top = r.max(g).max(b).max(1);
+ // never boost more than 3 times: a nearly black cover stays dark
+ let k = (GLOW_MAX * 256 / top).clamp(1, 768);
+ ((r * k / 256).min(255), (g * k / 256).min(255), (b * k / 256).min(255))
+}
+
+fn rgb8(r: u32, g: u32, b: u32) -> i32 {
+ (((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3)) as i32
+}
+
+/// The "tide": the bright core of the glow slides up and down while the outer discs stay still, so the watch only
+/// redraws a small area. The discs that are drawn are the ones where the colour takes a new step (about sixty).
+const HOLD: usize = 62;
+/// how far the light wanders from the middle, px
+const TIDE_AMP: i32 = 80;
+static mut TIDE_IDX: [u8; RINGS] = [0; RINGS];
+static mut TIDE_POS: [(i16, i16); RINGS] = [(0, 0); RINGS];
+static mut TIDE_N: usize = 0;
+/// which half of the moving discs the next tide frame moves (they take turns: half the commands per frame)
+static mut TIDE_TURN: usize = 0;
+
+fn smooth(t: u32) -> u32 {
+ t * t * (768 - 2 * t) / (256 * 256)
+}
+
+/// How much light disc `t` (0..=256, 0 = the outer one) has, 0..=256: mostly smoothstep with some straight ramp, so
+/// the glow stays short of the screen's edge and melts into the black with a long soft tail.
+fn ease(t: u32) -> u32 {
+ (smooth(t) * 3 + t) / 4
+}
+
+/// From where inwards the glow turns whiter: a hot core.
+const HOT_FROM: u32 = 170;
+
+/// How white (0..=256) disc `t` is: 0 until `HOT_FROM`, then up to about 40 % at the middle.
+fn hot(t: u32) -> u32 {
+ if t > HOT_FROM { (t - HOT_FROM) * 100 / (256 - HOT_FROM) } else { 0 }
+}
+
+/// sine of `p` (a turn is 1024), -256..=256
+fn sin(p: i32) -> i32 {
+ let p = p.rem_euclid(1024);
+ let (q, neg) = if p < 512 { (p, false) } else { (p - 512, true) };
+ let v = 4 * q * (512 - q) / 1024;
+ let v = v + 225 * (v * v / 256 - v) / 1000; // closer to a real sine
+ if neg { -v } else { v }
+}
+
+/// Where the light is at time `now` (ms): two slow waves per direction with different lengths, so it wanders in
+/// every direction and does not repeat for a long time.
+fn tide_light(now: u32) -> (i32, i32) {
+ let ph = |period: u32| (now % period * 1024 / period) as i32;
+ let x = (sin(ph(7_300)) * 6 + sin(ph(4_100)) * 4) / 10;
+ let y = (sin(ph(5_300)) * 6 + sin(ph(9_700)) * 4) / 10;
+ (TIDE_AMP * x / 256, TIDE_AMP * y / 256)
+}
+
+/// How far disc `i` follows the light, 0..=256.
+fn tide_weight(i: usize) -> i32 {
+ if i <= HOLD { 0 } else { ((i - HOLD) * 256 / (RINGS - 1 - HOLD)) as i32 }
+}
+
+/// Picks the discs to draw and returns how many. A disc with the colour of the one under it adds nothing; the moving
+/// ones step in coarser colour steps (half as many discs to redraw each frame).
+fn tide_pick() -> usize {
+ let mut n = 0;
+ let mut before = u32::MAX;
+ for i in 0..RINGS {
+ let t = (i * 256 / (RINGS - 1)) as u32;
+ let level = ease(t) >> 2;
+ if level != before || i == RINGS - 1 || (t > HOT_FROM && i % 2 == 0) {
+ unsafe {
+ (*(&raw mut TIDE_IDX))[n] = i as u8;
+ (*(&raw mut TIDE_POS))[n] = (0, 0);
+ }
+ n += 1;
+ }
+ before = level;
+ }
+ unsafe { *(&raw mut TIDE_N) = n };
+ n
+}
+
+/// What each drawn disc was last coloured, so a step only sends the discs that changed.
+static mut TIDE_COL: [u16; RINGS] = [0; RINGS];
+
+/// how long the player waits in the dark for the song's colours before it lights up with what it has
+const GLOW_WAIT_MS: u32 = 700;
+/// the light coming up, and going down before another song's colour comes up
+// longer than before: the watch can only draw a few frames a second here, so a 220 ms fall was 2 or 3 frames (a jump)
+const RISE_MS: u32 = 800;
+const FALL_MS: u32 = 380;
+/// the tide grows to its full reach this long after the light first came up
+const SWELL_MS: u32 = 1_600;
+/// colours closer than this (strongest channel, of 255) change in place, without dimming
+const SAME_GLOW: u32 = 28;
+
+#[derive(Clone, Copy, PartialEq, Debug)]
+pub enum Light {
+ /// dark, until the colour is known (or the wait is over, at this time)
+ Waiting(u32),
+ /// coming up since this time
+ Rising(u32),
+ On,
+ /// going down since this time, from this level
+ Falling(u32, u32),
+}
+
+/// The player's background light: it rises out of the dark in the song's colour, then the tide starts.
+pub struct Glow {
+ pub light: Light,
+ /// the colour on the screen
+ centre: (u32, u32, u32),
+ /// how much of the full light is on, 0..=256
+ level: u32,
+ /// since when the song on the player has had no colours (0: it has them)
+ unknown_since: u32,
+ /// the tide's own clock: it stands still while the light changes, so the tide never jumps
+ tide_ms: u32,
+ last: u32,
+}
+
+fn apart(a: (u32, u32, u32), b: (u32, u32, u32)) -> u32 {
+ a.0.abs_diff(b.0).max(a.1.abs_diff(b.1)).max(a.2.abs_diff(b.2))
+}
+
+/// The share (0..=256) of its colour disc `i` shows when the light is at `level`: the middle lights first and the
+/// light spreads outwards.
+fn bloom(level: u32, i: usize) -> u32 {
+ let t = (i * 256 / (RINGS - 1)) as u32; // 0 outer ..= 256 middle
+ let x = (level * 416 / 256).saturating_sub((256 - t) * 160 / 256).min(256);
+ smooth(x)
+}
+
+impl Glow {
+ pub const fn new() -> Glow {
+ Glow { light: Light::Waiting(0), centre: (0, 0, 0), level: 0, unknown_since: 0, tide_ms: 0, last: 0 }
+ }
+
+ /// A new player page: dark.
+ pub fn start(&mut self, now: u32) {
+ *self = Glow::new();
+ self.light = Light::Waiting(now.wrapping_add(GLOW_WAIT_MS));
+ self.last = now;
+ }
+
+ /// The app was away: the time that passed does not move the tide.
+ pub fn resume(&mut self, now: u32) {
+ self.last = now;
+ }
+
+ /// One frame: the light follows the colours of the song on the player, and the tide moves while it is steady.
+ pub fn frame(&mut self, b: &mut Batch, s: &Screen, m: &Model, now: u32) -> Result<(), LvError> {
+ let passed = now.wrapping_sub(self.last).min(100);
+ self.last = now;
+ let wanted = glow_centre(m.quarters(m.now));
+ // colours count once they are here, or once they have stayed away long enough
+ let known = m.has_quarters(m.now) || {
+ if self.unknown_since == 0 {
+ self.unknown_since = now | 1;
+ }
+ now.wrapping_sub(self.unknown_since) >= GLOW_WAIT_MS
+ };
+ if m.has_quarters(m.now) {
+ self.unknown_since = 0;
+ }
+ match self.light {
+ Light::Waiting(until) => {
+ if m.has_quarters(m.now) || now.wrapping_sub(until) as i32 >= 0 {
+ self.centre = wanted;
+ self.light = Light::Rising(now);
+ thin(b, s, true)?;
+ ring(b, s, m)?;
+ }
+ Ok(())
+ }
+ Light::Rising(since) => {
+ // the right colour arrived while it was barely lit: switch to it unseen
+ if known && self.centre != wanted && (self.level < 40 || apart(self.centre, wanted) < SAME_GLOW) {
+ self.centre = wanted;
+ ring(b, s, m)?;
+ }
+ if known && apart(self.centre, wanted) >= SAME_GLOW {
+ self.light = Light::Falling(now, self.level);
+ return Ok(());
+ }
+ // eased in time too (slow start, slow end), so the few frames that get drawn are evenly spaced in brightness
+ let lin = now.wrapping_sub(since).min(RISE_MS) * 256 / RISE_MS;
+ self.level = smooth(lin).max(self.level.min(256));
+ paint_glow(b, s, self.centre, self.level)?;
+ if self.level >= 256 {
+ self.light = Light::On;
+ thin(b, s, false)?;
+ }
+ Ok(())
+ }
+ Light::Falling(since, from) => {
+ let gone = now.wrapping_sub(since).min(FALL_MS);
+ let left = (FALL_MS - gone) * 256 / FALL_MS;
+ self.level = from * smooth(left) / 256;
+ paint_glow(b, s, self.centre, self.level)?;
+ if self.level == 0 {
+ self.light = Light::Waiting(now.wrapping_add(GLOW_WAIT_MS));
+ }
+ Ok(())
+ }
+ Light::On => {
+ if known && self.centre != wanted {
+ if apart(self.centre, wanted) >= SAME_GLOW {
+ self.light = Light::Falling(now, 256);
+ return thin(b, s, true);
+ }
+ self.centre = wanted;
+ paint_glow(b, s, wanted, 256)?;
+ ring(b, s, m)?;
+ }
+ self.tide_ms = self.tide_ms.wrapping_add(passed);
+ tide(b, s, self.tide_ms, self.tide_ms.min(SWELL_MS) * 256 / SWELL_MS)
+ }
+ }
+ }
+}
+
+/// While the light comes up or goes down every disc is recoloured on each frame, so every other one is left out
+/// (the outermost and the middle one stay): half the drawing, and the coarser steps don't show while it changes.
+fn thin(b: &mut Batch, s: &Screen, on: bool) -> Result<(), LvError> {
+ let n = unsafe { *(&raw const TIDE_N) };
+ for k in (1..n.saturating_sub(1)).step_by(2) {
+ if on {
+ b.flags(s.blobs[k], &[Flag::Hidden], &[])?;
+ } else {
+ b.flags(s.blobs[k], &[], &[Flag::Hidden])?;
+ }
+ }
+ Ok(())
+}
+
+/// Colours the discs for the light at `level` (0..=256) of `centre`.
+fn paint_glow(b: &mut Batch, s: &Screen, centre: (u32, u32, u32), level: u32) -> Result<(), LvError> {
+ let (idx, col, n) = unsafe { (&*(&raw const TIDE_IDX), &mut *(&raw mut TIDE_COL), *(&raw const TIDE_N)) };
+ for k in 0..n {
+ let i = idx[k] as usize;
+ let c = shade(glow_ring(centre, i) as u16, bloom(level, i)) as u16;
+ if c != col[k] {
+ b.style(s.blobs[k], Prop::BgColor, 0, c as i32)?;
+ col[k] = c;
+ }
+ }
+ Ok(())
+}
+
+/// One frame of the tide at time `now` (ms): moves the core. Only discs that moved are sent.
+pub fn tide(b: &mut Batch, s: &Screen, now: u32, reach: u32) -> Result<(), LvError> {
+ let (idx, pos, n) = unsafe { (&*(&raw const TIDE_IDX), &mut *(&raw mut TIDE_POS), *(&raw const TIDE_N)) };
+ let (lx, ly) = tide_light(now);
+ let (lx, ly) = (lx * reach as i32 / 256, ly * reach as i32 / 256);
+ // Each disc is moved every other frame, to where the light is NOW, so the frame is half as much to send and draw
+ // and more frames get through. Neighbouring discs differ by about a pixel at most, so the turns do not show.
+ let turn = unsafe { *(&raw const TIDE_TURN) };
+ unsafe { *(&raw mut TIDE_TURN) = turn ^ 1 };
+ for k in 0..n {
+ if k & 1 != turn {
+ continue;
+ }
+ let w = tide_weight(idx[k] as usize);
+ let p = ((lx * w / 256) as i16, (ly * w / 256) as i16);
+ if p != pos[k] {
+ b.align(s.blobs[k], Align::Center, p.0, CY + p.1)?;
+ pos[k] = p;
+ }
+ }
+ Ok(())
+}
+
+/// The colour of disc `i` (0 = the outer one, black) of the glow.
+pub fn glow_ring(centre: (u32, u32, u32), i: usize) -> i32 {
+ let t = (i * 256 / (RINGS - 1)) as u32; // 0..=256
+ let k = ease(t);
+ let w = hot(t);
+ let lift = |c: u32| {
+ let v = c * k / 256;
+ v + (255 - v.min(255)) * w / 256
+ };
+ rgb8(lift(centre.0), lift(centre.1), lift(centre.2))
+}
+
+/// The glow's centre colour as RGB565.
+pub fn glow_565(q: [u16; 4]) -> u16 {
+ let (r, g, b) = glow_centre(q);
+ rgb8(r, g, b) as u16
+}
+
+/// One glow: its quarter of the cover, pushed to a clear colour and bright.
+#[allow(dead_code)]
+pub fn glow(c: u16) -> i32 {
+ shade(vivid(c), 215)
+}
+
+/// The finished part of the ring.
+pub fn ring_colour(c: u16) -> i32 {
+ lighten(c, 190)
+}
+
+/// The rest of the ring: a little lighter than the background.
+pub fn track_colour(c: u16) -> i32 {
+ lighten(shade(c, 150) as u16, 40)
+}
+
+// ---- the player ------------------------------------------------------------------------------------------------
+
+/// A rounded solid bar that cannot be pressed (icons are made of these; a press goes to the button under them).
+fn bar_color(
+ b: &mut Batch, flush: Flush, parent: Obj, w: i32, h: i32, x: i16, radius: i32, color: i32,
+) -> Result {
+ room(b, flush)?;
+ let o = b.create(Class::Obj, parent)?;
+ b.size(o, w, h)?;
+ b.align(o, Align::Center, x, 0)?;
+ b.style(o, Prop::Radius, 0, radius)?;
+ b.style(o, Prop::BgColor, 0, color)?;
+ b.style(o, Prop::BgOpa, 0, 255)?;
+ b.style(o, Prop::BorderWidth, 0, 0)?;
+ b.flags(o, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ Ok(o)
+}
+
+fn bar(b: &mut Batch, flush: Flush, parent: Obj, w: i32, h: i32, x: i16, radius: i32) -> Result {
+ bar_color(b, flush, parent, w, h, x, radius, WHITE)
+}
+
+/// A triangle made of `n` bars `step` px apart: `tall_first` = the tallest bar is the first (it points right).
+#[allow(clippy::too_many_arguments)]
+fn wedge_color(
+ b: &mut Batch, flush: Flush, parent: Obj, n: usize, step: i32, w: i32, full: i32, x0: i32, dir: i32,
+ tall_first: bool, color: i32, out: &mut [Obj],
+) -> Result<(), LvError> {
+ for i in 0..n {
+ let k = if tall_first { n - i } else { i + 1 } as i32;
+ let h = (full * k / n as i32).max(4);
+ out[i] = bar_color(b, flush, parent, w, h, (x0 + dir * step * i as i32) as i16, 2, color)?;
+ }
+ Ok(())
+}
+
+#[allow(dead_code)]
+fn wedge(
+ b: &mut Batch, flush: Flush, parent: Obj, n: usize, step: i32, w: i32, full: i32, x0: i32, dir: i32,
+ tall_first: bool, out: &mut [Obj],
+) -> Result<(), LvError> {
+ wedge_color(b, flush, parent, n, step, w, full, x0, dir, tall_first, WHITE, out)
+}
+
+/// An arrow: a rounded shaft and a smooth head. `dir` -1 points left (Back), 1 right. `scale` 1 = the large home
+/// icon, 0 = the regular back arrow.
+fn arrow_shape(b: &mut Batch, flush: Flush, parent: Obj, x: i16, dir: i16, color: i32, scale: i32) -> Result<(), LvError> {
+ let (len, thick, head) = if scale > 0 { (44, 10, 34) } else { (30, 7, 26) };
+ // the whole arrow is `len` wide and centred on x: head at one end, shaft running into it
+ let tip = x + dir * (len / 2) as i16;
+ let shaft_w = len - head / 2;
+ let shaft_x = x - dir * (head / 4) as i16;
+ bar_color(b, flush, parent, shaft_w, thick, shaft_x, thick / 2, color)?;
+ // a 76-degree slice pointing along dir
+ sector(b, flush, parent, head, tip, 0, if dir < 0 { 322 } else { 142 }, 76, color)?;
+ Ok(())
+}
+
+fn arrow_color(b: &mut Batch, flush: Flush, parent: Obj, x: i16, color: i32) -> Result<(), LvError> {
+ arrow_shape(b, flush, parent, x, -1, color, 0)
+}
+
+#[allow(dead_code)]
+fn arrow(b: &mut Batch, flush: Flush, parent: Obj, x: i16) -> Result<(), LvError> {
+ arrow_color(b, flush, parent, x, WHITE)
+}
+
+/// The heart: a square turned 45 degrees with a round lobe on each of its two upper edges. With the square's side
+/// `H` the lobes are `H` wide circles centred on the midpoints of those edges (x = +-H / (2 sqrt 2), 1.06 H above the
+/// point), so every edge meets its lobe smoothly and the dip between them is a clean notch. The point is a 90-degree
+/// slice of radius `H` (all antialiased). Returns the three shapes so their colour can change with the saved state.
+fn heart_shape(b: &mut Batch, flush: Flush, parent: Obj, color: i32) -> Result<[Obj; 3], LvError> {
+ const H: i32 = 26;
+ const LOBE_X: i16 = 9; // H / (2 sqrt 2) = 9.2
+ const LOBE_Y: i16 = -8; // tip (20) - 1.06 H = -7.6
+ const TIP_Y: i16 = 20;
+ room(b, flush)?;
+ let mut parts = [ROOT; 3];
+ for (i, x) in [-LOBE_X, LOBE_X].into_iter().enumerate() {
+ let o = b.create(Class::Obj, parent)?;
+ b.size(o, H, H)?;
+ b.align(o, Align::Center, x, LOBE_Y)?;
+ b.style(o, Prop::Radius, 0, CIRCLE)?;
+ b.style(o, Prop::BgColor, 0, color)?;
+ b.style(o, Prop::BgOpa, 0, 255)?;
+ b.style(o, Prop::BorderWidth, 0, 0)?;
+ b.flags(o, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ parts[i] = o;
+ }
+ // the point: a 90-degree slice from (0, TIP_Y) opening upwards, its edges running into both lobes
+ parts[2] = sector(b, flush, parent, H, 0, TIP_Y, 225, 90, color)?;
+ Ok(parts)
+}
+
+/// A consistent, easy-to-hit pill used on the waiting screen.
+fn back_pill(b: &mut Batch, flush: Flush, parent: Obj) -> Result {
+ let k = b.create(Class::Btn, parent)?;
+ b.size(k, BACK_PILL_W, BACK_PILL_H)?;
+ b.align(k, Align::Center, 0, 160)?;
+ b.style(k, Prop::Radius, 0, CIRCLE)?;
+ b.style(k, Prop::BgColor, 0, LETTER_BG)?;
+ b.style(k, Prop::BgOpa, 0, 255)?;
+ b.style(k, Prop::BgColor, stock::PRESSED, ROW_PRESSED)?;
+ b.style(k, Prop::BgOpa, stock::PRESSED, 255)?;
+ b.style(k, Prop::BorderWidth, 0, 0)?;
+ b.events(k, &[Ev::Clicked])?;
+ // The waiting screen uses the same arrow-only red Back cue as the song list.
+ arrow_color(b, flush, k, 0, BACK_RED)?;
+ Ok(k)
+}
+
+/// A visible circular back button (no longer on the player: long press goes back there).
+#[allow(dead_code)]
+fn back_circle(b: &mut Batch, flush: Flush, parent: Obj, x: i16, y: i16) -> Result {
+ let k = b.create(Class::Btn, parent)?;
+ b.size(k, VOL, VOL)?;
+ b.align(k, Align::Center, x, y)?;
+ b.style(k, Prop::Radius, 0, CIRCLE)?;
+ // Keep a full-size invisible hit target; only the white arrow itself is visible.
+ b.style(k, Prop::BgColor, 0, LETTER_BG)?;
+ b.style(k, Prop::BgOpa, 0, 0)?;
+ b.style(k, Prop::BgColor, stock::PRESSED, ROW_PRESSED)?;
+ b.style(k, Prop::BgOpa, stock::PRESSED, 0)?;
+ b.style(k, Prop::BorderWidth, 0, 0)?;
+ b.events(k, &[Ev::Clicked])?;
+ arrow(b, flush, k, 0)?;
+ Ok(k)
+}
+
+/// A round, see-through white button (the play / prev / next hit area); pressing lights it.
+fn button(b: &mut Batch, parent: Obj, size: i32, opa: i32, x: i16, y: i16) -> Result {
+ let btn = b.create(Class::Btn, parent)?;
+ b.size(btn, size, size)?;
+ b.align(btn, Align::Center, x, y)?;
+ b.style(btn, Prop::Radius, 0, CIRCLE)?;
+ b.style(btn, Prop::BgColor, 0, WHITE)?;
+ b.style(btn, Prop::BgOpa, 0, opa)?;
+ b.style(btn, Prop::BgColor, stock::PRESSED, WHITE)?;
+ b.style(btn, Prop::BgOpa, stock::PRESSED, 90)?;
+ b.style(btn, Prop::BorderWidth, 0, 0)?;
+ // a long press anywhere on the player goes back, the buttons included
+ b.events(btn, &[Ev::Clicked, Ev::LongPressed])?;
+ Ok(btn)
+}
+
+/// "HH:MM".
+pub fn clock_text(hour: u8, minute: u8, buf: &mut [u8; 5]) -> &str {
+ *buf = [b'0' + hour / 10 % 10, b'0' + hour % 10, b':', b'0' + minute / 10 % 10, b'0' + minute % 10];
+ core::str::from_utf8(buf).unwrap_or("")
+}
+
+/// The player: the cover's tint, the clock, the song, the artist, prev / play / next and the ring.
+pub fn player(b: &mut Batch, flush: Flush, m: &Model, clock: &str, page_mode: bool) -> Result {
+ let ring_c = glow_565(m.quarters(m.now));
+ room(b, flush)?;
+ let page = b.create(Class::Obj, ROOT)?;
+ b.size(page, SCREEN, SCREEN)?;
+ for p in [Prop::PadTop, Prop::PadBottom, Prop::PadLeft, Prop::PadRight, Prop::BorderWidth, Prop::Radius] {
+ b.style(page, p, 0, 0)?;
+ }
+ b.style(page, Prop::BgColor, 0, 0)?;
+ b.style(page, Prop::BgOpa, 0, 255)?;
+ // Built hidden and shown by one last command: the watch draws between batches, so a visible page would appear
+ // piece by piece (glow, then buttons, then ring).
+ b.flags(page, &[Flag::Hidden], &[Flag::Scrollable])?;
+ // the crown comes to the app as CROWN events (the volume); the page does not scroll
+ b.knob(page)?;
+ let mut s = Screen { kind: Kind::Player, page, ..EMPTY };
+ let n = tide_pick();
+ unsafe { *(&raw mut TIDE_COL) = [0; RINGS] };
+ for k in 0..n {
+ room(b, flush)?;
+ let i = unsafe { (*(&raw const TIDE_IDX))[k] } as usize;
+ let d = 2 * (R_MAX * (RINGS - i) as i32 / RINGS as i32);
+ let o = b.create(Class::Obj, page)?;
+ b.size(o, d, d)?;
+ b.align(o, Align::Center, 0, CY)?;
+ b.style(o, Prop::Radius, 0, CIRCLE)?;
+ b.style(o, Prop::BgColor, 0, 0)?; // `Glow` brings the light up
+ b.style(o, Prop::BgOpa, 0, 255)?;
+ b.style(o, Prop::BorderWidth, 0, 0)?;
+ b.flags(o, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ s.blobs[k] = o;
+ }
+
+ // double-tap halves: invisible, behind every control, so the buttons keep working exactly as before
+ let _ = clock; // the clock is no longer shown on the player (it pushed the song down)
+ room(b, flush)?;
+ for (i, x) in [-(SCREEN / 4) as i16, (SCREEN / 4) as i16].into_iter().enumerate() {
+ let z = b.create(Class::Obj, page)?;
+ b.size(z, SCREEN / 2, SCREEN)?;
+ b.align(z, Align::Center, x, 0)?;
+ b.style(z, Prop::BgOpa, 0, 0)?;
+ b.style(z, Prop::BorderWidth, 0, 0)?;
+ b.style(z, Prop::Radius, 0, 0)?;
+ b.flags(z, &[], &[Flag::Scrollable])?;
+ b.events(z, &[Ev::Clicked, Ev::LongPressed])?;
+ if i == 0 { s.seek_left = z } else { s.seek_right = z }
+ }
+
+ // the song (and, while the volume is on, "Vol 65%" in its place)
+ room(b, flush)?;
+ let v = b.create(Class::Label, page)?;
+ b.size(v, 160, 30)?;
+ b.style(v, Prop::TextFont, 0, F24 as i32)?;
+ b.style(v, Prop::TextAlign, 0, 2)?;
+ let mut vbuf = [0u8; 8];
+ b.text(v, volume_text(m.level, &mut vbuf))?;
+ b.align(v, Align::TopMid, 0, TITLE_Y + 4)?;
+ b.flags(v, &[Flag::Hidden], &[])?;
+ s.vol_label = v;
+ let title_y = TITLE_Y;
+ let t = b.create(Class::Label, page)?;
+ b.size(t, 300, 40)?;
+ b.long_mode(t, LongMode::Dot)?;
+ b.style(t, Prop::TextAlign, 0, 2)?;
+ b.text(t, m.title(m.now))?;
+ b.align(t, Align::TopMid, 0, title_y)?;
+ s.title = t;
+ room(b, flush)?;
+ let ar = b.create(Class::Label, page)?;
+ b.size(ar, 300, 30)?;
+ b.long_mode(ar, LongMode::Dot)?;
+ b.style(ar, Prop::TextFont, 0, F24 as i32)?;
+ b.style(ar, Prop::TextColor, 0, SOFT)?;
+ b.style(ar, Prop::TextAlign, 0, 2)?;
+ b.text(ar, m.artist(m.now))?;
+ b.align(ar, Align::TopMid, 0, ARTIST_Y)?;
+ s.artist = ar;
+
+ // the ring first, so the button lies on top of it and touches it
+ room(b, flush)?;
+ let arc = b.create(Class::Arc, page)?;
+ b.size(arc, RING, RING)?;
+ b.align(arc, Align::Center, 0, CY)?;
+ b.angles(arc, 0, 360, 270)?;
+ b.value(arc, 0, false)?;
+ for (part, rounded) in [(0, 0), (stock::INDICATOR, 1)] {
+ b.style(arc, Prop::ArcWidth, part, RING_W)?;
+ b.style(arc, Prop::ArcRounded, part, rounded)?;
+ b.style(arc, Prop::ArcOpa, part, 255)?;
+ }
+ b.style(arc, Prop::ArcColor, 0, track_colour(ring_c))?;
+ b.style(arc, Prop::ArcColor, stock::INDICATOR, ring_colour(ring_c))?;
+ b.flags(arc, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ s.arc = arc;
+
+ // play / pause
+ room(b, flush)?;
+ let play = button(b, page, PLAY, 38, 0, CY)?;
+ s.play = play;
+ for (i, x) in [-13i16, 13].into_iter().enumerate() {
+ s.pause_bars[i] = bar(b, flush, play, 12, 44, x, 4)?;
+ }
+ for (i, h) in PLAY_SMALL.iter().enumerate() {
+ s.play_bars[i] = bar_color(b, flush, play, 3, *h as i32, -19 + 2 * i as i16, 0, WHITE)?;
+ }
+
+ // previous / next: a bar and a triangle each
+ room(b, flush)?;
+ s.prev = button(b, page, SIDE, 0, -SIDE_X, CY)?;
+ bar(b, flush, s.prev, 6, 30, -14, 3)?;
+ triangle(b, flush, s.prev, 30, 3, -1, WHITE)?;
+ room(b, flush)?;
+ s.next = button(b, page, SIDE, 0, SIDE_X, CY)?;
+ bar(b, flush, s.next, 6, 30, 14, 3)?;
+ triangle(b, flush, s.next, 30, -3, 1, WHITE)?;
+
+ // volume: a speaker (a box, a stepped cone, two sound waves) on a round button under the ring
+ room(b, flush)?;
+ let _ = (page_mode, VOL_Y);
+ let vol = button(b, page, VOL, 0, -BOTTOM_X, BOTTOM_Y)?;
+ s.vol = vol;
+ // speaker: a rounded box and a smooth cone (one antialiased slice opening to the right)
+ bar(b, flush, vol, 10, 16, -17, 3)?;
+ sector(b, flush, vol, 24, -20, 0, 312, 96, WHITE)?;
+ for (i, (size, w)) in [(26, 4), (42, 4)].into_iter().enumerate() {
+ room(b, flush)?;
+ let a = b.create(Class::Arc, vol)?;
+ b.size(a, size, size)?;
+ b.align(a, Align::Center, 3, 0)?;
+ b.angles(a, 0, 100, 310)?;
+ b.value(a, 0, false)?;
+ b.style(a, Prop::ArcWidth, 0, w)?;
+ b.style(a, Prop::ArcRounded, 0, 1)?;
+ b.style(a, Prop::ArcColor, 0, WHITE)?;
+ b.style(a, Prop::ArcOpa, 0, 255)?;
+ b.style(a, Prop::ArcOpa, stock::INDICATOR, 0)?;
+ b.style(a, Prop::BgOpa, stock::KNOB, 0)?;
+ b.flags(a, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ s.wave[i] = a;
+ }
+
+ // the heart, bottom right (in page mode this is where the back arrow was: long press goes back now)
+ room(b, flush)?;
+ let heart = button(b, page, VOL, 0, BOTTOM_X, BOTTOM_Y)?;
+ s.heart = heart;
+ s.heart_parts = heart_shape(b, flush, heart, HEART_OFF)?;
+
+ room(b, flush)?;
+ show_state(b, &s, m.playing)?;
+ show_liked(b, &s, m.liked)?;
+ show_volume(b, &s, false, m.level, m.muted)?;
+ b.flags(page, &[], &[Flag::Hidden])?; // everything is in place: show the player at once
+ Ok(s)
+}
+
+/// The volume button: lit, with "Vol 65%" in place of the clock, while the crown changes the volume; otherwise dark and
+/// the clock. The sound wave of the speaker is off at volume 0 and when muted.
+pub fn show_volume(b: &mut Batch, s: &Screen, on: bool, level: u8, muted: bool) -> Result<(), LvError> {
+ let mut buf = [0u8; 8];
+ b.text(s.vol_label, volume_text(level, &mut buf))?;
+ if on {
+ b.flags(s.title, &[Flag::Hidden], &[])?;
+ b.flags(s.vol_label, &[], &[Flag::Hidden])?;
+ } else {
+ b.flags(s.vol_label, &[Flag::Hidden], &[])?;
+ b.flags(s.title, &[], &[Flag::Hidden])?;
+ }
+ b.style(s.vol, Prop::BgOpa, 0, if on { 70 } else { 0 })?;
+ // a soft level shows only the inner wave, no sound (0 or muted) none
+ let silent = muted || level == 0;
+ for (i, &w) in s.wave.iter().enumerate() {
+ let show = !silent && (i == 0 || level >= 50);
+ if show { b.flags(w, &[], &[Flag::Hidden])? } else { b.flags(w, &[Flag::Hidden], &[])? }
+ }
+ Ok(())
+}
+
+/// The pause bars while it plays, the play triangle while it is paused.
+fn show_state(b: &mut Batch, s: &Screen, playing: bool) -> Result<(), LvError> {
+ for &o in s.pause_bars.iter().filter(|o| **o != ROOT) {
+ if playing { b.flags(o, &[], &[Flag::Hidden])? } else { b.flags(o, &[Flag::Hidden], &[])? }
+ }
+ for &o in s.play_bars.iter().filter(|o| **o != ROOT) {
+ if playing { b.flags(o, &[Flag::Hidden], &[])? } else { b.flags(o, &[], &[Flag::Hidden])? }
+ }
+ Ok(())
+}
+
+/// The ring takes the colour of the song's cover.
+fn ring(b: &mut Batch, s: &Screen, m: &Model) -> Result<(), LvError> {
+ let c = glow_565(m.quarters(m.now));
+ b.style(s.arc, Prop::ArcColor, 0, track_colour(c))?;
+ b.style(s.arc, Prop::ArcColor, stock::INDICATOR, ring_colour(c))
+}
+
+/// The song, the artist and play or pause follow the model (the tint follows in `Glow::frame`).
+pub fn show_now(b: &mut Batch, s: &Screen, m: &Model) -> Result<(), LvError> {
+ b.text(s.title, m.title(m.now))?;
+ if s.artist != ROOT {
+ b.text(s.artist, m.artist(m.now))?;
+ }
+ show_state(b, s, m.playing)
+}
+
+/// The ring: how much of the song is done, 0..=100.
+pub fn show_progress(b: &mut Batch, s: &Screen, percent: i32) -> Result<(), LvError> {
+ b.value(s.arc, percent.clamp(0, 100), false)
+}
+
+pub fn show_clock(b: &mut Batch, s: &Screen, text: &str) -> Result<(), LvError> {
+ if s.clock == ROOT { return Ok(()); } // the player has no clock any more
+ b.text(s.clock, text)
+}
+
+/// The heart: red when the song is saved, grey when not, hidden when the phone has no saved songs (older app).
+pub fn show_liked(b: &mut Batch, s: &Screen, liked: u8) -> Result<(), LvError> {
+ if s.heart == ROOT { return Ok(()); }
+ if liked == LIKED_UNKNOWN {
+ return b.flags(s.heart, &[Flag::Hidden], &[]);
+ }
+ b.flags(s.heart, &[], &[Flag::Hidden])?;
+ let c = if liked == LIKED_YES { HEART_ON } else { HEART_OFF };
+ for &o in &s.heart_parts {
+ if o == ROOT { continue; }
+ // the lobes are plain objects (background), the point is an arc
+ b.style(o, Prop::BgColor, 0, c)?;
+ b.style(o, Prop::ArcColor, 0, c)?;
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ extern crate std;
+ use super::*;
+ use std::boxed::Box;
+ use wp2_core::lvcmd::{self, Table};
+
+ struct Loader {
+ t: Table,
+ live_max: usize,
+ }
+
+ impl Loader {
+ fn flush(&mut self, b: &mut Batch) -> Result<(), LvError> {
+ if b.bytes().is_empty() {
+ return Ok(());
+ }
+ assert_eq!(lvcmd::validate(b.bytes(), &self.t, 0b1111), Ok(()));
+ for r in lvcmd::records(b.bytes()) {
+ lvcmd::apply(&mut self.t, &r.unwrap());
+ }
+ let live = (1..=192u16).filter(|&h| self.t.class(h).is_some()).count();
+ self.live_max = self.live_max.max(live);
+ b.clear();
+ Ok(())
+ }
+ }
+
+ fn full_model(n: usize) -> Model {
+ let mut m = Model::new();
+ m.count = n as u8;
+ for (i, t) in m.tracks.iter_mut().enumerate().take(n) {
+ let title = std::format!("Song number {i} with a long title");
+ let artist = "Some Artist & Friends";
+ t.title[..title.len().min(40)].copy_from_slice(&title.as_bytes()[..title.len().min(40)]);
+ t.tlen = title.len().min(40) as u8;
+ t.artist[..artist.len()].copy_from_slice(artist.as_bytes());
+ t.alen = artist.len() as u8;
+ t.c1 = 0x7BEF;
+ t.q = [0xF800, 0x07E0, 0x001F, 0xFFFF];
+ t.has_q = i % 2 == 0;
+ }
+ m.now = 1;
+ m.playing = true;
+ m.dur = 200;
+ m.pos = 20;
+ m
+ }
+
+ /// How much the player costs to send (bytes the watch must create before it can show it).
+ #[test]
+ fn player_stays_light_and_is_shown_last() {
+ let mut b = Batch::with_buf(Box::leak(Box::new([0; BUF])));
+ let mut l = Loader { t: Table::new(), live_max: 0 };
+ let m = full_model(10);
+ theme(&mut b).unwrap();
+ l.flush(&mut b).unwrap();
+ let (mut batches, mut bytes) = (0usize, 0usize);
+ let mut count = |b: &mut Batch| {
+ batches += 1;
+ bytes += b.bytes().len();
+ l.flush(b)
+ };
+ let _s = player(&mut b, &mut count, &m, "11:34", false).unwrap();
+ bytes += b.bytes().len();
+ batches += 1;
+ // The player is hidden until its last record, so these are the cost of one reveal: keep it from growing.
+ assert!(bytes < 13_500, "the player sends {bytes} bytes in {batches} batches");
+ }
+
+ #[test]
+ fn every_screen_validates_and_leaving_frees_it() {
+ let mut f = Batch::with_buf(Box::leak(Box::new([0; BUF])));
+ fonts(&mut f).unwrap();
+ assert_eq!(lvcmd::validate(f.bytes(), &Table::new(), 0), Ok(()));
+ let mut b = Batch::with_buf(Box::leak(Box::new([0; BUF])));
+ let mut l = Loader { t: Table::new(), live_max: 0 };
+ let mut m = full_model(50);
+ theme(&mut b).unwrap();
+ let mut s = wait(&mut b, &mut |b| l.flush(b), MODE_MUSIC, false, false).unwrap();
+ l.flush(&mut b).unwrap();
+ let first = s.page;
+ for round in 0..2 {
+ leave(&mut b, &s).unwrap();
+ s = menu(&mut b, &mut |b| l.flush(b), &m, round == 1, 0).unwrap();
+ l.flush(&mut b).unwrap();
+ assert_eq!(s.page, first, "the menu reuses the freed handles (round {round})");
+ assert_eq!(s.back != ROOT, round == 1);
+ assert!(!recolour(&mut b, &mut |b| l.flush(b), &mut s, &m).unwrap(), "nothing changed: nothing restyled");
+ m.tracks[3].c1 ^= 0x0841;
+ assert!(recolour(&mut b, &mut |b| l.flush(b), &mut s, &m).unwrap(), "a changed colour is restyled");
+ assert!(!recolour(&mut b, &mut |b| l.flush(b), &mut s, &m).unwrap());
+ l.flush(&mut b).unwrap();
+ leave(&mut b, &s).unwrap();
+ s = player(&mut b, &mut |b| l.flush(b), &m, "11:34", round == 1).unwrap();
+ assert_eq!(s.back, ROOT, "the player has no back arrow: long press goes back");
+ assert!(s.heart != ROOT && s.seek_left != ROOT && s.seek_right != ROOT);
+ for liked in [LIKED_YES, LIKED_NO, LIKED_UNKNOWN] {
+ show_liked(&mut b, &s, liked).unwrap();
+ }
+ l.flush(&mut b).unwrap();
+ m.playing = !m.playing;
+ show_now(&mut b, &s, &m).unwrap();
+ show_progress(&mut b, &s, 33).unwrap();
+ show_clock(&mut b, &s, "11:35").unwrap();
+ show_volume(&mut b, &s, true, 65, false).unwrap();
+ show_volume(&mut b, &s, false, 0, true).unwrap();
+ l.flush(&mut b).unwrap();
+ }
+ std::println!("most live objects: {}", l.live_max);
+ assert!(l.live_max < 192);
+ }
+
+ #[test]
+ fn square_and_wide_pictures_validate_and_come_off() {
+ let mut b = Batch::with_buf(Box::leak(Box::new([0; BUF])));
+ let mut l = Loader { t: Table::new(), live_max: 0 };
+ let m = full_model(50);
+ theme(&mut b).unwrap();
+ let mut s = menu(&mut b, &mut |b| l.flush(b), &m, false, 0).unwrap();
+ l.flush(&mut b).unwrap();
+ let mut t = thumb::Thumbs::new();
+ // the most squares a 50 song list allows, in a square and then a 16:9 picture
+ let n = thumb::budget(50);
+ for (idx, edge) in [(0u8, thumb::EDGE), (1u8, thumb::WIDE)] {
+ t.begin(idx);
+ for start in 0..n {
+ let msg = [b'I', idx, edge, start as u8, 0, 1, n as u8, (start % 40) as u8, (start % 30) as u8, 4, 4, 1, 0];
+ t.apply(&msg);
+ }
+ show_pulse(&mut b, &mut |b| l.flush(b), &mut s, 0).unwrap();
+ show_thumb(&mut b, &mut |b| l.flush(b), &mut s, 0, t.ready(idx).unwrap()).unwrap();
+ hide_pulse(&mut b, &mut s).unwrap();
+ l.flush(&mut b).unwrap();
+ assert!(s.thumb != ROOT);
+ hide_thumb(&mut b, &mut s).unwrap();
+ l.flush(&mut b).unwrap();
+ }
+ assert!(l.live_max < 192);
+ }
+
+ #[test]
+ fn start_screen_and_waiting_texts_validate() {
+ let mut b = Batch::with_buf(Box::leak(Box::new([0; BUF])));
+ let mut l = Loader { t: Table::new(), live_max: 0 };
+ theme(&mut b).unwrap();
+ let mut s = home(&mut b, &mut |b| l.flush(b), 0x03, 0).unwrap();
+ l.flush(&mut b).unwrap();
+ assert_eq!(s.kind, Kind::Home);
+ assert!(s.rows[0] != ROOT && s.rows[1] != ROOT && s.rows[0] != s.rows[1]);
+ assert_eq!(s.home_count, 2);
+ assert_eq!(s.home_modes[0], MODE_MUSIC);
+ assert_eq!(s.home_modes[1], MODE_PODCAST);
+ assert!(s.rows[2] == ROOT);
+ for obsolete in ["Your music", "Your shows", "Current media", "Your shortcuts"] {
+ assert!(
+ !b.bytes().windows(obsolete.len()).any(|window| window == obsolete.as_bytes()),
+ "redundant home subtitle still present: {obsolete}"
+ );
+ }
+ leave(&mut b, &s).unwrap();
+ // With the default anchor, Control media leads the category chooser.
+ s = home(&mut b, &mut |b| l.flush(b), 0x0C, 0).unwrap();
+ assert_eq!(s.home_count, 2);
+ assert_eq!(s.home_modes[0], MODE_EXTERNAL);
+ assert_eq!(s.home_modes[1], MODE_CUSTOM);
+ l.flush(&mut b).unwrap();
+ // Moving the focus down rotates the selected category to the first slot.
+ leave(&mut b, &s).unwrap();
+ s = home(&mut b, &mut |b| l.flush(b), 0x0C, 1).unwrap();
+ assert_eq!(s.home_count, 2);
+ assert_eq!(s.home_modes[0], MODE_CUSTOM);
+ assert_eq!(s.home_modes[1], MODE_EXTERNAL);
+ l.flush(&mut b).unwrap();
+ for (mode, empty) in [(MODE_MUSIC, false), (MODE_PODCAST, false), (MODE_PODCAST, true), (MODE_MUSIC, true)] {
+ leave(&mut b, &s).unwrap();
+ s = wait(&mut b, &mut |b| l.flush(b), mode, empty, false).unwrap();
+ assert_eq!(s.back, ROOT);
+ l.flush(&mut b).unwrap();
+ }
+ leave(&mut b, &s).unwrap();
+ s = wait(&mut b, &mut |b| l.flush(b), MODE_MUSIC, false, true).unwrap();
+ assert_ne!(s.back, ROOT);
+ l.flush(&mut b).unwrap();
+ leave(&mut b, &s).unwrap();
+ l.flush(&mut b).unwrap();
+ }
+
+ #[test]
+ fn player_without_a_song_and_a_short_list() {
+ let mut b = Batch::with_buf(Box::leak(Box::new([0; BUF])));
+ let mut l = Loader { t: Table::new(), live_max: 0 };
+ theme(&mut b).unwrap();
+ let mut m = full_model(0);
+ let s = player(&mut b, &mut |b| l.flush(b), &m, "00:00", true).unwrap();
+ assert_eq!(s.back, ROOT);
+ l.flush(&mut b).unwrap();
+ assert!(unsafe { *(&raw const TIDE_N) } <= 100);
+ for t in (0..9_000).step_by(250) {
+ tide(&mut b, &s, t, 256).unwrap();
+ assert!(b.bytes().len() <= BUF);
+ l.flush(&mut b).unwrap();
+ }
+ show_now(&mut b, &s, &m).unwrap();
+ l.flush(&mut b).unwrap();
+ leave(&mut b, &s).unwrap();
+ l.flush(&mut b).unwrap();
+ for n in [0, 1, 3] {
+ m = full_model(n);
+ let s = menu(&mut b, &mut |b| l.flush(b), &m, n == 1, 0).unwrap();
+ l.flush(&mut b).unwrap();
+ leave(&mut b, &s).unwrap();
+ l.flush(&mut b).unwrap();
+ }
+ }
+
+ #[test]
+ fn focus_event_index_maps_to_the_logical_row_after_rotation() {
+ assert_eq!(focused_anchor(0, 0, 4), Some(0));
+ assert_eq!(focused_anchor(0, 2, 4), Some(2));
+ assert_eq!(focused_anchor(2, 0, 4), Some(2));
+ assert_eq!(focused_anchor(2, 1, 4), Some(3));
+ assert_eq!(focused_anchor(2, 2, 4), Some(0));
+ assert_eq!(focused_anchor(3, 2, 4), Some(1));
+ assert_eq!(focused_anchor(0, -1, 4), None);
+ assert_eq!(focused_anchor(0, 4, 4), None);
+ assert_eq!(focused_anchor(3, 7, 4), None);
+ assert_eq!(focused_anchor(0, 0, 0), None);
+ }
+
+ #[test]
+ fn page_menu_rotates_back_and_tracks_without_losing_track_indices() {
+ let mut b = Batch::with_buf(Box::leak(Box::new([0; BUF])));
+ let mut l = Loader { t: Table::new(), live_max: 0 };
+ theme(&mut b).unwrap();
+ let m = full_model(3);
+ let s0 = menu(&mut b, &mut |b| l.flush(b), &m, true, 0).unwrap();
+ assert_ne!(s0.back, ROOT);
+ assert_eq!(&s0.row_indices[..3], &[0, 1, 2]);
+ leave(&mut b, &s0).unwrap();
+ l.flush(&mut b).unwrap();
+ let s2 = menu(&mut b, &mut |b| l.flush(b), &m, true, 2).unwrap();
+ assert_ne!(s2.back, ROOT);
+ assert_eq!(&s2.row_indices[..3], &[1, 2, 0]);
+ leave(&mut b, &s2).unwrap();
+ l.flush(&mut b).unwrap();
+ let regular = menu(&mut b, &mut |b| l.flush(b), &m, false, 2).unwrap();
+ assert_eq!(®ular.row_indices[..3], &[2, 0, 1]);
+ l.flush(&mut b).unwrap();
+ }
+
+ #[test]
+ fn vivid_pushes_colours_away_from_grey() {
+ assert_eq!(vivid(0xFFFF), 0xFFFF);
+ assert_eq!(vivid(0x0000), 0x0000);
+ assert_eq!(vivid(0xF800), 0xF800);
+ // a dull orange: red goes up, blue goes down
+ let dull = (20u16 << 11) | (32 << 5) | 14;
+ let v = vivid(dull);
+ let (r0, _, b0) = channels(dull);
+ let (r1, _, b1) = channels(v);
+ assert!(r1 > r0 && b1 < b0);
+ // the glow is a real colour, not darker than the old one
+ assert!(glow(dull) > 0);
+ }
+
+ #[test]
+ fn glow_is_dark_at_the_edge_and_the_covers_colour_in_the_middle() {
+ let q = [0x8410u16; 4]; // grey
+ let c = glow_centre(q);
+ assert!(c.0.abs_diff(c.1) < 8 && c.0 > 100 && c.0 <= GLOW_MAX);
+ assert_eq!(glow_ring(c, 0), 0);
+ let mut last = 0;
+ for i in 1..RINGS {
+ let v = glow_ring(c, i);
+ assert!(v >= last, "never darker towards the middle");
+ last = v;
+ }
+ // a red cover stays red; a nearly black one stays dark
+ let red = glow_centre([0xF800; 4]);
+ assert!(red.0 > red.1 * 4 && red.0 <= GLOW_MAX);
+ let dark = glow_centre([0x0001; 4]);
+ assert!(dark.0.max(dark.1).max(dark.2) <= 255);
+ }
+
+ #[test]
+ fn a_real_picture_validates_sharpens_and_comes_off() {
+ static PX: [u16; 128 * 72] = [0; 128 * 72];
+ let mut b = Batch::with_buf(Box::leak(Box::new([0; BUF])));
+ let mut l = Loader { t: Table::new(), live_max: 0 };
+ let m = full_model(50);
+ theme(&mut b).unwrap();
+ let mut s = menu(&mut b, &mut |b| l.flush(b), &m, false, 0).unwrap();
+ l.flush(&mut b).unwrap();
+ for (w, h) in [(88, 88), (128, 72), (88, 88)] {
+ show_pulse(&mut b, &mut |b| l.flush(b), &mut s, 0).unwrap();
+ show_photo(&mut b, &mut |b| l.flush(b), &mut s, 0, &PX[..w * h], w, h).unwrap();
+ hide_pulse(&mut b, &mut s).unwrap();
+ l.flush(&mut b).unwrap();
+ assert!(s.thumb != ROOT && s.thumb_image != ROOT);
+ hide_thumb(&mut b, &mut s).unwrap();
+ l.flush(&mut b).unwrap();
+ assert!(s.thumb == ROOT && s.thumb_image == ROOT);
+ }
+ assert!(l.live_max < 192);
+ }
+
+ #[test]
+ fn the_light_waits_rises_and_changes_with_the_song() {
+ let mut b = Batch::with_buf(Box::leak(Box::new([0; BUF])));
+ let mut l = Loader { t: Table::new(), live_max: 0 };
+ let mut m = full_model(3);
+ m.now = 0;
+ for t in m.tracks.iter_mut() {
+ t.has_q = false;
+ }
+ theme(&mut b).unwrap();
+ let s = player(&mut b, &mut |b| l.flush(b), &m, "10:00", false).unwrap();
+ l.flush(&mut b).unwrap();
+ let mut g = Glow::new();
+ g.start(1000);
+ // no colours yet: it stays dark
+ g.frame(&mut b, &s, &m, 1100).unwrap();
+ assert!(matches!(g.light, Light::Waiting(_)) && b.bytes().is_empty());
+ m.apply(&[b'Q', 0, 1, 0, 0xF8, 0, 0xF8, 0, 0xF8, 0, 0xF8]);
+ let mut now = 1120;
+ while g.light != Light::On {
+ g.frame(&mut b, &s, &m, now).unwrap();
+ l.flush(&mut b).unwrap();
+ now += 40;
+ assert!(now < 2200);
+ }
+ assert_eq!(g.level, 256);
+ // another song of another colour: down, then up in the new colour
+ m.apply(&[b'Q', 1, 1, 0x1F, 0, 0x1F, 0, 0x1F, 0, 0x1F, 0]);
+ m.now = 1;
+ g.frame(&mut b, &s, &m, now).unwrap();
+ assert!(matches!(g.light, Light::Falling(..)));
+ let end = now + 1600;
+ while now < end {
+ now += 40;
+ g.frame(&mut b, &s, &m, now).unwrap();
+ l.flush(&mut b).unwrap();
+ }
+ assert_eq!(g.light, Light::On);
+ assert_eq!(g.centre, glow_centre([0x001F; 4]));
+ // a song whose colours never come still gets the light, after the wait
+ m.now = 2;
+ g.start(now);
+ let end = now + 1800;
+ while now < end {
+ now += 40;
+ g.frame(&mut b, &s, &m, now).unwrap();
+ l.flush(&mut b).unwrap();
+ }
+ assert_eq!(g.light, Light::On);
+ }
+
+ #[test]
+ fn colours_and_clock() {
+ // the ring is lighter than the tint, the tint darker than the cover
+ let c = 0xF800u16; // pure red
+ assert!(background(c) < c as i32);
+ assert_eq!(shade(0xFFFF, 0), 0);
+ assert_eq!(lighten(0x0000, 256), 0xFFFF);
+ let mut buf = [0u8; 5];
+ assert_eq!(clock_text(7, 5, &mut buf), "07:05");
+ assert_eq!(clock_text(23, 59, &mut buf), "23:59");
+ }
+}
diff --git a/apps/watch-music/src/thumb.rs b/apps/watch-music/src/thumb.rs
new file mode 100644
index 0000000..537078d
--- /dev/null
+++ b/apps/watch-music/src/thumb.rs
@@ -0,0 +1,413 @@
+//! The cover pictures of the song list: the small mosaic the song the list has stopped on shows next to its name.
+//! No `Api` and no LVGL in here, so `cargo test` runs it on the computer.
+//!
+//! Watch -> phone:
+//! `a` idx edge blocks wide the list stopped on song `idx`: send its cover as a list of at most `blocks`
+//! rectangles on an `edge` x `edge` grid (the phone chooses them); `wide` 1 =
+//! a 16:9 cover may be sent as one instead
+//! Phone -> watch (first byte = kind, 1..=128 bytes):
+//! `I` idx edge start(u16 LE) n total (x y w h colour(u16 LE))*
+//! rectangles `start..start+n` of song `idx`'s picture, of `total` in all. They are
+//! painted in this order, each over the ones before it, so a thin line can lie on a
+//! big flat area. x, y, w, h are in grid squares; the colour is RGB565.
+//! The picture is complete when all `total` rectangles are here.
+//! `edge` 0 = the phone has no cover for this song.
+//! `edge` `WIDE` = a 16:9 cover (podcast episodes), on a `WIDE_W` x `WIDE_H` grid.
+//!
+//! The pictures live in RAM only (the few songs last shown) and are never written to the watch's storage.
+
+/// The grid the watch asks for, squares per side.
+pub const EDGE: u8 = 44;
+/// The biggest grid the picture takes; a bigger answer is ignored.
+pub const MAX_EDGE: usize = 44;
+/// The `edge` byte of a 16:9 picture, and its grid.
+pub const WIDE: u8 = 0x80;
+pub const WIDE_W: usize = 64;
+pub const WIDE_H: usize = 36;
+/// The last byte of the watch's request: it can draw 16:9 pictures.
+pub const WIDE_OK: u8 = 1;
+/// The most objects the app keeps alive (its own screen test holds it under this).
+const OBJECTS: usize = 192;
+/// Objects of a song list besides its rows and the cover's squares: the page and its bar, the Back arrow's pieces, the
+/// texts of the rows near the centre (2 x 9), the cover's box and its 4 corners, and some room to spare.
+const OTHERS: usize = 8 + 18 + 5 + 8;
+/// A cover never takes more squares than this, so it is drawn quickly.
+pub const MAX_BLOCKS: usize = 150;
+/// How many songs' pictures stay in RAM (the last few shown), so scrolling back to one is instant.
+pub const SLOTS: usize = 3;
+/// A slot that holds no song.
+const NO_SONG: u8 = 0xFF;
+/// Bytes of one rectangle in an `I` message, and the bytes before the first one.
+const RECT_BYTES: usize = 6;
+const HEADER: usize = 7;
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Status {
+ /// never asked for (or pushed out by newer ones)
+ Unknown,
+ /// asked; the picture has not fully arrived
+ Waiting,
+ /// every rectangle is here
+ Ready,
+ /// the phone has no cover for this song
+ NoCover,
+}
+
+#[derive(Clone, Copy)]
+struct Rect {
+ x: u8,
+ y: u8,
+ w: u8,
+ h: u8,
+ c: u16,
+}
+
+const NO_RECT: Rect = Rect { x: 0, y: 0, w: 0, h: 0, c: 0 };
+
+#[derive(Clone, Copy)]
+pub struct Pic {
+ idx: u8,
+ /// grid squares across (0 until the first piece arrives)
+ pub edge: u8,
+ /// grid squares down: the same as `edge`, or fewer for a 16:9 picture
+ pub rows: u8,
+ /// how many rectangles, from the first, have arrived
+ have: u16,
+ /// how many rectangles the picture has (0 until the first piece arrives)
+ total: u16,
+ no_cover: bool,
+ r: [Rect; MAX_BLOCKS],
+}
+
+impl Pic {
+ pub fn wide(&self) -> bool {
+ self.rows < self.edge
+ }
+
+ const EMPTY: Pic = Pic { idx: NO_SONG, edge: 0, rows: 0, have: 0, total: 0, no_cover: false, r: [NO_RECT; MAX_BLOCKS] };
+
+ pub fn status(&self) -> Status {
+ if self.idx == NO_SONG {
+ Status::Unknown
+ } else if self.no_cover {
+ Status::NoCover
+ } else if self.edge > 0 && self.total > 0 && self.have == self.total {
+ Status::Ready
+ } else {
+ Status::Waiting
+ }
+ }
+}
+
+pub struct Thumbs {
+ slots: [Pic; SLOTS],
+ next: usize,
+}
+
+impl Thumbs {
+ pub const fn new() -> Thumbs {
+ Thumbs { slots: [Pic::EMPTY; SLOTS], next: 0 }
+ }
+
+ /// Forgets every picture (another list is on the watch). Done in place: no second copy on the small stack.
+ pub fn clear(&mut self) {
+ for p in self.slots.iter_mut() {
+ p.idx = NO_SONG;
+ p.edge = 0;
+ p.rows = 0;
+ p.have = 0;
+ p.total = 0;
+ p.no_cover = false;
+ }
+ self.next = 0;
+ }
+
+ fn find(&self, idx: u8) -> Option {
+ if idx == NO_SONG {
+ return None;
+ }
+ self.slots.iter().position(|p| p.idx == idx)
+ }
+
+ pub fn status(&self, idx: u8) -> Status {
+ match self.find(idx) {
+ Some(i) => self.slots[i].status(),
+ None => Status::Unknown,
+ }
+ }
+
+ /// Drops what is held for song `idx` (a picture that stopped half-way is asked for afresh).
+ pub fn forget(&mut self, idx: u8) {
+ if let Some(i) = self.find(idx) {
+ self.slots[i].idx = NO_SONG;
+ self.slots[i].have = 0;
+ self.slots[i].total = 0;
+ self.slots[i].edge = 0;
+ self.slots[i].rows = 0;
+ }
+ }
+
+ /// The picture of song `idx`, once it is complete.
+ pub fn ready(&self, idx: u8) -> Option<&Pic> {
+ let i = self.find(idx)?;
+ let p = &self.slots[i];
+ if p.status() == Status::Ready { Some(p) } else { None }
+ }
+
+ /// Starts (or restarts) the picture of song `idx`: it keeps its slot, or takes the oldest one.
+ pub fn begin(&mut self, idx: u8) {
+ if idx == NO_SONG {
+ return;
+ }
+ let i = match self.find(idx) {
+ Some(i) => i,
+ None => {
+ let i = self.next;
+ self.next = (self.next + 1) % SLOTS;
+ i
+ }
+ };
+ let p = &mut self.slots[i];
+ p.idx = idx;
+ p.edge = 0;
+ p.rows = 0;
+ p.have = 0;
+ p.total = 0;
+ p.no_cover = false;
+ }
+
+ /// Applies one `I` message. Returns the song whose picture just became complete (or turned out to have no cover).
+ /// Anything that was not asked for, repeats a finished picture, leaves a gap or does not fit is ignored.
+ pub fn apply(&mut self, m: &[u8]) -> Option {
+ if m.len() < 3 || m[0] != b'I' {
+ return None;
+ }
+ let idx = m[1];
+ let edge = m[2] as usize;
+ let i = self.find(idx)?;
+ let p = &mut self.slots[i];
+ if matches!(p.status(), Status::Ready | Status::NoCover) {
+ return None;
+ }
+ if edge == 0 {
+ p.no_cover = true;
+ return Some(idx);
+ }
+ let (edge, rows) = if m[2] == WIDE {
+ (WIDE_W, WIDE_H)
+ } else if edge < 2 || edge > MAX_EDGE {
+ return None;
+ } else {
+ (edge, edge)
+ };
+ if m.len() < HEADER {
+ return None;
+ }
+ let start = u16::from_le_bytes([m[3], m[4]]) as usize;
+ let n = m[5] as usize;
+ let total = m[6] as usize;
+ if total == 0 || total > MAX_BLOCKS || n == 0 || start + n > total || m.len() < HEADER + RECT_BYTES * n {
+ return None;
+ }
+ if p.edge != 0 && (p.edge as usize != edge || p.rows as usize != rows || p.total as usize != total) {
+ return None;
+ }
+ // pieces come in order; a piece sent twice (the phone resends its window) overlaps what is here, which is fine
+ if start > p.have as usize {
+ return None;
+ }
+ // every rectangle must lie inside the grid, or the whole piece is ignored
+ for k in 0..n {
+ let b = HEADER + RECT_BYTES * k;
+ let (x, y, w, h) = (m[b] as usize, m[b + 1] as usize, m[b + 2] as usize, m[b + 3] as usize);
+ if w == 0 || h == 0 || x + w > edge || y + h > rows {
+ return None;
+ }
+ }
+ p.edge = edge as u8;
+ p.rows = rows as u8;
+ p.total = total as u16;
+ for k in 0..n {
+ let b = HEADER + RECT_BYTES * k;
+ p.r[start + k] = Rect { x: m[b], y: m[b + 1], w: m[b + 2], h: m[b + 3], c: u16::from_le_bytes([m[b + 4], m[b + 5]]) };
+ }
+ let end = start + n;
+ if end > p.have as usize {
+ p.have = end as u16;
+ }
+ if p.have == p.total { Some(idx) } else { None }
+ }
+}
+
+/// How many squares a cover may take on a list of `rows` rows (songs, plus Back if it has one).
+pub fn budget(rows: usize) -> usize {
+ OBJECTS.saturating_sub(OTHERS + rows).clamp(1, MAX_BLOCKS)
+}
+
+/// How many squares `rects` draws for this picture.
+pub fn count(p: &Pic) -> usize {
+ p.have as usize
+}
+
+/// Where grid line `i` (0..=`n`) of a picture `side` pixels wide falls: always an even number, so every square has
+/// an even size and sits on whole pixels. `side` must be even; the squares then fill it exactly.
+pub fn line(i: usize, n: usize, side: usize) -> usize {
+ (i * (side / 2) + n / 2) / n * 2
+}
+
+/// Calls `f(x, y, w, h, colour)` for the rectangles of the picture, in the order they are to be painted (each one over
+/// the ones before it). Every rectangle is something the watch has to create.
+pub fn rects(
+ p: &Pic,
+ f: &mut dyn FnMut(usize, usize, usize, usize, u16) -> Result<(), E>,
+) -> Result<(), E> {
+ if p.edge == 0 {
+ return Ok(());
+ }
+ for r in p.r[..p.have as usize].iter() {
+ f(r.x as usize, r.y as usize, r.w as usize, r.h as usize, r.c)?;
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// One `I` message: `rs` are the rectangles `start..` of a picture of `total` rectangles.
+ fn chunk(idx: u8, edge: u8, total: u8, start: u16, rs: &[(u8, u8, u8, u8, u16)]) -> Vec {
+ let [lo, hi] = start.to_le_bytes();
+ let mut m = vec![b'I', idx, edge, lo, hi, rs.len() as u8, total];
+ for &(x, y, w, h, c) in rs {
+ m.extend_from_slice(&[x, y, w, h]);
+ m.extend_from_slice(&c.to_le_bytes());
+ }
+ m
+ }
+
+ #[test]
+ fn a_picture_arrives_in_two_pieces() {
+ let mut t = Thumbs::new();
+ t.begin(3);
+ assert_eq!(t.status(3), Status::Waiting);
+ let first = [(0, 0, 4, 4, 1), (1, 1, 2, 2, 2)];
+ assert_eq!(t.apply(&chunk(3, 4, 3, 0, &first)), None);
+ assert_eq!(t.status(3), Status::Waiting);
+ // the same piece again (the phone resent its window) changes nothing
+ assert_eq!(t.apply(&chunk(3, 4, 3, 0, &first)), None);
+ assert_eq!(t.apply(&chunk(3, 4, 3, 2, &[(3, 3, 1, 1, 3)])), Some(3));
+ assert_eq!(t.status(3), Status::Ready);
+ assert_eq!(count(t.ready(3).unwrap()), 3);
+ }
+
+ #[test]
+ fn strangers_gaps_and_no_cover() {
+ let mut t = Thumbs::new();
+ // never asked for: ignored
+ assert_eq!(t.apply(&chunk(5, 4, 2, 0, &[(0, 0, 4, 4, 1)])), None);
+ assert_eq!(t.status(5), Status::Unknown);
+ t.begin(5);
+ // rectangle 1.. before 0..1: a gap, ignored
+ assert_eq!(t.apply(&chunk(5, 4, 3, 1, &[(0, 0, 4, 4, 1)])), None);
+ // bigger than the buffers: ignored
+ assert_eq!(t.apply(&chunk(5, 45, 2, 0, &[(0, 0, 4, 4, 1)])), None);
+ // a rectangle that sticks out of the grid: ignored
+ assert_eq!(t.apply(&chunk(5, 4, 2, 0, &[(2, 2, 3, 3, 1)])), None);
+ assert_eq!(t.status(5), Status::Waiting);
+ assert_eq!(t.apply(&[b'I', 5, 0]), Some(5));
+ assert_eq!(t.status(5), Status::NoCover);
+ }
+
+ #[test]
+ fn the_oldest_slot_is_reused_and_clear_forgets() {
+ let mut t = Thumbs::new();
+ for i in 0..4 {
+ t.begin(i);
+ }
+ assert_eq!(t.status(0), Status::Unknown);
+ assert_eq!(t.status(3), Status::Waiting);
+ t.clear();
+ assert_eq!(t.status(3), Status::Unknown);
+ }
+
+ #[test]
+ fn a_full_size_picture_fits_in_small_messages() {
+ let mut t = Thumbs::new();
+ t.begin(2);
+ let all: Vec<(u8, u8, u8, u8, u16)> =
+ (0..MAX_BLOCKS).map(|i| ((i % 40) as u8, (i / 4 % 40) as u8, 4, 4, i as u16)).collect();
+ let mut done = None;
+ for (i, part) in all.chunks(18).enumerate() {
+ let m = chunk(2, 44, MAX_BLOCKS as u8, (i * 18) as u16, part);
+ assert!(m.len() <= 128);
+ done = t.apply(&m);
+ }
+ assert_eq!(done, Some(2));
+ assert_eq!(count(t.ready(2).unwrap()), MAX_BLOCKS);
+ }
+
+ #[test]
+ fn grid_lines_fill_the_square_with_even_sizes() {
+ assert_eq!((line(0, 44, 88), line(44, 44, 88)), (0, 88));
+ for i in 0..44 {
+ assert_eq!(line(i + 1, 44, 88) - line(i, 44, 88), 2);
+ }
+ }
+
+ #[test]
+ fn a_wide_picture_has_its_own_grid() {
+ let mut t = Thumbs::new();
+ t.begin(6);
+ // below the 36th row: outside a 16:9 grid, ignored
+ assert_eq!(t.apply(&chunk(6, WIDE, 1, 0, &[(0, 30, 4, 8, 1)])), None);
+ assert_eq!(t.apply(&chunk(6, WIDE, 1, 0, &[(0, 0, 64, 36, 1)])), Some(6));
+ let p = t.ready(6).unwrap();
+ assert!(p.wide());
+ assert_eq!((p.edge, p.rows), (64, 36));
+ // a square one is not wide
+ t.begin(7);
+ t.apply(&chunk(7, 44, 1, 0, &[(0, 0, 44, 44, 1)]));
+ assert!(!t.ready(7).unwrap().wide());
+ // 128 x 72 pixels: every square is 2 x 2
+ assert_eq!((line(1, WIDE_W, 128), line(WIDE_W, WIDE_W, 128)), (2, 128));
+ assert_eq!((line(1, WIDE_H, 72), line(WIDE_H, WIDE_H, 72)), (2, 72));
+ }
+
+ #[test]
+ fn the_budget_leaves_room_for_the_list() {
+ assert_eq!(budget(3), MAX_BLOCKS);
+ assert_eq!(budget(51), 102);
+ // rows + everything else + the cover's squares stay under the limit
+ for rows in 1..=51 {
+ assert!(rows + OTHERS + budget(rows) <= OBJECTS);
+ }
+ }
+
+ #[test]
+ fn a_half_picture_can_be_forgotten_and_squares_counted() {
+ let mut t = Thumbs::new();
+ t.begin(4);
+ t.apply(&chunk(4, 4, 2, 0, &[(0, 0, 4, 4, 1)]));
+ t.forget(4);
+ assert_eq!(t.status(4), Status::Unknown);
+ t.begin(4);
+ assert_eq!(t.apply(&chunk(4, 4, 1, 0, &[(0, 0, 4, 4, 1)])), Some(4));
+ assert_eq!(count(t.ready(4).unwrap()), 1);
+ }
+
+ #[test]
+ fn rects_come_back_in_painting_order() {
+ let mut t = Thumbs::new();
+ t.begin(1);
+ let rs = [(0, 0, 4, 4, 7), (1, 1, 2, 2, 8), (0, 3, 4, 1, 9)];
+ assert_eq!(t.apply(&chunk(1, 4, 3, 0, &rs)), Some(1));
+ let p = t.ready(1).unwrap();
+ let mut got = Vec::new();
+ rects::<()>(p, &mut |x, y, w, h, c| {
+ got.push((x as u8, y as u8, w as u8, h as u8, c));
+ Ok(())
+ })
+ .unwrap();
+ assert_eq!(got, rs.to_vec());
+ }
+}
diff --git a/apps/watch-music/store.md b/apps/watch-music/store.md
new file mode 100644
index 0000000..dd40b63
--- /dev/null
+++ b/apps/watch-music/store.md
@@ -0,0 +1,36 @@
+Requires the **Watch Menu 2** Android app. Watch Music brings your phone's music, podcasts and media controls to your watch.
+
+- **Control media**: control whatever is playing on the phone, from music apps to video apps and podcast players.
+ Artist, title, play / pause, previous, next and a progress ring.
+- **Music**: browse your song list with the crown or by dragging. Tap a song to play it on your phone.
+- **Podcasts**: every podcast you add in Watch Menu 2 is a row. Tap one to open its episode player, and use previous
+ and next to move between episodes. **Only YouTube Music is supported.**
+- **Custom**: run the shortcuts you saved on the phone straight from the watch.
+
+## Player
+
+- **Heart to save a song.** Tap the heart to save what is playing, from any app.
+- **Double-tap to skip forward 5 seconds.** Double-tap the right side of the player to jump forward 5 seconds.
+- **Volume.** Press the speaker icon, then turn the crown to increase or decrease the volume.
+- **Progress ring.** One smooth ring around play / pause shows how far into the song you are.
+- **Long-press to go back.** Press and hold anywhere on the player to return to the list.
+- **Add it as a page.** Long-press Watch Music in Apps and choose Add page to keep the player a swipe away from the
+ watch face.
+
+- **Adding Music**
+Share a Spotify or YouTube Music playlist or individual song to the Watch Menu 2 app to add it to your music list.
+You can also copy a song's link, open a music group in Watch Menu 2, tap +, and paste the link as a new item.
+
+- **Adding Podcasts**
+**Only YouTube Music is supported.** Copy the podcast's share link, open the Music group in Watch Menu 2, tap +,
+and paste the link in Podcasts. Use the show's or playlist's share link, not a link to a single episode.
+
+## Requirements
+
+- The **Watch Menu 2** Android app (version 1.2.0 or newer) is required. Watch Music is its watch app: the phone
+ app provides your songs, podcasts, custom actions and the active media session, and carries every command back to
+ your phone. [Download Watch Menu 2](https://github.com/abdalrahmanmamdouh2004-svg/watch-menu/releases/tag/1.2.0).
+ Open it once and grant the notification access it asks for, so it can see what is playing.
+- The latest patched firmware batch (November 30, 2026 or newer) and the latest App Loader
+ (November 30, 2026 or newer): [firmware and App Loader instructions](/firmware).
+- The watch connected to your phone through Watch Menu 2, over the same Bluetooth link as Nothing X.
diff --git a/apps/watch-music/store.toml b/apps/watch-music/store.toml
new file mode 100644
index 0000000..a06835b
--- /dev/null
+++ b/apps/watch-music/store.toml
@@ -0,0 +1,5 @@
+name = "Watch Music"
+summary = "Music, podcasts and media controls on your watch: save songs with a heart, double-tap to skip 5s. REQUIRES Watch Menu 2 companion App"
+version = "0.11.0"
+author = "Abdalrahman"
+screenshots = ["shots/home.png", "shots/music-list.png", "shots/podcasts.png", "shots/music-player.png", "shots/saved-song.png", "shots/control-media.png", "shots/volume.png"]