From 5977c330ffa18982bd6bafa7d726bb95e9eef66f Mon Sep 17 00:00:00 2001 From: Ziyad Eslam Date: Tue, 1 Dec 2026 19:49:44 +0200 Subject: [PATCH 1/2] sdk: pin b1128d6 (app files, audio, mic, emoji, status bar, canvas Inter font) cmf-watch-sdk 2018e1a..b1128d6: - cmf-wp2-ui font: Inter Medium 20 px for canvas apps, baked into the app (~10 KiB, any loader, in the simulator), plus text::dots dot-matrix text, draw::scroll_bar (the stock lists' round scroll bar), ask and logo - app files on NAND (file_read/write/delete) and the speaker (audio_*): loader of 2026-11-21; the mic (mic_*) and the stock emoji: loader 6 - the loader-7 status bar: the time and GPS bars centred at y = 4 over every app - the Watch 3 Pro loader port (in progress), stub 11 (128 KiB loader budget), release tooling AGENTS.md and the watch-app skill: the new calls and the loaders they need, canvas apps draw text in cmf_wp2_ui::font, titles stay clear of the status bar. All 27 apps build and pass on b1128d6 (host tests, scripts/store build and check). Co-Authored-By: Claude Opus 5.5 --- .claude/skills/watch-app/SKILL.md | 5 +++-- AGENTS.md | 8 ++++++++ Makefile | 2 +- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.claude/skills/watch-app/SKILL.md b/.claude/skills/watch-app/SKILL.md index 719bb76..cc7441a 100644 --- a/.claude/skills/watch-app/SKILL.md +++ b/.claude/skills/watch-app/SKILL.md @@ -47,10 +47,11 @@ Worked examples: `sdk/examples/hello` (both, smallest), `sdk/examples/herdr-agen - **LVGL** (`cmf_wp2_app::lv` + `stock`): lists, buttons, text in stock fonts, crown scrolling. Not in the simulator. Verify with host tests that build every batch and with the emulator. -- **Canvas** (`cmf-wp2-ui`): custom drawing, animation. Runs in `make sim`. +- **Canvas** (`cmf-wp2-ui`): custom drawing, animation. Runs in `make sim`. Text in `cmf_wp2_ui::font` (Inter, the + system font's family), not the 16 px cell font. The look is always the stock one: `stock::font`, `stock::theme`, the `stock` colours, the system font. Text has to fit -the round 466×466 panel (`app-guide.md` section 2, Screen table). +the round 466×466 panel (`app-guide.md` section 2, Screen table) and stay clear of the loader's status bar at the top. ## 4. Scaffold and build it diff --git a/AGENTS.md b/AGENTS.md index caa02f9..e09fdae 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,6 +13,9 @@ is what an agent needs on top. channel, budgets, the shipping checklist in section 7). - `.sdk/wp2-apps/docs/abi-1.4.md`: the channel key K, heart rate, pager, cards, stub version; horizontal pager, phone music (`media_key`, `media_bind`) and the 5 s escape for `own_back` apps need the loader of 2026-11-16. + An app's own files on NAND for data over the 4 KiB `save` blob (`file_read`/`file_write`/`file_delete`, "Files") + and the speaker (`audio_*`, "Audio") need the loader of 2026-11-21; the mic (`mic_*`) and the stock emoji + (`emoji_read`) loader 6; `-22` on an older one. The simulator models files, audio and mic. - `.sdk/wp2-apps/docs/storage-inspection.md`: read-only device storage metadata and bounded scans; requires a loader with storage service v1. Probe with `Storage::open`, not the ABI minor. Installed icons use `Batch::installed_app_icon` with `IconSize`. The desktop simulator has no LVGL; verify icon rendering in QEMU. - `apps/vibration-lab` (template, canvas), `apps/ui-gallery` (stock LVGL widgets), `apps/sky-hop` (a game): worked examples. More in `.sdk/wp2-apps/sdk/examples` (`hello` and `herdr-agents` have a widget and a page). @@ -30,6 +33,11 @@ LVGL apps use the system font and the stock look (`cmf_wp2_app::stock`), never L `app-guide.md`, "Stock components: SDK and ui-gallery", maps each stock component to its SDK call. Rollers: short and not infinite (infinite ones draw at 4-6 fps; same section). +Canvas apps (`cmf-wp2-ui`) draw text in `cmf_wp2_ui::font`: Inter Medium 20 px, the system font's family, baked into +the app (~10 KiB, any loader, in the simulator too), measured in pixels. The 16 px cell font of `Api::text` and +`cmf_wp2_ui::text` is for pixel-art looks only. From loader 7 a status bar (the time, GPS bars) sits centred at +y = 4, about 72 px wide, over every app: keep titles clear of the top ~30 px (`abi-1.4.md`, "Status bar"). + ## What an app can be One package can offer several of these; ask which the owner wants before building. diff --git a/Makefile b/Makefile index f3916dd..7547890 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ # The SDK and its tooling. To move to a newer one: change the commit here, `make sdk`, build and test every app, # open a PR. Packages built against it change, but a store update still needs each app's version raised. -WP2_APPS_REV := 2018e1a7dd3716435de7665a5329e6e43f5ec7e5 +WP2_APPS_REV := b1128d651c0b881652e9b9a7ad69b133ee443b10 WP2_APPS_GIT := https://github.com/cmf-tech-community/cmf-watch-sdk SDK := .sdk/wp2-apps From bfd60ccf07879964feff4bb7c7c7b423469b40f2 Mon Sep 17 00:00:00 2001 From: Ziyad Eslam Date: Wed, 2 Dec 2026 01:37:33 +0200 Subject: [PATCH 2/2] Add Tech News app MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Hacker News front page on the watch: the top 8 stories from the public Algolia HN search API, fetched by FMC Companion's http.request (the 153-byte URL is past http.get's limit, so it goes as a two-part GET). - Menu app: a crown-scrolled list, each headline wrapped to up to three lines in Inter with a grey "780 pts · 335 comments · 3h" line, the stock scroll bar and a Refresh pill. A tap opens a story (whole title, points, comments, age; the crown steps through them, a tap or back returns). - Page next to the face: "Top on HN" and three headlines of two lines; a tap shows the next three. - Widget card: "HN 780 pts" and the top headline on two lines of at most 15 characters. One request at a time with a new id, stale ids dropped, recv drained every loop; every 15 min while shown, ASK again every 10 s, failures and DENIED after 60 s, a silent phone after 3/6/12/24/48 s then every 60 s. Titles are unescaped and folded to ASCII. The last headlines are kept in storage (at most 832 bytes), written once per answer. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + apps/tech-news/Cargo.toml | 14 + apps/tech-news/icon.svg | 26 ++ apps/tech-news/shots/list.png | Bin 0 -> 6534 bytes apps/tech-news/shots/page.png | Bin 0 -> 5263 bytes apps/tech-news/shots/story.png | Bin 0 -> 3595 bytes apps/tech-news/src/fixtures/front.json | 1 + apps/tech-news/src/format.rs | 315 ++++++++++++++ apps/tech-news/src/main.rs | 206 +++++++++ apps/tech-news/src/model.rs | 407 ++++++++++++++++++ apps/tech-news/src/model_tests.rs | 444 ++++++++++++++++++++ apps/tech-news/src/parse.rs | 560 +++++++++++++++++++++++++ apps/tech-news/src/screen.rs | 419 ++++++++++++++++++ apps/tech-news/src/screen_tests.rs | 329 +++++++++++++++ apps/tech-news/store.md | 25 ++ apps/tech-news/store.toml | 6 + 16 files changed, 2753 insertions(+) create mode 100644 apps/tech-news/Cargo.toml create mode 100644 apps/tech-news/icon.svg create mode 100644 apps/tech-news/shots/list.png create mode 100644 apps/tech-news/shots/page.png create mode 100644 apps/tech-news/shots/story.png create mode 100644 apps/tech-news/src/fixtures/front.json create mode 100644 apps/tech-news/src/format.rs create mode 100644 apps/tech-news/src/main.rs create mode 100644 apps/tech-news/src/model.rs create mode 100644 apps/tech-news/src/model_tests.rs create mode 100644 apps/tech-news/src/parse.rs create mode 100644 apps/tech-news/src/screen.rs create mode 100644 apps/tech-news/src/screen_tests.rs create mode 100644 apps/tech-news/store.md create mode 100644 apps/tech-news/store.toml diff --git a/README.md b/README.md index 1af0426..532db69 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ An app runs on a watch with the patched firmware and the App Loader, both on the | [`ha-remote`](apps/ha-remote) | Up to five Home Assistant light and group toggles with an Android companion | | [`metrolist`](apps/metrolist) | Browse and play your Metrolist (YouTube Music) library, and control the phone's playback; the [Android companion](https://github.com/krtkygpta/metrolist/releases/latest) carries the link | | [`connect-four`](apps/connect-four) | Connect Four against a negamax bot on three levels: tap a column to drop a disc | +| [`tech-news`](apps/tech-news) | The Hacker News front page: top headlines with points, comments and age, a page next to the face and a widget card (needs FMC Companion) | ## Make your own app diff --git a/apps/tech-news/Cargo.toml b/apps/tech-news/Cargo.toml new file mode 100644 index 0000000..e0470fe --- /dev/null +++ b/apps/tech-news/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "tech-news" +edition.workspace = true +license.workspace = true +version.workspace = true + +[dependencies] +cmf-wp2-app.workspace = true +cmf-wp2-ui.workspace = true +companion-rpc.workspace = true + +[[bin]] +name = "tech-news" +bench = false diff --git a/apps/tech-news/icon.svg b/apps/tech-news/icon.svg new file mode 100644 index 0000000..159d3d8 --- /dev/null +++ b/apps/tech-news/icon.svg @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/tech-news/shots/list.png b/apps/tech-news/shots/list.png new file mode 100644 index 0000000000000000000000000000000000000000..4d1d070980fb8d2788dec06c2a03e7656ff2696a GIT binary patch literal 6534 zcmcIoc{tnKx;7Loin3eP3cI_e*3_D3b+lDuT0?CiR1n*&RDwuUwM7kW4bd2PYj0|5 z8bc*wY?Ts3X^0XrMoEl8YKp7-oO{nX&$)lxf9`so-?P^GJ>UACZ>{xy?|Rotx#?ha zT=l;@cd3bmSe|$&z4*!hs(Y$$hWbCc4S~y1+EYVssSoj>FJAz_L1>t-` z#-n1BzV8L}-1v7PB1r%l)OmiCddP9X&@b74e6V~1DX(Y|e{eTH>Z)V>cVb`^IqJfp z%YPIgZhV2NNL6(cT)lu+FWFjT%1(xaT=&+M9YF}}JCk_KZtP|6tj@tn49{+plf*VF zW-6`p&9E*+`nyLY1ilt3JqhoI*L0(7LVm)Dyxk`W+HXgDUT#BxtU}CWjUmqKd?q$Z zK3?~qfF~nElqO&I(o`jgZS$bkPH@8!zv@EiR!hOR3aA(FwiyipU3k&ST4!yXF-*IV z|G#7W&w8YGZw0t^`|%=EyQo)&eZ(M@DiB>-d!BWN6}qenOOU>u{z; zjiZ4^rN?hd$A6G(2pe{0zxjh6JbqwU{1j8OTedJ9$}5(lt;%JXO4)V!G_c}!={l4e zc_JlLr0t6438G@|Q!9vmjGS#R5DS6NqbI_1DTrq6F1FZ@~@P)_rH6B z1PYzy`72BOmEOW%Fgu&g%|)|W>OaG#&dWZf+5NU`I$DncEg2dnEDt%R(@G~mySx(? zL9Ecn4yAKJOvF}cQT}5QrDvDbVZ;LnkEcu5Q0PrGurkm>E7{8aXSeYa8EYC4X|w*5 zkcI`r*f3+QgyC{@-L1RgO;5`@LS+jPVEbfRM%ntUk2E5W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M1%e<((+W^(>)7@K3;`W$YittYt&OE}!x-bb!;rYoe7iTU>=;=anbNK!5}G`D+2 zy>0iqdR%iPei260;gg;iT1uY+>c?|O*(*a0V~Tii@)%|HjP(B%)A*VLq54+hRf!|x R^dDoauQ^{tLWJ?Hm9A literal 0 HcmV?d00001 diff --git a/apps/tech-news/shots/page.png b/apps/tech-news/shots/page.png new file mode 100644 index 0000000000000000000000000000000000000000..a5026f3c7f83b6cc9bcd7a0e879940ac04a787e9 GIT binary patch literal 5263 zcmb_g2{hYVx5rf-Xw&cNr6_J&+Ij&`|N|T zwlq0@O!}CBfWUFno7Zm(2nc@s@f{K3uZ#&X-2?j0|yYkmHyH8LZK7td4N_s z#Mk&=#8M_+5w8&TR(vmD_`$Ar;Z6OFKp>WWjNJDy*6w+QjL6EhDbh%C`s8_9EpqP; zJMtiG`u5sMDK*IK%-jH#q zbDRmKUvKPp!aY`q?G;ufhH-3=|2N@4Ivo6SVycq*{t2npoGp|uEifk8GKFu6ISFV< zVnTxdZsorp;}Y4E`^x*uU>m31eV@h&`Do?1u@d$~x(~UPHc{RJAu$*1>1sha0kKEv z!(3JeZ_S79(Y`zM&I=}~XU>&mvmF1jWAt%Xe`QEFlRl67Hp*Lz>0Eeb(0ZTFc|T8?7f@=lXY|R-?$HHZkHffb z9%LT(!68?DSUC6{tvO5JuKTMSos-F7;wQ@37@bqk@ivS@{WKVvR}}DjIXG;1ZjmZ1 zwzv9%Ed-QaK;lAx6DPHN$qCy6Fv*C+kHuTd>h8sv`;rAvAHxLy{b~H~C2>FoCks$b z$R5*zPDnj_JZ>%w9(cwroSkT9W9mv!P1je}8zUy|tH>XhPFf07S1xAjEdNQ2i{KcbDrYrvn z{wL@0kY`Oh;y&b+WPfLa=~WxxY^V=;R}8J&5dhI~#VU81`OPl%XTLrh!io9F%eCvD zx&9|BEBWyh^<`ww%}5$zs@lW!+HN!?{HUWvInvK|SZd43@x3)9s4gE~QaU;`1R`d5 zc4kg=-9c&9wa)wBPA%vb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dHl&^E*?x_CexMNeE5gKilGjvTD}Wd~ z)xrokIm%pT#=(&|t_YXUzrRLDARBC~REqP9A@`aVx?nT930t?VMy!AKY$clpB+Q7! zoTMVHYL3Sw*cW0iZ+v%RJSECl$$I~00}Yfx*GbFcNshlO@!jC+F6>5&{z&)roPn}t zl0FAA^V~sCfB-{b)eIrJdmSNt`kRGjiB9@_lN}l45BBS6gE$q&V zJ@~hSFWG;T(hwZ5T%akSR$=l5)};4M#El9f6S8-Wy1x)Qkf-Nag>;;fjNcs*=VuwS zfm}%?#VCJnq{U{|ZAK12O76r5Mg;w{MB%4S+Kv`(A!kd=SKAxj^GH#=4D(PPsHS3Y zZFj`(eVXv+$LhJv4BIQ-0naQSOl#RS6V4v%4S;H1NAM|=b9F2G*C(AaZ zNE_>#2D_-vCn@gH%rtWALBr8(mNMF`=cy$~3rTOz9!A<2HUnvowe$4ewz{6QghrQtrFXUM(_j+ZX*3SYmNS?wB{~+C)P2yT z9M-c}bvirYx((DBpKg$9a1+<+r)m9d(+fsQf#xrT^Wx@tx$wATIWIlv+Uw}Q0%w)y zrO4BV8BPn6Ed{Cz|tgHv3eT&*whaxbe6^B!o@_46F8F-0_=iahEE+YTv+W$Lb z{;w-5?#vk8-lF&S!FGEIOt1o@NN^JT5JIsSOSMW847|ZmC2vBH_j9`-MEL2IfI4P$ zZ`A4fgWOpE6UJ+9tuj3%X7Xs}Zge9J7q7q^YvnAVg&cZ61Bm8W+4&CX zMtt}L9y&4_3%VK+Rd_{|Rb~-Os^(@_>hy9+!n`89k^g{DgfHVZ&fbBkwQm*FUwCNc zBeBe()`u)`Fn|&hK&|0N1ghrLp9?zm9XS1X4*Y*47GYPu;+4AHee>7%f2cLRVR^mk I57+qr0QA)>lK=n! literal 0 HcmV?d00001 diff --git a/apps/tech-news/shots/story.png b/apps/tech-news/shots/story.png new file mode 100644 index 0000000000000000000000000000000000000000..bea4a92b9105a313a9566b33678c5904ff3dab7c GIT binary patch literal 3595 zcmcgudo&y9whsn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z3ZuE(5rAu-q$=UhBw$c7=~J7QWq9D5 z^*Rx*w2bPl`mzcc+!myv5|yI6+I=JyodQ)m?-aB2?jEt3V~m!JwBVk?q;1)LXQje> zhYL;sEtwXQ8Ap`K(veSgQn#DeC&;^pIwpl{e_o0>N~P(5k5Y|brJs_iYT)Ku(6XNM zdFsaK4#b-umqelI`mZf?3vN{Hxpi2{Iv@OOHr&D3`MY1)`1Qs1`Cwe52|KD$=l(?P z5qUSb$wz{Nn8Bjd!_cL^WMIu>=L2Xab`2&`Bp5Z&2Si?aDcbfUcKk7*-dYePvaN&s zZwUK?x&JcKXkn>gx%iYvCxVN`qPDUB#I9$VqpUff@MrfDr)>C=2OlYx>%{CSOi<^79 z0wcGqtt+4yH-BkK3;WX5krxRDIT^nAa_iyUce!Lzi?m5o^tHiY!Nhnom-i?XabZ45 z-eIocg;E()=3a;ZMcn1?$sk+;G-RR9{9_jW>|%LQU{$;MDXV)Im+H&5REyR%;+4eSb0IWQR&NXn>;UZ5%tcl(0kC6 zPv+sMr=9#$fg-;_a`*Wt|DE@(Hsmj1?d$c~c5*i}HY$!4`e7C2)C*alju~EtCbu8k zyF*u64LaoXbuyV=0W8MX)wlKXa3Kg)e_tw%mv0Ut9KJe|AQyPsTit@LppAC%=KH1G#geyI3cDU3ZAQ4}*xdZ6xxf8( uYqiiQ$6*bmkW_V-&z(CdLWi;aq8|WnY#VkImaKt7i#|+nEnr0ns3hl literal 0 HcmV?d00001 diff --git a/apps/tech-news/src/fixtures/front.json b/apps/tech-news/src/fixtures/front.json new file mode 100644 index 0000000..e55a335 --- /dev/null +++ b/apps/tech-news/src/fixtures/front.json @@ -0,0 +1 @@ +{"exhaustive":{"nbHits":true,"typo":true},"exhaustiveNbHits":true,"exhaustiveTypo":true,"hits":[{"created_at_i":1796147550,"num_comments":335,"objectID":"50718402","points":780,"title":"Amazon Ergo: A fast, cost-effective open-weights model"},{"created_at_i":1796139469,"num_comments":247,"objectID":"50716305","points":429,"title":"Cryptopocalypse"},{"created_at_i":1796144952,"num_comments":155,"objectID":"50717648","points":417,"title":"Michael Caine has died"},{"created_at_i":1796122809,"num_comments":154,"objectID":"50713342","points":388,"title":"Goals don't work. Rely on your values"},{"created_at_i":1796144120,"num_comments":91,"objectID":"50717444","points":364,"title":"Ty 1.0: Fast Python type checker and language server"},{"created_at_i":1796142479,"num_comments":137,"objectID":"50717029","points":311,"title":"Claude 5-minute prompt cache vs GPT 30-minute cache: the cost of pauses"},{"created_at_i":1796039570,"num_comments":486,"objectID":"50698717","points":297,"title":"Advent of Code 2026"},{"created_at_i":1796134439,"num_comments":151,"objectID":"50715275","points":284,"title":"Micromorts \u2013 visualizing your chances of dying doing everyday activities"}],"hitsPerPage":8,"nbHits":30,"nbPages":4,"page":0,"params":"tags=front_page&hitsPerPage=8&attributesToRetrieve=title%2Cpoints%2Cnum_comments%2Ccreated_at_i&attributesToHighlight=none&advancedSyntax=true&analyticsTags=backend","processingTimeMS":1,"processingTimingsMS":{"_request":{"queue":3,"roundTrip":15},"total":0},"query":"","serverTimeMS":4} diff --git a/apps/tech-news/src/format.rs b/apps/tech-news/src/format.rs new file mode 100644 index 0000000..e61aee1 --- /dev/null +++ b/apps/tech-news/src/format.rs @@ -0,0 +1,315 @@ +//! The short texts the screens and the widget card show: times, ages, a story's points and comments, the card's two +//! lines. Integers only. Titles are ASCII by now (`parse::ascii`); the separators here are the font's own `·`. + +/// A short text built in place; what doesn't fit is cut at a character boundary. +#[derive(Clone, Copy, PartialEq, Eq)] +pub struct Line { + buf: [u8; 48], + len: usize, +} + +impl Line { + pub const fn new() -> Line { + Line { buf: [0; 48], len: 0 } + } + + pub fn of(s: &str) -> Line { + let mut l = Line::new(); + l.push(s); + l + } + + /// Appends `s`, or as much of it as fits, whole characters only. + pub fn push(&mut self, s: &str) { + for ch in s.chars() { + let mut b = [0u8; 4]; + let e = ch.encode_utf8(&mut b).as_bytes(); + if self.len + e.len() > self.buf.len() { + return; + } + self.buf[self.len..self.len + e.len()].copy_from_slice(e); + self.len += e.len(); + } + } + + /// `n` in decimal, at least `width` digits (zero padded). + pub fn uint(&mut self, n: u64, width: usize) { + let mut d = [0u8; 20]; + let (mut i, mut v) = (0, n); + while (v > 0 || i < width.max(1)) && i < d.len() { + d[i] = b'0' + (v % 10) as u8; + v /= 10; + i += 1; + } + while i > 0 { + i -= 1; + if self.len < self.buf.len() { + self.buf[self.len] = d[i]; + self.len += 1; + } + } + } + + pub fn as_str(&self) -> &str { + core::str::from_utf8(&self.buf[..self.len]).unwrap_or("") + } + + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } +} + +impl core::fmt::Debug for Line { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + core::fmt::Debug::fmt(self.as_str(), f) + } +} + +/// The separator between the parts of a meta line. +pub const DOT: &str = " \u{b7} "; + +/// "14:05" of wall-clock minutes. +pub fn hhmm(wall: i32) -> Line { + let m = wall.rem_euclid(1440) as u64; + let mut l = Line::new(); + l.uint(m / 60, 2); + l.push(":"); + l.uint(m % 60, 2); + l +} + +/// An age in minutes as its number and unit: `m` below an hour, `h` below two days, `d` after; `None` for less +/// than a minute (or a post "from the future": a clock or zone off by a little). +pub fn age_parts(min: i32) -> Option<(u32, &'static str)> { + match min { + m if m < 1 => None, + m if m < 60 => Some((m as u32, "m")), + m if m < 48 * 60 => Some(((m / 60) as u32, "h")), + m => Some(((m / 1440) as u32, "d")), + } +} + +/// "now", "12m", "3h", "2d". +pub fn age(min: i32) -> Line { + let mut l = Line::new(); + match age_parts(min) { + None => l.push("now"), + Some((n, unit)) => { + l.uint(n as u64, 1); + l.push(unit); + } + } + l +} + +/// What the clock changes in [`age`]: equal keys draw the same text. +pub fn age_key(min: i32) -> u32 { + match age_parts(min) { + None => 0, + Some((n, unit)) => n.saturating_mul(4) + if unit == "m" { 1 } else if unit == "h" { 2 } else { 3 }, + } +} + +/// "3 hours ago", "1 minute ago", "just now", for the detail screen. +pub fn age_long(min: i32) -> Line { + let mut l = Line::new(); + match age_parts(min) { + None => l.push("just now"), + Some((n, unit)) => { + l.uint(n as u64, 1); + let word = match unit { + "m" => " minute", + "h" => " hour", + _ => " day", + }; + l.push(word); + if n != 1 { + l.push("s"); + } + l.push(" ago"); + } + } + l +} + +/// "780 points", "1 point" (`short`: "780 pts", "1 pt"). +pub fn points(n: u32, short: bool) -> Line { + let mut l = Line::new(); + l.uint(n as u64, 1); + l.push(match (short, n == 1) { + (true, true) => " pt", + (true, false) => " pts", + (false, true) => " point", + (false, false) => " points", + }); + l +} + +/// "335 comments", "1 comment". +pub fn comments(n: u32) -> Line { + let mut l = Line::new(); + l.uint(n as u64, 1); + l.push(if n == 1 { " comment" } else { " comments" }); + l +} + +/// The grey line under a headline: "780 pts · 335 comments · 3h", or without the comments ("780 pts · 3h"). +pub fn meta(points_n: u32, comments_n: Option, age_min: i32) -> Line { + let mut l = points(points_n, true); + if let Some(c) = comments_n { + l.push(DOT); + l.push(comments(c).as_str()); + } + l.push(DOT); + l.push(age(age_min).as_str()); + l +} + +/// `text` (ASCII) on two lines of at most `max` characters, cut at a space where it can be; a text that goes on +/// past the second line ends it in "...". A word longer than a line is cut hard. +pub fn two_lines(text: &str, max: usize) -> Line { + let text = text.trim(); + let (first, rest) = take_line(text, max); + let mut l = Line::of(first); + let rest = rest.trim_start(); + if rest.is_empty() { + return l; + } + let (second, more) = take_line(rest, max); + let second = if more.trim().is_empty() { + second + } else { + // room for the dots: a shorter second line, at a space if there is one + take_line(rest, max.saturating_sub(3)).0.trim_end_matches([' ', '.', ',', ':', ';', '-']) + }; + l.push("\n"); + l.push(second); + if !more.trim().is_empty() { + l.push("..."); + } + l +} + +/// The longest start of `s` (ASCII) of at most `max` characters that ends before a space (or at the end), and the +/// rest; a first word longer than `max` is cut at `max`. +fn take_line(s: &str, max: usize) -> (&str, &str) { + if s.len() <= max { + return (s, ""); + } + let b = s.as_bytes(); + // a space right after the cut keeps the whole last word + if b.get(max) == Some(&b' ') { + return (&s[..max], &s[max..]); + } + match s[..max].rfind(' ') { + Some(i) if i > 0 => (s[..i].trim_end(), &s[i..]), + _ => { + let mut k = max; + while k > 0 && !s.is_char_boundary(k) { + k -= 1; + } + (&s[..k], &s[k..]) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn times() { + assert_eq!(hhmm(14 * 60 + 5).as_str(), "14:05"); + assert_eq!(hhmm(1440 * 20_000 + 59).as_str(), "00:59"); + assert_eq!(hhmm(-1).as_str(), "23:59"); + } + + #[test] + fn ages() { + let a = |m| age(m).as_str().to_owned(); + assert_eq!(a(-30), "now"); + assert_eq!(a(0), "now"); + assert_eq!(a(1), "1m"); + assert_eq!(a(59), "59m"); + assert_eq!(a(60), "1h"); + assert_eq!(a(179), "2h"); + assert_eq!(a(47 * 60 + 59), "47h"); + assert_eq!(a(48 * 60), "2d"); + assert_eq!(a(i32::MAX), "1491308d"); + assert_eq!(age_long(0).as_str(), "just now"); + assert_eq!(age_long(1).as_str(), "1 minute ago"); + assert_eq!(age_long(61).as_str(), "1 hour ago"); + assert_eq!(age_long(185).as_str(), "3 hours ago"); + assert_eq!(age_long(3 * 1440).as_str(), "3 days ago"); + // the key changes exactly when the text does + for m in -5..5000 { + assert_eq!(age_key(m) == age_key(m + 1), age(m) == age(m + 1), "{m}"); + } + } + + #[test] + fn meta_lines() { + assert_eq!(meta(780, Some(335), 150).as_str(), "780 pts \u{b7} 335 comments \u{b7} 2h"); + assert_eq!(meta(1, Some(1), 0).as_str(), "1 pt \u{b7} 1 comment \u{b7} now"); + assert_eq!(meta(42, None, 12).as_str(), "42 pts \u{b7} 12m"); + assert_eq!(points(780, false).as_str(), "780 points"); + assert_eq!(comments(0).as_str(), "0 comments"); + // the longest there can be still fits the line's buffer + let l = meta(u32::MAX, Some(u32::MAX), i32::MAX); + assert!(l.as_str().starts_with("4294967295 pts") && l.len() <= 48, "{l:?}"); + } + + #[test] + fn card_lines() { + let t = |s: &str| two_lines(s, 15).as_str().to_owned(); + assert_eq!(t("Cryptopocalypse"), "Cryptopocalypse"); + assert_eq!(t("Michael Caine has died"), "Michael Caine\nhas died"); + assert_eq!(t("Amazon Ergo: A fast, cost-effective open-weights model"), "Amazon Ergo: A\nfast..."); + assert_eq!(t("Goals don't work. Rely on your values"), "Goals don't\nwork. Rely..."); + assert_eq!(t("Advent of Code 2026"), "Advent of Code\n2026"); + assert_eq!(t("Supercalifragilisticexpialidocious"), "Supercalifragil\nisticexpiali..."); + assert_eq!(t("A Supercalifragilisticexpialidocious b"), "A\nSupercalifra..."); + assert_eq!(t(""), ""); + assert_eq!(t(" x "), "x"); + assert_eq!(t("exactly fifteen"), "exactly fifteen"); + assert_eq!(t("exactly fifteen and then fifteen"), "exactly fifteen\nand then..."); + assert_eq!(t("exactly fifteen and then fiftee"), "exactly fifteen\nand then fiftee"); + } + + #[test] + fn card_lines_never_overflow() { + let words = ["a", "to", "the", "four", "fifty", "dozens", "fifteen", "Rust's", "eight888", "Kubernetes", "verylongword123", "evenlongerword12345"]; + let mut seed = 7u32; + for _ in 0..4000 { + let mut s = std::string::String::new(); + for _ in 0..(seed % 9 + 1) { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); + s.push_str(words[(seed >> 16) as usize % words.len()]); + s.push(' '); + } + let l = two_lines(&s, 15); + assert!(l.len() <= 39, "{l:?}"); + assert!(l.as_str().matches('\n').count() <= 1); + for line in l.as_str().split('\n') { + assert!(line.len() <= 15 && !line.is_empty(), "{s:?} -> {l:?}"); + } + } + } + + #[test] + fn line_cuts_at_characters() { + let mut l = Line::new(); + for _ in 0..30 { + l.push("\u{b7}"); + } + assert_eq!(l.len(), 48); + let mut l = Line::of(&"x".repeat(47)); + l.push("\u{b7}"); + assert_eq!(l.len(), 47); + assert!(l.as_str().is_ascii()); + } +} diff --git a/apps/tech-news/src/main.rs b/apps/tech-news/src/main.rs new file mode 100644 index 0000000..576d5d3 --- /dev/null +++ b/apps/tech-news/src/main.rs @@ -0,0 +1,206 @@ +//! tech-news: the Hacker News front page, through FMC Companion's `http.request` on the phone. +//! +//! - The menu app: the 8 top stories in a list the crown scrolls (`screen::menu`); a tap opens one (its whole title, +//! points, comments, age; the crown steps to the next, a tap or back returns), the Refresh pill asks the phone now. +//! BUTTON closes a story, else exits. +//! - The page next to the watch face (`app_features!(PAGE)`): "Top on HN" and three headlines (`screen::page`); a tap +//! shows the next three. Swiped away (PAUSE) it draws and asks nothing; back (RESUME) it asks again if the headlines +//! are older than 10 minutes. +//! - The widget card (`WIDGET`): the top story's points and its headline on two lines, written at start and whenever +//! the text changes. +//! +//! The phone is asked when the app starts and every 15 minutes while it is shown (`model.rs`); the last headlines are +//! kept in storage, so the list, the page and the card show at once without the phone. +#![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 format; +#[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 parse; +#[cfg_attr(not(any(target_os = "none", wp2_sim)), allow(dead_code))] +mod screen; + +#[cfg(not(any(target_os = "none", wp2_sim)))] +fn main() {} + +#[cfg(any(target_os = "none", wp2_sim))] +mod device { + use crate::format::Line; + use crate::model::{BLOB_MAX, Clock, Got, Model, wall_min}; + use crate::parse::N; + use crate::screen::{self, Hit, Ui}; + use cmf_wp2_app::{Api, BUTTON, CROWN, MSG_MAX, PAUSE, RESUME, TOUCH_DOWN, TOUCH_UP}; + use cmf_wp2_ui::haptic::{Motor, TICK}; + use core::ptr::addr_of_mut; + + cmf_wp2_app::entry!(main); + cmf_wp2_app::app_icon!(); + cmf_wp2_app::app_features!(cmf_wp2_app::WIDGET | cmf_wp2_app::PAGE); + + /// How often to look at the clock: the status line and the ages move. + const TICK_MS: u32 = 30_000; + /// Longest press that still counts as a tap. + const TAP_MS: u32 = 600; + + // the model holds a 2 KiB body buffer: off the 8 KiB stack + static mut MODEL: Model = Model::new(); + static mut BLOB: [u8; BLOB_MAX] = [0; BLOB_MAX]; + + fn clock(api: &Api) -> Clock { + api.time().map_or(Clock::new(0, 0), |t| { + let wall = wall_min(t.year as i32, t.month as u32, t.day as u32, t.hour as u32, t.minute as u32); + Clock::new(wall, t.utc_offset_min) + }) + } + + struct App { + api: &'static Api, + m: &'static mut Model, + ui: Ui, + on_page: bool, + /// The clock-dependent part of the last drawn screen. + shown: (Line, [u32; N]), + /// The card as last written. + card: Option<(Line, Line)>, + } + + impl App { + fn draw(&mut self) { + let c = clock(self.api); + self.ui.fit(self.m); + let mut s = self.api; + if self.on_page { + screen::page(&mut s, self.m, &self.ui, c); + } else { + screen::menu(&mut s, self.m, &self.ui, c); + } + self.api.show(); + self.shown = screen::clock_key(self.m, c); + } + + /// The clock moved the status line or an age. + fn ticked(&self) -> bool { + screen::clock_key(self.m, clock(self.api)) != self.shown + } + + /// Storage and the card, when they changed. + fn keep(&mut self) { + if self.m.take_dirty() { + let blob = unsafe { &mut *addr_of_mut!(BLOB) }; + let n = self.m.save(blob); + self.api.save(&blob[..n]); // on change: the app can end without notice + } + let card = self.m.widget(); + if self.card != Some(card) { + self.api.widget(card.0.as_str(), card.1.as_str()); // -22 on a loader without widgets + self.card = Some(card); + } + } + } + + fn main(api: &'static Api) -> i32 { + let m = unsafe { &mut *addr_of_mut!(MODEL) }; + let blob = unsafe { &mut *addr_of_mut!(BLOB) }; + let n = api.load(blob); + if n > 0 { + m.load(&blob[..n as usize]); + } + let on_page = api.on_page(); + if !on_page { + api.own_back(true); // BUTTON closes a story first; a no-op on a loader before ABI 1.3 + } + let mut app = App { api, m, ui: Ui::new(), on_page, shown: (Line::new(), [0; N]), card: None }; + let mut motor = Motor::new(api); + app.m.refresh(api.now()); + let mut paused = false; + let mut redraw = true; + let mut touch: Option<(i32, i32, u32)> = None; + let mut msg = [0u8; MSG_MAX]; + loop { + motor.update(); + if !paused { + // a request is two parts: both go now, unless the outbox is full (then again in 100 ms) + while let Some(req) = app.m.poll(api.now()) { + let r = api.send(&req); // -107 with no phone: the retry timer asks again + app.m.sent(r, api.now()); + if r < 0 { + break; + } + redraw = true; // "Updating..." + } + // an answer, a silent phone, the clock: the status line and the pill change too + if redraw || app.ticked() { + app.draw(); + } + } + redraw = false; + app.keep(); + let wait = if paused { u32::MAX } else { app.m.wait(api.now()).min(TICK_MS).min(motor.wait().unwrap_or(u32::MAX)) }; + let e = api.event(wait); + // every turn: the inbox holds 4 messages and an answer is about 14 + while let Some(r) = api.recv(&mut msg) { + if app.m.reply(r, api.now(), clock(api).wall) == Got::Changed { + redraw = true; + } + } + let Some(e) = e else { continue }; + match e.kind { + BUTTON if app.ui.detail.is_some() => { + app.ui.detail = None; + redraw = true; + } + BUTTON => { + motor.off(); + app.keep(); + return 0; + } + PAUSE => { + touch = None; // a swipe away from the page starts with a TOUCH_DOWN + motor.off(); + paused = true; + } + RESUME => { + paused = false; + app.m.resume(api.now(), clock(api).wall); + redraw = true; // the loader repainted the old frame + } + CROWN if !paused && !app.on_page => redraw |= app.ui.crown(app.m, e.delta), + // A tap acts on the finger's lift, at the place it went down (UP's x/y are unreliable). + TOUCH_DOWN if !paused => touch = Some((e.x as i32, e.y as i32, api.now())), + TOUCH_UP if !paused => { + let Some((x, y, at)) = touch.take() else { continue }; + if api.now().wrapping_sub(at) > TAP_MS { + continue; + } + let hit = if app.on_page { screen::page_hit(app.m) } else { screen::menu_hit(app.m, &app.ui, x, y) }; + match hit { + Hit::Open(i) => { + motor.play(TICK); + app.ui.detail = Some(i); + redraw = true; + } + Hit::Back => { + app.ui.detail = None; + redraw = true; + } + Hit::Next => { + app.ui.group = (app.ui.group + 1) % screen::groups(app.m); + redraw = true; + } + Hit::Refresh => { + if !app.m.busy() { + motor.play(TICK); + app.m.refresh(api.now()); + redraw = true; + } + } + Hit::Nothing => {} + } + } + _ => {} + } + } + } +} diff --git a/apps/tech-news/src/model.rs b/apps/tech-news/src/model.rs new file mode 100644 index 0000000..a3222d6 --- /dev/null +++ b/apps/tech-news/src/model.rs @@ -0,0 +1,407 @@ +//! Tech News' state, without `Api`: the stories, the `http.request` call that refreshes them through FMC Companion, +//! the cache blob and the widget card's text. +//! +//! One request at a time, each with a new id; replies for an older id are dropped by [`rpc::Call`]. The URL is 153 +//! bytes, past `http.get`'s 123, so it goes as `http.request` GET, a request of two parts sent back to back +//! ([`Model::poll`], [`Model::sent`]). After an answer the next one is due in [`PERIOD_MS`], or sooner while the phone +//! waits for the user's "allow" ([`ASK_AGAIN_MS`]) or after a failure ([`RETRY_FAILED_MS`]). A phone that doesn't +//! answer is asked again after 3 s, then 6, 12, 24, 48 and every [`LONGEST_MS`]. + +use crate::format::{self, Line}; +use crate::parse::{self, N, Story, TITLE_MAX}; +use companion_rpc as rpc; + +/// The front page's 8 top stories, only the fields shown, no highlighting (with it the answer is ~5 KB: TOO_LARGE). +pub const URL: &str = "https://hn.algolia.com/api/v1/search?tags=front_page&hitsPerPage=8&attributesToRetrieve=title,points,num_comments,created_at_i&attributesToHighlight=none"; + +/// A new request this often while the app or its page is shown. +pub const PERIOD_MS: u32 = 15 * 60_000; +/// While the phone waits for the user to allow the host. +pub const ASK_AGAIN_MS: u32 = 10_000; +/// After `DENIED`, `UNAVAILABLE`, an HTTP error or a body we can't read. +pub const RETRY_FAILED_MS: u32 = 60_000; +/// The longest wait between two tries while the phone is silent. +pub const LONGEST_MS: u32 = 60_000; +/// Before sending a part again that the full outbox refused. +pub const PART_RETRY_MS: u32 = 100; +/// Headlines fetched longer ago than this are marked as old. +pub const STALE_MIN: i32 = 60; +/// Coming back to the screen asks again when the headlines are this old. +pub const RESUME_MIN: i32 = 10; +/// The largest body `http.request` gives (`TOO_LARGE` above). +pub const BODY_MAX: usize = 2048; +/// Characters per widget card line that the stock card draws without wrapping (about 17 of its font fit; markets). +pub const WIDGET_LINE_MAX: usize = 15; + +/// Messages of the request: `method ‖ url_len ‖ url` in chunks of 121 bytes. +pub const PARTS: u8 = (2 + URL.len()).div_ceil(rpc::CHUNK_MAX) as u8; + +/// `api.send`'s "the outbox is full". +const EAGAIN: i32 = -11; + +/// How the phone answered last. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Status { + /// Not answered yet in this run. + Waiting, + Ok, + /// The phone asked the user to allow the host. + Ask, + /// The user said no. + Denied, + /// No network, a timeout, an HTTP error or a body we can't read. + Failed, +} + +/// What a message changed. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Got { + Nothing, + /// Redraw. + Changed, +} + +/// The body of the open request: its records may come in any order. +struct Body { + buf: [u8; BODY_MAX], + head: Option, + /// Bytes from 0 that some record covered (the end of the furthest chunk). + end: usize, + bad: bool, +} + +impl Body { + const fn new() -> Body { + Body { buf: [0; BODY_MAX], head: None, end: 0, bad: false } + } + + fn clear(&mut self) { + self.head = None; + self.end = 0; + self.bad = false; + } + + /// Record `index` of `total`: the head first, then the body in chunks of 121 bytes (each but the last full). + fn put(&mut self, index: u8, total: u8, record: &[u8]) { + if index == 0 { + self.head = rpc::HttpHead::decode(record); + self.bad |= self.head.is_none(); + return; + } + let at = (index as usize - 1) * rpc::RECORD_MAX; + let full = record.len() == rpc::RECORD_MAX; + let to = at + record.len(); + if (index + 1 < total && !full) || record.len() > rpc::RECORD_MAX || to > BODY_MAX { + self.bad = true; + return; + } + self.buf[at..to].copy_from_slice(record); + self.end = self.end.max(to); + } + + /// The whole body of a 200 answer. + fn ok(&self) -> Option<&[u8]> { + let h = self.head?; + let n = h.length as usize; + (!self.bad && h.code == 200 && n == self.end).then(|| &self.buf[..n]) + } +} + +pub struct Model { + pub stories: [Story; N], + pub count: usize, + /// Wall-clock minutes of the last answer with stories. + pub fetched: Option, + pub status: Status, + call: rpc::Call, + ids: u8, + /// The id of the open request. + id: u8, + /// The next part of the open request to send, and not before when. + part: u8, + part_at: u32, + /// The joined request, for [`rpc::http_request`]. + out: [u8; rpc::JOINED_MAX], + body: Body, + /// A `BAD_REQUEST` was asked again at once (a request the phone got only part of); the next waits. + bad_again: bool, + /// Something worth keeping changed since the last [`Model::save`]. + dirty: bool, +} + +/// Storage: magic, version, count, the fetch minute, then per story points, comments (`u32::MAX`: none), time, +/// title length and the title. +const MAGIC: &[u8; 2] = b"TN"; +const VERSION: u8 = 1; +const HEAD_BYTES: usize = 8; +const STORY_HEAD: usize = 13; +pub const BLOB_MAX: usize = HEAD_BYTES + N * (STORY_HEAD + TITLE_MAX); + +/// Days since 1970-01-01 of a civil date. +pub fn days(y: i32, m: u32, d: u32) -> i32 { + let y = if m <= 2 { y - 1 } else { y }; + let (era, yoe) = (y.div_euclid(400), y.rem_euclid(400)); + let doy = (153 * ((m as i32 + 9) % 12) + 2) / 5 + d as i32 - 1; + era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468 +} + +/// Wall-clock minutes since 1970. +pub fn wall_min(y: i32, m: u32, d: u32, hour: u32, minute: u32) -> i32 { + days(y, m, d) * 1440 + (hour * 60 + minute) as i32 +} + +/// The watch's clock as the screens need it: local minutes for "Updated 14:05", UTC minutes for a story's age. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Clock { + pub wall: i32, + pub utc: i32, +} + +impl Clock { + /// From local minutes and the zone's offset (`i16::MIN`: the phone never set one, taken as UTC). + pub fn new(wall: i32, offset_min: i16) -> Clock { + let off = if offset_min == i16::MIN { 0 } else { offset_min as i32 }; + Clock { wall, utc: wall - off } + } + + /// Minutes since a post at Unix second `t`. + pub fn age(&self, t: u32) -> i32 { + self.utc - (t / 60) as i32 + } +} + +fn reached(now: u32, at: u32) -> bool { + (now.wrapping_sub(at) as i32) >= 0 +} + +impl Model { + pub const fn new() -> Model { + Model { + stories: [Story::EMPTY; N], + count: 0, + fetched: None, + status: Status::Waiting, + call: rpc::Call::new(LONGEST_MS), + ids: 0, + id: 0, + part: u8::MAX, + part_at: 0, + out: [0; rpc::JOINED_MAX], + body: Body::new(), + bad_again: false, + dirty: false, + } + } + + pub fn stories(&self) -> &[Story] { + &self.stories[..self.count] + } + + /// Waiting for an answer. + pub fn running(&self) -> bool { + self.call.open() + } + + /// The phone left the last request unanswered. + pub fn silent(&self) -> bool { + self.call.silent() + } + + /// Ask at once, unless a request is open (start, the Refresh pill); a silent phone is asked again at once. + pub fn refresh(&mut self, now: u32) { + if !self.running() || self.silent() { + self.call.now(now); + } + } + + /// Waiting for a phone that answers: what the Refresh pill can't speed up. + pub fn busy(&self) -> bool { + self.running() && !self.silent() + } + + /// Back on screen after `PAUSE`: the open request again (its answer was refused while paused), or a new one when + /// the headlines are older than [`RESUME_MIN`]. + pub fn resume(&mut self, now: u32, wall: i32) { + if self.running() || self.fetched.is_none_or(|at| wall - at >= RESUME_MIN) { + self.call.now(now); + } + } + + /// The parts of the request. + fn parts(&mut self) -> Option> { + rpc::http_request(self.id, rpc::http::GET, URL, &[], &mut self.out) + } + + /// The next message to send now, if one is due: a part of a new request, or the next part of the open one. Tell + /// [`Model::sent`] what `api.send` said. + pub fn poll(&mut self, now: u32) -> Option { + if let Some(id) = self.call.due(now, &mut self.ids) { + self.id = id; + self.part = 0; + self.part_at = now; + self.body.clear(); + } + if !self.call.open() || self.part >= PARTS || !reached(now, self.part_at) { + return None; + } + let k = self.part; + self.parts()?.nth(k as usize) + } + + /// `api.send`'s result for the message [`Model::poll`] gave: the next part, the same again soon when the outbox + /// was full, or no more (no phone: the call's timer asks again). + pub fn sent(&mut self, r: i32, now: u32) { + if r >= 0 { + self.part = self.part.saturating_add(1); + } else if r == EAGAIN { + self.part_at = now.wrapping_add(PART_RETRY_MS); + } else { + self.part = u8::MAX; + } + } + + /// Ms until [`Model::poll`] has something to do. + pub fn wait(&self, now: u32) -> u32 { + let w = self.call.wait(now); + if self.call.open() && self.part < PARTS { + w.min((self.part_at.wrapping_sub(now) as i32).max(0) as u32) + } else { + w + } + } + + /// One message from the phone, at `now` ms and `wall` minutes. + pub fn reply(&mut self, m: &[u8], now: u32, wall: i32) -> Got { + match self.call.take(m) { + rpc::Got::Nothing => Got::Nothing, + rpc::Got::Status(s) => { + self.part = u8::MAX; + let again = match s { + rpc::ASK => { + self.status = Status::Ask; + ASK_AGAIN_MS + } + rpc::DENIED => { + self.status = Status::Denied; + RETRY_FAILED_MS + } + // the phone may hold the first part of a request whose second never came: once more, at once + rpc::BAD_REQUEST if !self.bad_again => { + self.bad_again = true; + self.status = Status::Failed; + rpc::RETRY_MS + } + _ => { + // UNAVAILABLE, TOO_LARGE, BAD_REQUEST again, an empty OK + self.status = Status::Failed; + RETRY_FAILED_MS + } + }; + self.call.after(now, again); + Got::Changed + } + rpc::Got::Record { index, total, record, last } => { + self.body.put(index, total, record); + if !last { + return Got::Nothing; + } + self.part = u8::MAX; + let again = if self.take_body(wall) { + self.status = Status::Ok; + self.bad_again = false; + PERIOD_MS + } else { + self.status = Status::Failed; + RETRY_FAILED_MS + }; + self.call.after(now, again); + Got::Changed + } + } + } + + /// The finished body into the stories; `false` if it had none. + fn take_body(&mut self, wall: i32) -> bool { + let Some(body) = self.body.ok() else { return false }; + let mut got = [Story::EMPTY; N]; + let n = parse::front_page(body, &mut got); + if n == 0 { + return false; + } + self.stories = got; + self.count = n; + self.fetched = Some(wall); + self.dirty = true; + true + } + + /// Whether to [`Model::save`] now: new stories since the last time; one NAND write per answer. + pub fn take_dirty(&mut self) -> bool { + core::mem::replace(&mut self.dirty, false) + } + + /// The cache blob into `out`; its length. + pub fn save(&self, out: &mut [u8; BLOB_MAX]) -> usize { + out[..2].copy_from_slice(MAGIC); + out[2] = VERSION; + out[3] = self.count as u8; + out[4..8].copy_from_slice(&self.fetched.unwrap_or(i32::MIN).to_le_bytes()); + let mut at = HEAD_BYTES; + for s in self.stories() { + let t = s.title().as_bytes(); + out[at..at + 4].copy_from_slice(&s.points.to_le_bytes()); + out[at + 4..at + 8].copy_from_slice(&s.comments.unwrap_or(u32::MAX).to_le_bytes()); + out[at + 8..at + 12].copy_from_slice(&s.time.to_le_bytes()); + out[at + 12] = t.len() as u8; + out[at + STORY_HEAD..at + STORY_HEAD + t.len()].copy_from_slice(t); + at += STORY_HEAD + t.len(); + } + at + } + + /// A blob of [`Model::save`]; anything else leaves the model as it is. `true` if it loaded. + pub fn load(&mut self, b: &[u8]) -> bool { + if b.len() < HEAD_BYTES || b.len() > BLOB_MAX || &b[..2] != MAGIC || b[2] != VERSION || b[3] as usize > N { + return false; + } + let le4 = |a: usize| u32::from_le_bytes([b[a], b[a + 1], b[a + 2], b[a + 3]]); + let count = b[3] as usize; + let fetched = le4(4) as i32; + let mut stories = [Story::EMPTY; N]; + let mut at = HEAD_BYTES; + for s in stories.iter_mut().take(count) { + let Some(&len) = b.get(at + 12) else { return false }; + let Some(raw) = b.get(at + STORY_HEAD..at + STORY_HEAD + len as usize) else { return false }; + let comments = le4(at + 4); + let comments = (comments != u32::MAX).then_some(comments); + let Some(story) = Story::with_raw_title(raw, le4(at), comments, le4(at + 8)) else { return false }; + *s = story; + at += STORY_HEAD + len as usize; + } + if at != b.len() || (count > 0) == (fetched == i32::MIN) { + return false; + } + self.stories = stories; + self.count = count; + self.fetched = (fetched != i32::MIN).then_some(fetched); + true + } + + /// The widget card: title (≤ 23 bytes) and value (≤ 39 bytes, two lines), e.g. "HN 780 pts" and + /// "Amazon Ergo: A\nfast...". Every line stays within [`WIDGET_LINE_MAX`] characters. + pub fn widget(&self) -> (Line, Line) { + let Some(top) = self.stories().first() else { + return (Line::of("Top on HN"), Line::of("No news yet\nOpen to load")); + }; + let mut title = Line::of("HN "); + title.push(format::points(top.points, true).as_str()); + if title.len() > WIDGET_LINE_MAX { + title = Line::of("Top on HN"); + } + (title, format::two_lines(top.title(), WIDGET_LINE_MAX)) + } +} + +#[cfg(test)] +#[path = "model_tests.rs"] +mod tests; diff --git a/apps/tech-news/src/model_tests.rs b/apps/tech-news/src/model_tests.rs new file mode 100644 index 0000000..73db90d --- /dev/null +++ b/apps/tech-news/src/model_tests.rs @@ -0,0 +1,444 @@ +extern crate std; + +use super::*; +use std::vec::Vec; + +const FRONT: &[u8] = include_bytes!("fixtures/front.json"); +const WALL: i32 = 1440 * 20_000 + 14 * 60 + 5; + +/// `R1A id status index total record`. +fn msg(id: u8, status: u8, index: u8, total: u8, record: &[u8]) -> Vec { + let mut m = Vec::from(&b"R1A"[..]); + m.extend_from_slice(&[id, status, index, total]); + m.extend_from_slice(record); + m +} + +/// An `http.request` answer as the phone sends it: the head, then the body in 121-byte chunks. +fn answer(id: u8, code: u16, body: &[u8]) -> Vec> { + let chunks: Vec<&[u8]> = body.chunks(rpc::RECORD_MAX).collect(); + let total = 1 + chunks.len() as u8; + let mut head = Vec::from(code.to_le_bytes()); + head.extend_from_slice(&(body.len() as u16).to_le_bytes()); + let mut out = std::vec![msg(id, rpc::OK, 0, total, &head)]; + for (i, c) in chunks.iter().enumerate() { + out.push(msg(id, rpc::OK, 1 + i as u8, total, c)); + } + out +} + +fn feed(m: &mut Model, msgs: &[Vec], now: u32) -> Got { + let mut got = Got::Nothing; + for x in msgs { + if m.reply(x, now, WALL) == Got::Changed { + got = Got::Changed; + } + } + got +} + +/// Sends what is due at `now` as the main loop does (every send succeeding); the messages and the request's id. +fn send_all(m: &mut Model, now: u32) -> (Vec, Option) { + let mut out = Vec::new(); + while let Some(q) = m.poll(now) { + m.sent(0, now); + out.push(q); + assert!(out.len() <= 9); + } + let id = out.first().map(|q| q.as_bytes()[3]); + (out, id) +} + +/// The joined payload of a multi-part request's messages. +fn joined(msgs: &[rpc::Msg]) -> Vec { + let mut v = Vec::new(); + for (k, q) in msgs.iter().enumerate() { + let b = q.as_bytes(); + assert_eq!(&b[..3], b"R1Q"); + assert_eq!(b[4], rpc::method::HTTP_REQUEST); + assert_eq!((b[5], b[6]), (k as u8, msgs.len() as u8)); + assert_eq!(b[3], msgs[0].as_bytes()[3], "one id for every part"); + v.extend_from_slice(&b[7..]); + } + v +} + +#[test] +fn the_request_is_an_http_get_in_two_parts() { + assert_eq!(URL.len(), 153); + assert!(URL.len() <= 255 && URL.len() > 123, "too long for http.get, fits http.request"); + assert!(rpc::http_get(1, URL).is_none()); + assert!(URL.contains("attributesToHighlight=none") && URL.contains("hitsPerPage=8")); + assert_eq!(PARTS, 2); + let mut m = Model::new(); + m.refresh(0); + let (msgs, id) = send_all(&mut m, 0); + assert_eq!(msgs.len(), 2); + assert_eq!(id, Some(1)); + let p = joined(&msgs); + assert_eq!(p[0], rpc::http::GET); + assert_eq!(p[1] as usize, URL.len()); + assert_eq!(&p[2..], URL.as_bytes()); // no body + assert_eq!(msgs[0].as_bytes().len(), rpc::MSG_MAX); + // the same bytes as the crate's encoder + let mut out = [0; rpc::JOINED_MAX]; + let want: Vec> = + rpc::http_request(1, rpc::http::GET, URL, &[], &mut out).unwrap().map(|q| q.as_bytes().to_vec()).collect(); + assert_eq!(msgs.iter().map(|q| q.as_bytes().to_vec()).collect::>(), want); +} + +#[test] +fn a_full_outbox_sends_the_part_again_and_no_phone_stops() { + let mut m = Model::new(); + m.refresh(0); + let a = m.poll(0).unwrap(); + m.sent(0, 0); + let b = m.poll(0).unwrap(); + m.sent(-11, 0); + assert!(m.poll(50).is_none()); + assert_eq!(m.wait(50), PART_RETRY_MS - 50); + let b2 = m.poll(PART_RETRY_MS).unwrap(); + assert_eq!(b.as_bytes(), b2.as_bytes()); + assert_ne!(a.as_bytes(), b.as_bytes()); + m.sent(0, PART_RETRY_MS); + assert!(m.poll(PART_RETRY_MS).is_none()); + // -107: no more parts; the call's timer asks again, from part 0 with a new id + let mut m = Model::new(); + m.refresh(0); + m.poll(0).unwrap(); + m.sent(-107, 0); + assert!(m.poll(10).is_none()); + assert_eq!(m.wait(10), rpc::RETRY_MS - 10); + let (msgs, id) = send_all(&mut m, rpc::RETRY_MS); + assert_eq!((msgs.len(), id), (2, Some(2))); + assert!(m.silent()); +} + +#[test] +fn an_answer_fills_the_stories() { + let mut m = Model::new(); + assert!(m.poll(0).is_none()); // nothing until asked + m.refresh(0); + let (_, id) = send_all(&mut m, 0); + let id = id.unwrap(); + assert!(m.running() && m.busy()); + let msgs = answer(id, 200, FRONT); + assert!(msgs.len() > 10); + // records in any order; nothing to redraw until the last one + for x in msgs.iter().rev().skip(1) { + assert_eq!(m.reply(x, 10, WALL), Got::Nothing); + } + assert_eq!(m.reply(&msgs[msgs.len() - 1], 10, WALL), Got::Changed); + assert_eq!(m.count, 8); + assert_eq!(m.stories[0].title(), "Amazon Ergo: A fast, cost-effective open-weights model"); + assert_eq!((m.stories[0].points, m.stories[0].comments), (780, Some(335))); + assert_eq!(m.fetched, Some(WALL)); + assert_eq!(m.status, Status::Ok); + assert!(!m.running()); + assert!(m.take_dirty() && !m.take_dirty()); // one write per answer + // the next one in 15 minutes + assert_eq!(m.wait(10), PERIOD_MS); + assert!(m.poll(10 + PERIOD_MS - 1).is_none()); + let (msgs, id2) = send_all(&mut m, 10 + PERIOD_MS); + assert_eq!((msgs.len(), id2), (2, Some(id + 1))); +} + +#[test] +fn replies_for_an_old_id_are_dropped() { + let mut m = Model::new(); + m.refresh(0); + let (_, first) = send_all(&mut m, 0); + // silent: asked again with a new id after 3 s + let (_, again) = send_all(&mut m, rpc::RETRY_MS); + assert_ne!(first, again); + assert!(m.silent() && !m.busy()); + assert_eq!(feed(&mut m, &answer(first.unwrap(), 200, FRONT), 3_100), Got::Nothing); + assert_eq!(m.count, 0); + assert_eq!(feed(&mut m, &answer(again.unwrap(), 200, FRONT), 3_200), Got::Changed); + assert!(m.count == 8 && !m.silent()); + // other prefixes and garbage are nothing + assert_eq!(m.reply(b"hello", 0, WALL), Got::Nothing); + assert_eq!(m.reply(b"R1A", 0, WALL), Got::Nothing); + assert_eq!(m.reply(&msg(again.unwrap(), rpc::OK, 0, 2, &[200, 0, 5, 0]), 0, WALL), Got::Nothing); // answered +} + +#[test] +fn silence_backs_off() { + let mut m = Model::new(); + m.refresh(0); + let mut t = 0; + send_all(&mut m, t); + let mut waits = Vec::new(); + for _ in 0..7 { + let w = m.wait(t); + waits.push(w); + t += w; + assert_eq!(send_all(&mut m, t).0.len(), 2); + } + assert_eq!(waits, [3_000, 6_000, 12_000, 24_000, 48_000, 60_000, 60_000]); + assert!(m.silent() && m.running()); + // the Refresh pill asks a silent phone at once, with a fresh back-off + m.refresh(t + 10); + assert_eq!(send_all(&mut m, t + 10).0.len(), 2); + assert_eq!(m.wait(t + 10), rpc::RETRY_MS); +} + +#[test] +fn ask_then_allowed() { + let mut m = Model::new(); + m.refresh(0); + let (_, id) = send_all(&mut m, 0); + assert_eq!(feed(&mut m, &[msg(id.unwrap(), rpc::ASK, 0, 0, &[])], 5), Got::Changed); + assert_eq!(m.status, Status::Ask); + assert!(!m.running()); + assert_eq!(m.wait(5), ASK_AGAIN_MS); + let (_, id) = send_all(&mut m, 5 + ASK_AGAIN_MS); + assert_eq!(m.status, Status::Ask); // until the phone says otherwise + feed(&mut m, &answer(id.unwrap(), 200, FRONT), 6 + ASK_AGAIN_MS); + assert_eq!(m.status, Status::Ok); + assert_eq!(m.wait(6 + ASK_AGAIN_MS), PERIOD_MS); +} + +#[test] +fn denied_and_failures() { + let mut m = Model::new(); + m.refresh(0); + let (_, id) = send_all(&mut m, 0); + feed(&mut m, &[msg(id.unwrap(), rpc::DENIED, 0, 0, &[])], 0); + assert_eq!(m.status, Status::Denied); + assert_eq!(m.wait(0), RETRY_FAILED_MS); + + // an HTTP error, a body that isn't the answer, TOO_LARGE, UNAVAILABLE: failed, again in a minute + let mut t = 0; + let fails: [Vec>; 5] = [ + answer(0, 429, b"{}"), + answer(0, 200, b""), + answer(0, 200, br#"{"hits":[]}"#), + std::vec![msg(0, rpc::TOO_LARGE, 0, 0, &[])], + std::vec![msg(0, rpc::UNAVAILABLE, 0, 0, &[])], + ]; + for f in fails { + let mut m = Model::new(); + m.refresh(t); + let (_, id) = send_all(&mut m, t); + let f: Vec> = f + .into_iter() + .map(|mut x| { + x[3] = id.unwrap(); + x + }) + .collect(); + assert_eq!(feed(&mut m, &f, t), Got::Changed); + assert_eq!(m.status, Status::Failed); + assert_eq!(m.count, 0); + assert_eq!(m.wait(t), RETRY_FAILED_MS); + t += 1; + } + + // a failure keeps the stories there are + let mut m = Model::new(); + m.refresh(0); + let (_, id) = send_all(&mut m, 0); + feed(&mut m, &answer(id.unwrap(), 200, FRONT), 0); + m.refresh(1); // not running: asks at once + let (_, id) = send_all(&mut m, 1); + feed(&mut m, &[msg(id.unwrap(), rpc::UNAVAILABLE, 0, 0, &[])], 1); + assert_eq!((m.status, m.count, m.fetched), (Status::Failed, 8, Some(WALL))); +} + +#[test] +fn bad_request_is_asked_again_once_at_once() { + let mut m = Model::new(); + m.refresh(0); + let (_, id) = send_all(&mut m, 0); + feed(&mut m, &[msg(id.unwrap(), rpc::BAD_REQUEST, 0, 0, &[])], 0); + assert_eq!(m.wait(0), rpc::RETRY_MS); + let (_, id) = send_all(&mut m, rpc::RETRY_MS); + feed(&mut m, &[msg(id.unwrap(), rpc::BAD_REQUEST, 0, 0, &[])], rpc::RETRY_MS); + assert_eq!(m.wait(rpc::RETRY_MS), RETRY_FAILED_MS); + // an answer resets it + let t = rpc::RETRY_MS + RETRY_FAILED_MS; + let (_, id) = send_all(&mut m, t); + feed(&mut m, &answer(id.unwrap(), 200, FRONT), t); + m.refresh(t); + let (_, id) = send_all(&mut m, t); + feed(&mut m, &[msg(id.unwrap(), rpc::BAD_REQUEST, 0, 0, &[])], t); + assert_eq!(m.wait(t), rpc::RETRY_MS); +} + +#[test] +fn a_cut_or_odd_body_is_not_taken() { + // a head that claims more than came + let mut m = Model::new(); + m.refresh(0); + let (_, id) = send_all(&mut m, 0); + let mut msgs = answer(id.unwrap(), 200, FRONT); + msgs[0][9] = msgs[0][9].wrapping_add(1); // the length's low byte + feed(&mut m, &msgs, 0); + assert_eq!((m.count, m.status), (0, Status::Failed)); + // a short chunk in the middle + m.refresh(1); + let (_, id) = send_all(&mut m, 1); + let mut msgs = answer(id.unwrap(), 200, FRONT); + msgs[2].pop(); + feed(&mut m, &msgs, 1); + assert_eq!(m.count, 0); + // a body over 2048 bytes in pieces past the buffer + m.refresh(2); + let (_, id) = send_all(&mut m, 2); + feed(&mut m, &answer(id.unwrap(), 200, &[b' '; 2100]), 2); + assert_eq!(m.count, 0); + // a bad head + m.refresh(3); + let (_, id) = send_all(&mut m, 3); + feed(&mut m, &[msg(id.unwrap(), rpc::OK, 0, 1, &[200])], 3); + assert_eq!((m.count, m.status), (0, Status::Failed)); +} + +#[test] +fn resume_asks_again_when_old_or_open() { + let mut m = Model::new(); + m.refresh(0); + let (_, id) = send_all(&mut m, 0); + feed(&mut m, &answer(id.unwrap(), 200, FRONT), 0); + let now = 1000; + m.resume(now, WALL + 1); + assert!(m.poll(now).is_none()); + m.resume(now, WALL + RESUME_MIN); + assert!(m.poll(now).is_some()); + // paused with a request open: asked again at once, not counted as silence + let mut m = Model::new(); + m.refresh(0); + let (_, first) = send_all(&mut m, 0); + m.resume(500, WALL); + let (_, again) = send_all(&mut m, 500); + assert!(!m.silent()); + assert_ne!(first, again); + // nothing cached: asked at once + let mut m = Model::new(); + m.resume(7, WALL); + assert!(m.poll(7).is_some()); +} + +#[test] +fn refresh_doesnt_restart_an_open_request() { + let mut m = Model::new(); + m.refresh(0); + send_all(&mut m, 0); + assert!(m.busy()); + m.refresh(100); + assert!(m.poll(100).is_none()); +} + +fn loaded() -> Model { + let mut m = Model::new(); + m.refresh(0); + let (_, id) = send_all(&mut m, 0); + feed(&mut m, &answer(id.unwrap(), 200, FRONT), 0); + m +} + +#[test] +fn storage_round_trip() { + let mut m = loaded(); + m.stories[2].comments = None; + m.stories[3] = Story::new(&"long words ".repeat(20), u32::MAX, Some(u32::MAX - 1), u32::MAX); + let mut blob = [0u8; BLOB_MAX]; + let n = m.save(&mut blob); + assert!(n <= BLOB_MAX && BLOB_MAX <= cmf_wp2_app::STORE_MAX); + let mut k = Model::new(); + assert!(k.load(&blob[..n])); + assert_eq!(k.stories, m.stories); + assert_eq!((k.count, k.fetched), (8, Some(WALL))); + // the largest blob there can be + for s in m.stories.iter_mut() { + *s = Story::new(&"x".repeat(200), 1, Some(2), 3); + assert_eq!(s.title().len(), parse::TITLE_MAX); + } + assert_eq!(m.save(&mut blob), BLOB_MAX); + assert!(k.load(&blob)); + // nothing yet + let e = Model::new(); + let n = e.save(&mut blob); + assert_eq!(n, 8); + let mut k = loaded(); + assert!(k.load(&blob[..n])); + assert_eq!((k.count, k.fetched), (0, None)); +} + +#[test] +fn a_bad_blob_loads_nothing() { + let m = loaded(); + let mut blob = [0u8; BLOB_MAX]; + let n = m.save(&mut blob); + let bad = |f: &dyn Fn(&mut Vec)| { + let mut b = blob[..n].to_vec(); + f(&mut b); + let mut k = Model::new(); + assert!(!k.load(&b), "{b:?}"); + assert_eq!((k.count, k.fetched), (0, None)); + }; + bad(&|b| b[0] = b'X'); + bad(&|b| b[2] = 9); + bad(&|b| b[3] = 9); + bad(&|b| b[3] = 7); // fewer stories than the bytes hold + bad(&|b| b[4..8].copy_from_slice(&i32::MIN.to_le_bytes())); // stories without a time + bad(&|b| b[8 + 12] = 0); // an empty title + bad(&|b| b[8 + 12] = 200); // a title past the end + bad(&|b| b[8 + 13] = 0xC3); // not ASCII + bad(&|b| b[8 + 13] = b'\n'); + bad(&|b| { + b.pop(); + }); + bad(&|b| b.push(0)); + bad(&|b| b.truncate(5)); + bad(&|b| b.clear()); + let mut k = Model::new(); + assert!(!k.load(&[0; BLOB_MAX + 1])); + // a good blob still loads after all that + assert!(k.load(&blob[..n])); +} + +#[test] +fn widget_text_fits() { + let m = Model::new(); + let (t, v) = m.widget(); + assert_eq!((t.as_str(), v.as_str()), ("Top on HN", "No news yet\nOpen to load")); + let mut m = loaded(); + let (t, v) = m.widget(); + assert_eq!(t.as_str(), "HN 780 pts"); + assert_eq!(v.as_str(), "Amazon Ergo: A\nfast..."); + m.stories[0] = Story::new("Cryptopocalypse", 1, None, 0); + assert_eq!(m.widget().0.as_str(), "HN 1 pt"); + assert_eq!(m.widget().1.as_str(), "Cryptopocalypse"); + m.stories[0] = Story::new("x", u32::MAX, None, 0); + assert_eq!(m.widget().0.as_str(), "Top on HN"); // "HN 4294967295 pts" is too wide + // every headline of the fixture, and odd ones, on two lines of at most 15 + let mut odd: Vec = m.stories().to_vec(); + for t in ["a", "Supercalifragilisticexpialidocious and more", "I I I I I I I I I I I I I I I I I I I I", "-- -- -- -- -- -- -- --"] { + odd.push(Story::new(t, 99_999, None, 0)); + } + odd.push(Story::new(&"w".repeat(90), 5, None, 0)); + for s in odd.iter().chain(loaded().stories()) { + m.stories[0] = *s; + let (t, v) = m.widget(); + assert!(t.len() <= 23 && v.len() <= 39, "{t:?} {v:?}"); + assert!(v.as_str().matches('\n').count() <= 1); + for line in core::iter::once(t.as_str()).chain(v.as_str().split('\n')) { + assert!(line.len() <= WIDGET_LINE_MAX && line.is_ascii(), "{line:?} is wider than the card"); + } + } +} + +#[test] +fn clock_and_ages() { + assert_eq!(days(1970, 1, 1), 0); + assert_eq!(wall_min(2026, 12, 1, 14, 5) % 1440, 14 * 60 + 5); + // the fixture's first story, 1796147550 = 2026-12-01 17:52:30 UTC, seen at 22:22 in UTC+2 + let c = Clock::new(wall_min(2026, 12, 1, 22, 22), 120); + assert_eq!(c.age(1_796_147_550), 150); + assert_eq!(format::age(c.age(1_796_147_550)).as_str(), "2h"); + // no zone from the phone: taken as UTC + let c = Clock::new(wall_min(2026, 12, 1, 18, 0), i16::MIN); + assert_eq!(c.age(1_796_147_550), 8); +} diff --git a/apps/tech-news/src/parse.rs b/apps/tech-news/src/parse.rs new file mode 100644 index 0000000..31526fd --- /dev/null +++ b/apps/tech-news/src/parse.rs @@ -0,0 +1,560 @@ +//! The Hacker News front page out of Algolia's search answer, without a heap, floats or a JSON library: a cursor walks +//! the top object to `"hits"` and reads each hit's `title`, `points`, `num_comments` and `created_at_i`, skipping +//! everything else whatever its order. Every byte is untrusted: nothing here indexes past a slice, recurses or panics, +//! and a hit is only taken once its closing `}` has come, so a cut body gives the whole hits before the cut and nothing +//! half-read. +//! +//! Titles are folded to ASCII on the way in ([`ascii`]): the watch's widget font has ASCII and Cyrillic, the canvas +//! font ASCII and Latin-1, so typographic quotes and dashes become plain ones, accented Latin letters their base +//! letter, and anything else (emoji, CJK, ...) is dropped rather than drawn as a box. + +/// Stories kept: the URL asks for this many. +pub const N: usize = 8; +/// Bytes of a title kept; a longer one is cut at a word and ends in "...". HN titles are at most 80 characters. +pub const TITLE_MAX: usize = 90; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Story { + title: [u8; TITLE_MAX], + len: u8, + pub points: u32, + /// `None` when the answer had no count (`null`). + pub comments: Option, + /// Unix seconds (UTC) of the post. + pub time: u32, +} + +impl Story { + pub const EMPTY: Story = Story { title: [0; TITLE_MAX], len: 0, points: 0, comments: None, time: 0 }; + + /// A story with this title (folded to ASCII like a parsed one). + #[cfg(test)] + pub fn new(title: &str, points: u32, comments: Option, time: u32) -> Story { + let mut t = Title::new(); + for ch in title.chars() { + t.push(ch); + } + let mut s = Story { points, comments, time, ..Story::EMPTY }; + s.set_title(&mut t); + s + } + + /// From stored bytes: `None` unless they are ASCII text of at most [`TITLE_MAX`] bytes, not empty. + pub fn with_raw_title(raw: &[u8], points: u32, comments: Option, time: u32) -> Option { + if raw.is_empty() || raw.len() > TITLE_MAX || !raw.iter().all(|&c| (b' '..=b'~').contains(&c)) { + return None; + } + let mut s = Story { points, comments, time, ..Story::EMPTY }; + s.title[..raw.len()].copy_from_slice(raw); + s.len = raw.len() as u8; + Some(s) + } + + pub fn title(&self) -> &str { + core::str::from_utf8(&self.title[..self.len as usize]).unwrap_or("") + } + + fn set_title(&mut self, t: &mut Title) { + let b = t.finish(); + self.title[..b.len()].copy_from_slice(b); + self.len = b.len() as u8; + } +} + +// --------------------------------------------------------------------------------------------------------------- +// ASCII + +const PRINTABLE: &str = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; +/// U+00C0..U+00FF to a base letter; `*` = see [`ascii`]. +const LATIN1: &[u8; 64] = b"AAAAAA*CEEEEIIIIDNOOOOOxOUUUUY**aaaaaa*ceeeeiiiidnooooo/ouuuuy*y"; +/// U+0100..U+017F (Latin Extended-A) to a base letter; `*` = see [`ascii`]. +const EXT_A: &[u8; 128] = b"AaAaAaCcCcCcCcDdDdEeEeEeEeEeGgGgGgGgHhHhIiIiIiIiIi**JjKkkLlLlLlLlLlNnNnNnnNnOoOoOo**RrRrRrSsSsSsSsTtTtTtUuUuUuUuUuUuWwYyYZzZzZzs"; + +/// What `ch` is written as on the watch: itself if ASCII, its plain look-alike, its base letter, or nothing. +pub fn ascii(ch: char) -> &'static str { + let c = ch as u32; + let table = |t: &'static [u8], i: usize| -> &'static str { + let b = t[i]; + if b == b'*' { "" } else { &PRINTABLE[(b - b' ') as usize..(b - b' ' + 1) as usize] } + }; + match c { + 0x20..=0x7E => &PRINTABLE[(c - 0x20) as usize..(c - 0x1F) as usize], + 0x09 | 0x0A | 0x0D | 0xA0 => " ", + 0xAB | 0xBB => "\"", + 0xB4 => "'", + 0xB7 => "-", + 0xC6 => "AE", + 0xE6 => "ae", + 0xDE => "Th", + 0xFE => "th", + 0xDF => "ss", + 0xC0..=0xFF => table(LATIN1, (c - 0xC0) as usize), + 0x132 => "IJ", + 0x133 => "ij", + 0x152 => "OE", + 0x153 => "oe", + 0x100..=0x17F => table(EXT_A, (c - 0x100) as usize), + 0x2000..=0x200A | 0x202F | 0x205F | 0x3000 => " ", + 0x2010..=0x2015 | 0x2212 | 0x2022 | 0x2043 => "-", + 0x2018..=0x201B | 0x2032 | 0x2039 | 0x203A => "'", + 0x201C..=0x201F | 0x2033 => "\"", + 0x2026 => "...", + 0x2044 | 0x2215 => "/", + 0x2122 => "TM", + 0x2190 => "<-", + 0x2192 => "->", + 0x2194 => "<->", + 0x21D2 => "=>", + 0x2248 => "~", + 0x2260 => "!=", + 0x2264 => "<=", + 0x2265 => ">=", + _ => "", + } +} + +/// A title being built: ASCII, spaces collapsed, none at the start; what doesn't fit is noted. +struct Title { + buf: [u8; TITLE_MAX], + len: usize, + over: bool, +} + +impl Title { + const fn new() -> Title { + Title { buf: [0; TITLE_MAX], len: 0, over: false } + } + + fn push(&mut self, ch: char) { + for b in ascii(ch).bytes() { + if b == b' ' && (self.len == 0 || self.buf[self.len - 1] == b' ') { + continue; + } + if self.len == TITLE_MAX { + self.over |= b != b' '; + return; + } + self.buf[self.len] = b; + self.len += 1; + } + } + + /// The title without trailing spaces; a cut one ends in "..." after its last whole word (if that isn't too far + /// back). + fn finish(&mut self) -> &[u8] { + while self.len > 0 && self.buf[self.len - 1] == b' ' { + self.len -= 1; + } + if self.over { + let room = TITLE_MAX - 3; + let mut end = room; + if self.buf[room] != b' ' { + if let Some(i) = self.buf[..room].iter().rposition(|&c| c == b' ').filter(|&i| i >= TITLE_MAX / 2) { + end = i; + } + } + while end > 0 && matches!(self.buf[end - 1], b' ' | b',' | b':' | b';' | b'-') { + end -= 1; + } + self.buf[end..end + 3].copy_from_slice(b"..."); + self.len = end + 3; + self.over = false; + } + &self.buf[..self.len] + } +} + +// --------------------------------------------------------------------------------------------------------------- +// JSON + +struct Cur<'a> { + b: &'a [u8], + i: usize, +} + +impl<'a> Cur<'a> { + fn ws(&mut self) { + while self.b.get(self.i).is_some_and(|c| c.is_ascii_whitespace()) { + self.i += 1; + } + } + + fn peek(&mut self) -> Option { + self.ws(); + self.b.get(self.i).copied() + } + + fn eat(&mut self, c: u8) -> bool { + if self.peek() == Some(c) { + self.i += 1; + true + } else { + false + } + } + + /// The raw bytes of a string, between its quotes (escapes left in); the cursor after the closing quote. + fn string(&mut self) -> Option<&'a [u8]> { + if !self.eat(b'"') { + return None; + } + let start = self.i; + loop { + match *self.b.get(self.i)? { + b'\\' => self.i += 2, + b'"' => { + let s = self.b.get(start..self.i)?; + self.i += 1; + return Some(s); + } + _ => self.i += 1, + } + } + } + + /// An unsigned integer that fits a `u32` (a larger one is clamped); `None` for `null`, a sign, a fraction, an + /// exponent or a number the body cuts off. The cursor goes past the value either way, if it can. + fn uint(&mut self) -> Option> { + match self.peek()? { + b'0'..=b'9' => { + let mut v: u64 = 0; + while let Some(c) = self.b.get(self.i).filter(|c| c.is_ascii_digit()) { + v = (v * 10 + (c - b'0') as u64).min(u32::MAX as u64); + self.i += 1; + } + match self.b.get(self.i)? { + b',' | b'}' | b']' | b' ' | b'\t' | b'\r' | b'\n' => Some(Some(v as u32)), + _ => { + self.skip()?; + Some(None) + } + } + } + _ => { + self.skip()?; + Some(None) + } + } + } + + /// Past one value of any kind; `None` if the body ends inside it. + fn skip(&mut self) -> Option<()> { + match self.peek()? { + b'"' => self.string().map(|_| ()), + b'{' | b'[' => { + let mut depth = 0usize; + loop { + match *self.b.get(self.i)? { + b'"' => { + self.string()?; + continue; + } + b'{' | b'[' => depth += 1, + b'}' | b']' => { + depth -= 1; + if depth == 0 { + self.i += 1; + return Some(()); + } + } + _ => {} + } + self.i += 1; + } + } + _ => { + // a number or a literal: up to a delimiter, which must be there + while !matches!(*self.b.get(self.i)?, b',' | b'}' | b']' | b' ' | b'\t' | b'\r' | b'\n') { + self.i += 1; + } + Some(()) + } + } + } +} + +/// One UTF-8 character at the start of `b` and its length; a broken sequence is one byte of nothing. +fn utf8(b: &[u8]) -> (Option, usize) { + let n = match b.first() { + None => return (None, 0), + Some(0x00..=0x7F) => 1, + Some(0xC2..=0xDF) => 2, + Some(0xE0..=0xEF) => 3, + Some(0xF0..=0xF4) => 4, + Some(_) => return (None, 1), + }; + match b.get(..n).and_then(|s| core::str::from_utf8(s).ok()).and_then(|s| s.chars().next()) { + Some(ch) => (Some(ch), n), + None => (None, 1), + } +} + +fn hex4(b: &[u8]) -> Option { + let s = core::str::from_utf8(b.get(..4)?).ok()?; + if !s.bytes().all(|c| c.is_ascii_hexdigit()) { + return None; + } + u32::from_str_radix(s, 16).ok() +} + +/// The characters of a JSON string's raw bytes, escapes resolved (`🚀` pairs too), into `t`. +fn unescape(raw: &[u8], t: &mut Title) { + let mut i = 0; + while i < raw.len() { + if raw[i] != b'\\' { + let (ch, n) = utf8(&raw[i..]); + if let Some(ch) = ch { + t.push(ch); + } + i += n.max(1); + continue; + } + let Some(&e) = raw.get(i + 1) else { return }; + i += 2; + let ch = match e { + b'"' => '"', + b'\\' => '\\', + b'/' => '/', + b'b' | b'f' => continue, + b'n' | b'r' | b't' => ' ', + b'u' => { + let Some(hi) = hex4(&raw[i..]) else { continue }; + i += 4; + let cp = if (0xD800..0xDC00).contains(&hi) { + match (raw.get(i..i + 2), hex4(raw.get(i + 2..).unwrap_or(&[]))) { + (Some(b"\\u"), Some(lo)) if (0xDC00..0xE000).contains(&lo) => { + i += 6; + 0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00) + } + _ => continue, + } + } else { + hi + }; + match char::from_u32(cp) { + Some(ch) => ch, + None => continue, + } + } + _ => continue, + }; + t.push(ch); + } +} + +/// One hit object at the cursor (its `{` next): a story, or `None` for one without a title. `Err` if the body ends +/// inside it. +fn hit(c: &mut Cur) -> Result, ()> { + if !c.eat(b'{') { + c.skip().ok_or(())?; + return Ok(None); + } + let mut s = Story::EMPTY; + let mut title = Title::new(); + let mut has_title = false; + if c.eat(b'}') { + return Ok(None); + } + loop { + let key = c.string().ok_or(())?; + if !c.eat(b':') { + return Err(()); + } + match key { + b"title" => { + if c.peek() == Some(b'"') { + unescape(c.string().ok_or(())?, &mut title); + has_title = true; + } else { + c.skip().ok_or(())?; + } + } + b"points" => s.points = c.uint().ok_or(())?.unwrap_or(0), + b"num_comments" => s.comments = c.uint().ok_or(())?, + b"created_at_i" => s.time = c.uint().ok_or(())?.unwrap_or(0), + _ => c.skip().ok_or(())?, + } + if c.eat(b',') { + continue; + } + if c.eat(b'}') { + break; + } + return Err(()); + } + s.set_title(&mut title); + if !has_title || s.len == 0 { + return Ok(None); + } + Ok(Some(s)) +} + +/// The stories of the answer, in its order, into `out`; how many. Hits without a title are left out; a body cut short +/// gives the hits that ended before the cut. +pub fn front_page(b: &[u8], out: &mut [Story; N]) -> usize { + let mut c = Cur { b, i: 0 }; + let mut n = 0; + if !c.eat(b'{') { + return 0; + } + loop { + let Some(key) = c.string() else { return n }; + if !c.eat(b':') { + return n; + } + if key == b"hits" && c.eat(b'[') { + if c.eat(b']') { + return n; + } + loop { + match hit(&mut c) { + Ok(Some(s)) if n < N => { + out[n] = s; + n += 1; + } + Ok(_) => {} + Err(()) => return n, + } + if !c.eat(b',') { + return n; + } + } + } + if c.skip().is_none() || !c.eat(b',') { + return n; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const FRONT: &[u8] = include_bytes!("fixtures/front.json"); + + fn parse(b: &[u8]) -> std::vec::Vec { + let mut out = [Story::EMPTY; N]; + let n = front_page(b, &mut out); + out[..n].to_vec() + } + + fn titles(b: &[u8]) -> std::vec::Vec { + parse(b).iter().map(|s| s.title().into()).collect() + } + + #[test] + fn the_real_answer() { + let s = parse(FRONT); + assert_eq!(s.len(), 8); + assert_eq!(s[0], Story::new("Amazon Ergo: A fast, cost-effective open-weights model", 780, Some(335), 1_796_147_550)); + assert_eq!(s[1].title(), "Cryptopocalypse"); + assert_eq!(s[3].title(), "Goals don't work. Rely on your values"); + assert_eq!((s[6].points, s[6].comments, s[6].time), (297, Some(486), 1_796_039_570)); + // "–" is an en dash + assert_eq!(s[7].title(), "Micromorts - visualizing your chances of dying doing everyday activities"); + } + + #[test] + fn key_order_and_extra_fields_dont_matter() { + let b = br#"{"hits" : [ {"_highlightResult":{"title":{"value":"x\"}]","matchLevel":"none"}},"objectID":"1", + "points": 5 ,"title":"B","num_comments":null,"created_at_i":7,"tags":["a",{"b":[1,2]}]}, + {"title":"C","points":1.5,"num_comments":-1,"created_at_i":1e3}, 3, "x", null, + {"points":9}, {}, {"title":null}, {"title":"D"} ],"nbHits":3}"#; + let s = parse(b); + assert_eq!(s.len(), 3); + assert_eq!(s[0], Story::new("B", 5, None, 7)); + // numbers we can't read are 0 / unknown, the story stays + assert_eq!(s[1], Story::new("C", 0, None, 0)); + assert_eq!(s[2], Story::new("D", 0, None, 0)); + // hits after other keys, and nothing at all + assert_eq!(titles(br#"{"a":{"hits":[{"title":"no"}]},"b":[],"hits":[{"title":"yes"}]}"#), ["yes"]); + assert!(parse(br#"{"hits":[]}"#).is_empty()); + assert!(parse(br#"{"message":"rate limited"}"#).is_empty()); + assert!(parse(b"").is_empty()); + assert!(parse(b"").is_empty()); + // more than N: the first N + let many = std::format!("{{\"hits\":[{}]}}", std::vec![r#"{"title":"t"}"#; 12].join(",")); + assert_eq!(parse(many.as_bytes()).len(), N); + } + + #[test] + fn escapes_and_non_ascii() { + let b = r#"{"hits":[{"title":"Say \"hi\" \\ back\/slash\ttab étÉ Straße naïve ‘q’ “dq” a—b 1–2 wait… 🚀 rocket 中 x y"}]}"#; + assert_eq!(titles(b.as_bytes()), [r#"Say "hi" \ back/slash tab etE Strasse naive 'q' "dq" a-b 1-2 wait... rocket x y"#]); + // the same as raw UTF-8, as a server may send it + let b = "{\"hits\":[{\"title\":\"Café — “Zürich” 🚀 Łódź Œuvre №5 ½\"}]}"; + assert_eq!(titles(b.as_bytes()), ["Cafe - \"Zurich\" Lodz OEuvre 5"]); + // broken escapes, lone surrogates and invalid UTF-8 drop out without taking their neighbours + let b = b"{\"hits\":[{\"title\":\"a\\ud83d b\\udc00c\\u12 d\\q e\xff\xc3f \xe2\x80g\"}]}"; + assert_eq!(titles(b), ["a bc12 d ef g"]); + // a title of nothing we can draw is no story + assert!(parse("{\"hits\":[{\"title\":\"🚀 中文\"}]}".as_bytes()).is_empty()); + } + + #[test] + fn folding() { + for c in ' '..='~' { + assert_eq!(ascii(c), c.encode_utf8(&mut [0; 4])); + } + for (c, a) in [('é', "e"), ('Ñ', "N"), ('ø', "o"), ('ÿ', "y"), ('ß', "ss"), ('Æ', "AE"), ('č', "c"), ('ł', "l"), ('ő', "o"), ('ž', "z"), ('Ş', "S"), ('ı', "i"), ('ĸ', "k"), ('ſ', "s"), ('×', "x"), ('÷', "/")] { + assert_eq!(ascii(c), a, "{c}"); + } + for c in ['\u{1F680}', '中', 'Ж', '\u{7}', '\u{200B}', '©', '°'] { + assert_eq!(ascii(c), "", "{c:?}"); + } + // every letter of both tables is a letter + for cp in (0xC0u32..0x180).filter(|&c| c != 0xD7 && c != 0xF7) { + let a = ascii(char::from_u32(cp).unwrap()); + assert!(!a.is_empty() && a.bytes().all(|b| b.is_ascii_alphabetic()), "{cp:x} {a:?}"); + } + } + + #[test] + fn long_titles_are_cut_at_a_word() { + let long = "word ".repeat(40); + let s = Story::new(&long, 0, None, 0); + assert!(s.title().len() <= TITLE_MAX && s.title().ends_with("word..."), "{:?}", s.title()); + let b = std::format!("{{\"hits\":[{{\"title\":\"{}\"}}]}}", "x".repeat(200)); + let t = &titles(b.as_bytes())[0]; + assert_eq!(t.len(), TITLE_MAX); + assert!(t.ends_with("x...")); + // exactly TITLE_MAX stays whole + let exact = "y".repeat(TITLE_MAX); + assert_eq!(Story::new(&exact, 0, None, 0).title(), exact); + let with_space = std::format!("{} ", exact); + assert_eq!(Story::new(&with_space, 0, None, 0).title(), exact); + } + + #[test] + fn every_cut_gives_whole_hits_only() { + let full = parse(FRONT); + // the body arrives in 121-byte records: every cut, inside and across them + for n in 0..FRONT.len() { + let got = parse(&FRONT[..n]); + assert!(got.len() <= full.len()); + assert_eq!(&got[..], &full[..got.len()], "cut at {n}"); + } + // a cut right after a hit's `}` gives that hit + let at = FRONT.windows(3).position(|w| w == b"\"},").unwrap() + 2; + assert_eq!(parse(&FRONT[..at]).len(), 1); + assert_eq!(parse(&FRONT[..at - 1]).len(), 0); + } + + #[test] + fn junk_never_panics() { + let mut seed = 1u32; + let alphabet = b"{}[]\":,\\u0123456789abcdefnulltrue \xc3\xa9\xff"; + for _ in 0..3000 { + let mut v = std::vec::Vec::new(); + v.extend_from_slice(br#"{"hits":["#); + for _ in 0..(seed % 200) { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); + v.push(alphabet[(seed >> 16) as usize % alphabet.len()]); + } + let _ = parse(&v); + } + // deep nesting is no recursion + let deep = std::format!("{{\"hits\":[{{\"x\":{}1{}, \"title\":\"ok\"}}]}}", "[".repeat(5000), "]".repeat(5000)); + assert_eq!(titles(deep.as_bytes()), ["ok"]); + } +} diff --git a/apps/tech-news/src/screen.rs b/apps/tech-news/src/screen.rs new file mode 100644 index 0000000..e5803ba --- /dev/null +++ b/apps/tech-news/src/screen.rs @@ -0,0 +1,419 @@ +//! What the screens draw, through `cmf_wp2_ui::Surface` so host tests see the watch's pixels. Three screens: +//! +//! - the menu app's list ([`menu`]): the title, a status line, the headlines in a list the crown scrolls (each +//! wrapped to up to 3 lines, a grey line of points, comments and age under it), the stock round scroll bar and a +//! Refresh pill; +//! - a story ([`detail`]), opened by a tap: its whole title and its numbers; the crown steps to the next one; +//! - the page next to the watch face ([`page`]): "Top on HN" and three headlines of two lines each, a tap shows the +//! next three. +//! +//! Text is Inter (`cmf_wp2_ui::font`, the system font's family) in the stock colours (`cmf_wp2_app::stock`), all of it +//! below the loader's status bar (the time, about 72 px wide, centred at y 4) and inside the round panel. Each screen +//! is drawn whole: it changes on a reply, a crown detent, a tap or the clock, never per frame. + +use crate::format::{self, Line}; +use crate::model::{Clock, Model, STALE_MIN, Status}; +use crate::parse::{N, Story}; +use cmf_wp2_app::stock; +use cmf_wp2_ui::color::{BLACK as BLACK_RGB, Rgb}; +use cmf_wp2_ui::draw::{rrect, scroll_bar}; +use cmf_wp2_ui::font::{self, HEIGHT, width}; +use cmf_wp2_ui::geom::chord; +use cmf_wp2_ui::{C, SIZE, Surface}; + +pub const BLACK: u16 = stock::BLACK as u16; +pub const WHITE: u16 = stock::WHITE as u16; +pub const GREY: u16 = stock::GREY as u16; +pub const ACCENT: u16 = stock::ACCENT as u16; +pub const ROW_BG: u16 = stock::ROW_BG as u16; + +/// Between two lines of a title. +pub const LINE_H: i32 = 25; +/// The meta line under a title, and the room it takes. +const META_GAP: i32 = 2; +pub const META_H: i32 = 26; + +// the menu: clear of the loader's status bar +const TITLE_Y: i32 = 38; +const STATUS_Y: i32 = 66; +pub const LIST_TOP: i32 = 98; +pub const LIST_BOTTOM: i32 = 392; +/// Between two stories of the list, a thin rule in the middle. +pub const ITEM_GAP: i32 = 14; +const LIST_MARGIN: i32 = 28; +pub const MENU_LINES: usize = 3; +pub const PILL_Y: i32 = 400; +const PILL_W: i32 = 160; +const PILL_H: i32 = 36; + +// a story +const DETAIL_HEAD_Y: i32 = 38; +const DETAIL_TOP: i32 = 72; +const DETAIL_BOTTOM: i32 = 392; +const DETAIL_LINE_H: i32 = 27; +pub const DETAIL_LINES: usize = 6; +const DETAIL_MARGIN: i32 = 22; +const DETAIL_NUM_H: i32 = 28; + +// the page +const PAGE_TITLE_Y: i32 = 44; +pub const PAGE_TOP: i32 = 82; +const PAGE_BOTTOM: i32 = 350; +pub const PAGE_PER: usize = 3; +const PAGE_LINES: usize = 2; +const PAGE_MARGIN: i32 = 20; +const PAGE_GAP: i32 = 14; +const PAGE_STATUS_Y: i32 = 362; +const DOTS_Y: i32 = 398; + +/// What the menu app shows besides the data. +pub struct Ui { + /// The first story of the list. + pub scroll: usize, + /// The story open, if one is. + pub detail: Option, + /// The page's three stories: `group · PAGE_PER` on. + pub group: usize, +} + +impl Ui { + pub const fn new() -> Ui { + Ui { scroll: 0, detail: None, group: 0 } + } + + /// One crown detent: the list scrolls by a story, a story open steps to the next; `true` if anything moved. + pub fn crown(&mut self, m: &Model, delta: i16) -> bool { + let step = delta.signum() as i32; + if let Some(i) = self.detail { + let j = (i as i32 + step).clamp(0, m.count.max(1) as i32 - 1) as usize; + self.detail = Some(j); + return j != i; + } + let s = (self.scroll as i32 + step).clamp(0, max_scroll(m) as i32) as usize; + let moved = s != self.scroll; + self.scroll = s; + moved + } + + /// After the stories changed: nothing out of range. + pub fn fit(&mut self, m: &Model) { + self.scroll = self.scroll.min(max_scroll(m)); + if self.detail.is_some_and(|i| i >= m.count) { + self.detail = None; + } + if self.group >= groups(m) { + self.group = 0; + } + } +} + +/// What a tap hit. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Hit { + Nothing, + /// Open this story. + Open(usize), + /// Close the story. + Back, + Refresh, + /// The page's next three. + Next, +} + +/// The status line and its colour: the phone's answer if something is wrong, else when the headlines are from. +pub fn status(m: &Model, wall: i32) -> (Line, u16) { + let with_time = |s: &str| { + let mut l = Line::of(s); + if let Some(at) = m.fetched { + l.push(" "); + l.push(format::hhmm(at).as_str()); + } + l + }; + let stale = m.fetched.is_some_and(|at| wall - at > STALE_MIN); + match m.status { + Status::Ask => (Line::of("Allow on phone"), ACCENT), + Status::Denied => (Line::of("Off in Companion"), ACCENT), + _ if m.busy() => (Line::of("Updating..."), GREY), + // old headlines on screen matter more than why the phone didn't answer + _ if stale => (with_time("Stale"), ACCENT), + _ if m.silent() => (with_time("No phone"), GREY), + Status::Failed => (with_time("Can't load"), GREY), + _ if m.fetched.is_none() => (Line::of("No news yet"), GREY), + _ => (with_time("Updated"), GREY), + } +} + +/// Everything the clock changes on a screen: the status line and every story's age. When it changes the screen is +/// drawn again. +pub fn clock_key(m: &Model, clock: Clock) -> (Line, [u32; N]) { + let mut ages = [0; N]; + for (a, s) in ages.iter_mut().zip(m.stories()) { + *a = format::age_key(clock.age(s.time)); + } + (status(m, clock.wall).0, ages) +} + +/// The phone needs the user before there is anything to show: the lines that say what to do. +fn help(m: &Model) -> Option<&'static [&'static str]> { + if m.count > 0 { + return None; + } + match m.status { + Status::Ask => Some(&["On your phone, open", "FMC Companion", "> Apps > Tech News", "and allow it"]), + Status::Denied => Some(&["Turned off on phone.", "Turn it on in", "FMC Companion", "> Apps > Tech News"]), + _ => None, + } +} + +/// Nothing yet and nothing wrong: where the headlines come from. +const EMPTY: &[&str] = &["Headlines come from", "your phone through", "FMC Companion"]; + +fn clear(s: &mut impl Surface) { + s.rect(0, 0, SIZE, SIZE, BLACK); +} + +/// A centred line, cut at the circle. +fn line(s: &mut impl Surface, y: i32, t: &str, c: u16) { + let (x0, x1) = chord(y - 4, y + HEIGHT, 8); + if width(t) <= x1 - x0 { + font::centre(s, C, y, t, c); + } else { + font::fitted(s, x0, y, t, x1 - x0, c); + } +} + +fn lines(s: &mut impl Surface, top: i32, ls: &[&str], c: u16) { + for (k, t) in ls.iter().enumerate() { + line(s, top + k as i32 * 30, t, c); + } +} + +/// A title in at most `max` lines of `px` (≤ 6); the last one keeps the rest, to draw with [`font::fitted`]. +pub fn wrap<'a>(title: &'a str, px: i32, max: usize) -> ([&'a str; DETAIL_LINES], usize) { + let mut out = [""; DETAIL_LINES]; + let n = font::wrap(title, px, &mut out[..max.min(DETAIL_LINES)]); + (out, n.max(1)) +} + +/// The meta line that fits `px`: with the comments, or without. +fn meta_text(st: &Story, clock: Clock, px: i32) -> Line { + let full = format::meta(st.points, st.comments, clock.age(st.time)); + if width(full.as_str()) <= px { full } else { format::meta(st.points, None, clock.age(st.time)) } +} + +/// A headline from (x, y): its lines in white, then the meta in grey. Returns the y under it. +fn headline(s: &mut impl Surface, st: &Story, x: i32, y: i32, px: i32, max: usize, clock: Clock) -> i32 { + let (ls, n) = wrap(st.title(), px, max); + for (k, t) in ls[..n].iter().enumerate() { + font::fitted(s, x, y + k as i32 * LINE_H, t, px, WHITE); + } + let my = y + n as i32 * LINE_H + META_GAP; + font::fitted(s, x, my, meta_text(st, clock, px).as_str(), px, GREY); + y + n as i32 * LINE_H + META_H +} + +/// The height of a headline wrapped to `max` lines of `px`. +fn headline_h(st: &Story, px: i32, max: usize) -> i32 { + wrap(st.title(), px, max).1 as i32 * LINE_H + META_H +} + +/// The list's text box: (left, right), as wide as its narrowest row so every line starts at one x. +pub fn list_box() -> (i32, i32) { + chord(LIST_TOP, LIST_BOTTOM, LIST_MARGIN) +} + +fn list_px() -> i32 { + let (x0, x1) = list_box(); + x1 - x0 +} + +/// The stories the list shows from `scroll`: (story, top y, height), as many as fit whole. +pub fn menu_layout(m: &Model, scroll: usize) -> ([(usize, i32, i32); N], usize) { + let mut out = [(0, 0, 0); N]; + let (mut n, mut y) = (0, LIST_TOP); + for i in scroll..m.count { + let h = headline_h(&m.stories[i], list_px(), MENU_LINES); + if y + h > LIST_BOTTOM && n > 0 { + break; + } + out[n] = (i, y, h); + n += 1; + y += h + ITEM_GAP; + } + (out, n) +} + +/// The last scroll that still fills the list: the stories from it to the end fit. +pub fn max_scroll(m: &Model) -> usize { + let mut room = LIST_BOTTOM - LIST_TOP + ITEM_GAP; + let mut s = m.count; + while s > 0 { + let h = headline_h(&m.stories[s - 1], list_px(), MENU_LINES) + ITEM_GAP; + if h > room { + break; + } + room -= h; + s -= 1; + } + s.min(m.count.saturating_sub(1)) +} + +fn pill(s: &mut impl Surface, t: &str, c: u16) { + let x = C - PILL_W / 2; + rrect(s, x, PILL_Y, PILL_W, PILL_H, PILL_H / 2, Rgb::from565(ROW_BG), BLACK_RGB); + font::centre(s, C, PILL_Y + (PILL_H - HEIGHT) / 2 + 1, t, c); +} + +/// The menu app: the list, or the story open. +pub fn menu(s: &mut impl Surface, m: &Model, ui: &Ui, clock: Clock) { + if let Some(i) = ui.detail.filter(|&i| i < m.count) { + detail(s, m, i, clock); + return; + } + clear(s); + font::centre(s, C, TITLE_Y, "Tech News", ACCENT); + let (st, c) = status(m, clock.wall); + line(s, STATUS_Y, st.as_str(), c); + if let Some(h) = help(m) { + lines(s, LIST_TOP + 50, h, WHITE); + } else if m.count == 0 { + lines(s, LIST_TOP + 64, EMPTY, GREY); + } else { + let (x0, x1) = list_box(); + let (items, n) = menu_layout(m, ui.scroll); + for (k, &(i, y, h)) in items[..n].iter().enumerate() { + headline(s, &m.stories[i], x0, y, x1 - x0, MENU_LINES, clock); + if k + 1 < n { + s.rect(x0, y + h + ITEM_GAP / 2 - 1, x1 - x0, 1, ROW_BG); + } + } + let max = max_scroll(m); + scroll_bar(s, ui.scroll as i32, max as i32, n as i32, BLACK_RGB); + } + let (t, c) = if m.busy() { ("Updating", GREY) } else { ("Refresh", WHITE) }; + pill(s, t, c); +} + +/// What a tap at (x, y) on the menu app hit. +pub fn menu_hit(m: &Model, ui: &Ui, _x: i32, y: i32) -> Hit { + if ui.detail.is_some() { + return Hit::Back; + } + if y >= PILL_Y - 4 { + return Hit::Refresh; + } + if help(m).is_some() { + return Hit::Nothing; + } + let (items, n) = menu_layout(m, ui.scroll); + for &(i, top, h) in &items[..n] { + // the gap around a story belongs to it + if (top - ITEM_GAP / 2..top + h + ITEM_GAP / 2).contains(&y) { + return Hit::Open(i); + } + } + Hit::Nothing +} + +/// The text box of a story's title: as wide as its narrowest line. +pub fn detail_box() -> (i32, i32) { + chord(DETAIL_TOP, DETAIL_TOP + DETAIL_LINES as i32 * DETAIL_LINE_H, DETAIL_MARGIN) +} + +/// One story: "3 of 8", its whole title centred, its points, comments and age, the Back pill. +pub fn detail(s: &mut impl Surface, m: &Model, i: usize, clock: Clock) { + clear(s); + let st = &m.stories[i]; + let mut head = Line::new(); + head.uint(i as u64 + 1, 1); + head.push(" of "); + head.uint(m.count as u64, 1); + font::centre(s, C, DETAIL_HEAD_Y, head.as_str(), ACCENT); + let (x0, x1) = detail_box(); + let (ls, n) = wrap(st.title(), x1 - x0, DETAIL_LINES); + let nums = [ + (format::points(st.points, false), WHITE), + (st.comments.map_or(Line::new(), format::comments), GREY), + (format::age_long(clock.age(st.time)), GREY), + ]; + let shown = nums.iter().filter(|(l, _)| !l.is_empty()).count() as i32; + // the block centred between the head and the pill + let block = n as i32 * DETAIL_LINE_H + 14 + shown * DETAIL_NUM_H; + let mut y = ((DETAIL_TOP + DETAIL_BOTTOM) / 2 - block / 2).max(DETAIL_TOP); + for t in &ls[..n] { + // only the last line can be too wide (it keeps the rest): cut with "…" + if width(t) > x1 - x0 { + font::fitted(s, x0, y, t, x1 - x0, WHITE); + } else { + font::centre(s, C, y, t, WHITE); + } + y += DETAIL_LINE_H; + } + y += 14; + for (l, c) in nums.iter().filter(|(l, _)| !l.is_empty()) { + line(s, y, l.as_str(), *c); + y += DETAIL_NUM_H; + } + pill(s, "Back", WHITE); +} + +/// How many threes of stories the page has. +pub fn groups(m: &Model) -> usize { + m.count.div_ceil(PAGE_PER).max(1) +} + +/// The page's text box. +pub fn page_box() -> (i32, i32) { + chord(PAGE_TOP, PAGE_BOTTOM, PAGE_MARGIN) +} + +/// The page next to the watch face: three headlines, the status line, a dot per three. +pub fn page(s: &mut impl Surface, m: &Model, ui: &Ui, clock: Clock) { + clear(s); + font::centre(s, C, PAGE_TITLE_Y, "Top on HN", ACCENT); + if let Some(h) = help(m) { + lines(s, PAGE_TOP + 50, h, WHITE); + } else if m.count == 0 { + lines(s, PAGE_TOP + 64, EMPTY, GREY); + } else { + let (x0, x1) = page_box(); + let from = (ui.group * PAGE_PER).min(m.count); + let shown = m.stories().iter().skip(from).take(PAGE_PER); + // the three centred in their band + let block: i32 = shown.clone().map(|st| headline_h(st, x1 - x0, PAGE_LINES) + PAGE_GAP).sum::() - PAGE_GAP; + let mut y = PAGE_TOP + ((PAGE_BOTTOM - PAGE_TOP - block) / 2).max(0); + for st in shown { + if y + headline_h(st, x1 - x0, PAGE_LINES) > PAGE_BOTTOM { + break; + } + y = headline(s, st, x0, y, x1 - x0, PAGE_LINES, clock) + PAGE_GAP; + } + } + let (st, c) = status(m, clock.wall); + line(s, PAGE_STATUS_Y, st.as_str(), c); + let g = groups(m); + if g > 1 && m.count > 0 { + dots(s, g, ui.group); + } +} + +/// The stock page dots, side by side: a white pill for the current one, grey dots for the others. +fn dots(s: &mut impl Surface, n: usize, at: usize) { + let w = (n as i32 - 1) * (stock::DOT + stock::DOT_GAP) + stock::DOT_ON; + let mut x = C - w / 2; + for k in 0..n { + let (dw, c) = if k == at { (stock::DOT_ON, WHITE) } else { (stock::DOT, GREY) }; + rrect(s, x, DOTS_Y, dw, stock::DOT, stock::DOT / 2, Rgb::from565(c), BLACK_RGB); + x += dw + stock::DOT_GAP; + } +} + +/// A tap on the page: the next three, when there are more. +pub fn page_hit(m: &Model) -> Hit { + if groups(m) > 1 && m.count > 0 { Hit::Next } else { Hit::Nothing } +} + +#[cfg(test)] +#[path = "screen_tests.rs"] +mod tests; diff --git a/apps/tech-news/src/screen_tests.rs b/apps/tech-news/src/screen_tests.rs new file mode 100644 index 0000000..754bf19 --- /dev/null +++ b/apps/tech-news/src/screen_tests.rs @@ -0,0 +1,329 @@ +extern crate std; + +use super::*; +use crate::model::wall_min; +use crate::parse::front_page; +use cmf_wp2_ui::Fb; +use std::vec; +use std::vec::Vec; + +const FRONT: &[u8] = include_bytes!("fixtures/front.json"); +const WALL: i32 = 1440 * 20_000 + 14 * 60 + 5; + +/// 21:02 in UTC+2 on the day of the fixture: its stories are 1 to 30 hours old. +fn clock() -> Clock { + Clock::new(wall_min(2026, 12, 1, 21, 2), 120) +} + +fn real() -> Model { + let mut m = Model::new(); + m.count = front_page(FRONT, &mut m.stories); + m.fetched = Some(clock().wall - 3); + m.status = Status::Ok; + m +} + +/// Eight stories as long as titles get, with the widest numbers. +fn widest() -> Model { + let mut m = real(); + for (k, s) in m.stories.iter_mut().enumerate() { + let t = if k % 2 == 0 { "WWWWWWWW ".repeat(10) } else { "Mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm".repeat(2) }; + *s = Story::new(&t, u32::MAX, Some(u32::MAX), 0); + } + m +} + +/// One-word stories: the list holds many at once. +fn short() -> Model { + let mut m = real(); + for (k, s) in m.stories.iter_mut().enumerate() { + *s = Story::new(if k == 0 { "A" } else { "Cryptopocalypse" }, 1, Some(1), 1_796_147_550); + } + m +} + +/// Every lit pixel lies 2 px inside the round panel. +fn inside(draw: impl Fn(&mut Fb)) { + let mut px = vec![0u16; (SIZE * SIZE) as usize]; + let mut fb = Fb::new(&mut px); + draw(&mut fb); + let r = C - 2; + let mut lit = 0; + for y in 0..SIZE { + for x in 0..SIZE { + if fb.at(x, y) != BLACK { + lit += 1; + let (dx, dy) = (2 * x + 1 - 2 * C, 2 * y + 1 - 2 * C); + assert!(dx * dx + dy * dy <= 4 * r * r, "lit at ({x}, {y})"); + } + } + } + assert!(lit > 0); +} + +fn states() -> Vec { + let mut v = vec![Model::new(), real(), widest(), short()]; + let mut ask = Model::new(); + ask.status = Status::Ask; + v.push(ask); + let mut denied = Model::new(); + denied.status = Status::Denied; + v.push(denied); + let mut stale = real(); + stale.fetched = Some(clock().wall - 300); + stale.status = Status::Failed; + v.push(stale); + let mut one = real(); + one.count = 1; + v.push(one); + v +} + +#[test] +fn menu_stays_inside_the_circle() { + for m in states() { + for scroll in 0..=max_scroll(&m) { + let ui = Ui { scroll, detail: None, group: 0 }; + inside(|fb| menu(fb, &m, &ui, clock())); + } + for i in 0..m.count { + let ui = Ui { scroll: 0, detail: Some(i), group: 0 }; + inside(|fb| menu(fb, &m, &ui, clock())); + } + } +} + +#[test] +fn page_stays_inside_the_circle() { + for m in states() { + for group in 0..groups(&m) { + let ui = Ui { scroll: 0, detail: None, group }; + inside(|fb| page(fb, &m, &ui, clock())); + } + } +} + +/// The rows with lit pixels of colour `c` in columns x0..x1, as (first, last). +fn lit_y(fb: &Fb, x0: i32, x1: i32, c: u16) -> Option<(i32, i32)> { + let v: Vec = (0..SIZE).filter(|&y| (x0..x1).any(|x| fb.at(x, y) == c)).collect(); + Some((*v.first()?, *v.last()?)) +} + +#[test] +fn nothing_under_the_status_bar() { + // the loader's clock sits at the top centre, about 72 px wide from y 4: nothing lit above y 32 on any screen + for m in states() { + let mut draws: Vec> = Vec::new(); + let mm = &m; + draws.push(std::boxed::Box::new(move |fb| menu(fb, mm, &Ui::new(), clock()))); + draws.push(std::boxed::Box::new(move |fb| page(fb, mm, &Ui::new(), clock()))); + if m.count > 0 { + draws.push(std::boxed::Box::new(move |fb| detail(fb, mm, 0, clock()))); + } + for d in draws { + let mut px = vec![0u16; (SIZE * SIZE) as usize]; + let mut fb = Fb::new(&mut px); + d(&mut fb); + assert!((0..32).all(|y| (0..SIZE).all(|x| fb.at(x, y) == BLACK))); + } + } +} + +#[test] +fn the_list_fits_between_status_and_pill() { + for m in states() { + for scroll in 0..=max_scroll(&m) { + let (items, n) = menu_layout(&m, scroll); + assert!(n >= 1 || m.count == 0); + for &(_, y, h) in &items[..n] { + assert!(y >= LIST_TOP && y + h <= LIST_BOTTOM, "{y} {h}"); + } + let mut px = vec![0u16; (SIZE * SIZE) as usize]; + let mut fb = Fb::new(&mut px); + menu(&mut fb, &m, &Ui { scroll, detail: None, group: 0 }, clock()); + // the text column (not the scroll bar at the rim): white and grey between the status line and the pill + let (x0, x1) = list_box(); + if m.count > 0 { + let (top, bottom) = lit_y(&fb, x0, x1, WHITE).unwrap(); + assert!(top < LIST_TOP + 10, "{top}"); + assert!(bottom >= PILL_Y, "the pill's label"); + let rows: Vec = (LIST_TOP - 4..PILL_Y).filter(|&y| (x0..x1).any(|x| fb.at(x, y) != BLACK)).collect(); + assert!(rows.iter().all(|&y| y < LIST_BOTTOM), "{:?}", rows.last()); + } + } + } +} + +#[test] +fn scrolling_reaches_the_last_story() { + for m in [real(), widest(), short()] { + let mut ui = Ui::new(); + for _ in 0..20 { + ui.crown(&m, 1); + } + assert_eq!(ui.scroll, max_scroll(&m)); + let (items, n) = menu_layout(&m, ui.scroll); + assert_eq!(items[n - 1].0, m.count - 1, "the last story shows at the end"); + assert!(!ui.crown(&m, 1)); + // one detent less hides it, or there's nothing to scroll + if ui.scroll > 0 { + assert!(ui.crown(&m, -1)); + let (items, n) = menu_layout(&m, ui.scroll); + assert!(items[n - 1].0 < m.count - 1 || n == m.count - ui.scroll); + } + } + assert_eq!(max_scroll(&short()), 4); // four one-line stories fill the list + assert!(max_scroll(&widest()) >= 5); + assert_eq!(max_scroll(&Model::new()), 0); +} + +#[test] +fn titles_wrap_to_three_lines_in_the_list() { + let m = real(); + let (x0, x1) = list_box(); + assert!(x1 - x0 >= 280, "{}", x1 - x0); + for s in m.stories() { + let (ls, n) = wrap(s.title(), x1 - x0, MENU_LINES); + assert!((1..=MENU_LINES).contains(&n)); + // the fixture's titles show whole + assert_eq!(ls[..n].join(" "), s.title()); + for l in &ls[..n] { + assert!(width(l) <= x1 - x0, "{l:?}"); + } + } + // and with their meta line in full + for s in m.stories() { + let full = format::meta(s.points, s.comments, clock().age(s.time)); + assert!(width(full.as_str()) <= x1 - x0, "{full:?}"); + } + // a story shows the fixture's titles whole, and the longest real ones (80 characters) + let (d0, d1) = detail_box(); + let long = Story::new("Show HN: I built a tiny relational database in 4,000 lines of C, and you can too!", 1, None, 0); + assert_eq!(long.title().len(), 81); + for s in m.stories().iter().chain([&long]) { + let (ls, n) = wrap(s.title(), d1 - d0, DETAIL_LINES); + assert!(n <= 4, "{ls:?}"); + assert!(ls[..n].iter().all(|l| width(l) <= d1 - d0), "{ls:?}"); + } + // a pathological one: the last of six lines is cut + for s in widest().stories() { + let (ls, n) = wrap(s.title(), d1 - d0, DETAIL_LINES); + assert!(n <= DETAIL_LINES); + assert!(ls[..n - 1].iter().all(|l| width(l) <= d1 - d0), "{ls:?}"); + } +} + +#[test] +fn menu_taps() { + let m = real(); + let mut ui = Ui::new(); + let (items, n) = menu_layout(&m, 0); + assert!(n >= 2); + for &(i, y, h) in &items[..n] { + assert_eq!(menu_hit(&m, &ui, C, y + 1), Hit::Open(i)); + assert_eq!(menu_hit(&m, &ui, C, y + h - 1), Hit::Open(i)); + assert_eq!(menu_hit(&m, &ui, C, y + h / 2), Hit::Open(i)); + } + // the rule between two stories splits them + let (_, y1, h1) = items[0]; + assert_eq!(menu_hit(&m, &ui, C, y1 + h1 + ITEM_GAP / 2 - 1), Hit::Open(0)); + assert_eq!(menu_hit(&m, &ui, C, y1 + h1 + ITEM_GAP / 2), Hit::Open(1)); + assert_eq!(menu_hit(&m, &ui, C, PILL_Y + 10), Hit::Refresh); + assert_eq!(menu_hit(&m, &ui, C, 20), Hit::Nothing); + assert_eq!(menu_hit(&m, &ui, C, 66), Hit::Nothing); + // scrolled: the first row is the scroll's story + ui.crown(&m, 1); + ui.crown(&m, 1); + assert_eq!(menu_hit(&m, &ui, C, LIST_TOP + 2), Hit::Open(2)); + // a story open: any tap goes back, the crown steps through the stories + ui.detail = Some(0); + assert_eq!(menu_hit(&m, &ui, C, 200), Hit::Back); + assert_eq!(menu_hit(&m, &ui, C, PILL_Y + 10), Hit::Back); + assert!(!ui.crown(&m, -1)); + assert!(ui.crown(&m, 1)); + assert_eq!(ui.detail, Some(1)); + for _ in 0..20 { + ui.crown(&m, 1); + } + assert_eq!(ui.detail, Some(7)); + // the help text has no rows + let mut m = Model::new(); + m.status = Status::Ask; + assert_eq!(menu_hit(&m, &Ui::new(), C, LIST_TOP + 10), Hit::Nothing); + assert_eq!(menu_hit(&m, &Ui::new(), C, PILL_Y + 10), Hit::Refresh); + let m = Model::new(); + assert_eq!(menu_hit(&m, &Ui::new(), C, LIST_TOP + 10), Hit::Nothing); +} + +#[test] +fn page_taps_cycle_threes() { + let m = real(); + assert_eq!(groups(&m), 3); + assert_eq!(page_hit(&m), Hit::Next); + let mut one = real(); + one.count = 3; + assert_eq!(page_hit(&one), Hit::Nothing); + assert_eq!(page_hit(&Model::new()), Hit::Nothing); + // fewer stories after an answer: back to the first three, nothing open past the end + let mut ui = Ui { scroll: 5, detail: Some(7), group: 2 }; + ui.fit(&one); + assert_eq!((ui.scroll, ui.detail, ui.group), (0, None, 0)); +} + +#[test] +fn the_page_shows_three_with_two_lines_each() { + let (x0, x1) = page_box(); + for m in [real(), widest()] { + // three headlines of two lines and their meta fit above the status line + let mut y = PAGE_TOP; + for s in m.stories().iter().take(PAGE_PER) { + let (_, n) = wrap(s.title(), x1 - x0, 2); + assert!(n <= 2); + y += n as i32 * LINE_H + META_H + 14; + } + assert!(y - 14 <= 350, "{y}"); + } +} + +#[test] +fn status_lines() { + let st = |m: &Model, w: i32| status(m, w).0; + let mut m = Model::new(); + assert_eq!(st(&m, WALL).as_str(), "No news yet"); + m.refresh(0); + m.poll(0); + assert_eq!(st(&m, WALL).as_str(), "Updating..."); + m.sent(0, 0); + m.poll(0); + m.sent(0, 0); + m.poll(companion_rpc::RETRY_MS); + assert_eq!(st(&m, WALL).as_str(), "No phone"); + let mut m = real(); + m.fetched = Some(WALL); + assert_eq!(st(&m, WALL + 3).as_str(), "Updated 14:05"); + assert_eq!(status(&m, WALL + 61), (Line::of("Stale 14:05"), ACCENT)); + m.status = Status::Failed; + assert_eq!(st(&m, WALL).as_str(), "Can't load 14:05"); + assert_eq!(st(&m, WALL + 61).as_str(), "Stale 14:05"); + // a silent phone with headlines: when they're from, "Stale" once they're old + let mut q = real(); + q.fetched = Some(WALL); + q.refresh(0); + q.poll(0); + q.poll(companion_rpc::RETRY_MS); + assert!(q.silent()); + assert_eq!(st(&q, WALL + 2).as_str(), "No phone 14:05"); + assert_eq!(status(&q, WALL + 61), (Line::of("Stale 14:05"), ACCENT)); + m.status = Status::Denied; + assert_eq!(st(&m, WALL).as_str(), "Off in Companion"); + m.status = Status::Ask; + assert_eq!(st(&m, WALL).as_str(), "Allow on phone"); + // the clock key moves when the status or an age changes + let m = real(); + let at = |min: i32| Clock { wall: clock().wall + min, utc: clock().utc + min }; + assert_eq!(clock_key(&m, at(0)).0, clock_key(&m, at(1)).0); + assert_ne!(clock_key(&m, at(0)), clock_key(&m, at(61))); + let mut fresh = real(); + fresh.stories[0].time = (clock().utc as u32) * 60 - 120; // 2 minutes old + assert_ne!(clock_key(&fresh, at(0)), clock_key(&fresh, at(1))); +} diff --git a/apps/tech-news/store.md b/apps/tech-news/store.md new file mode 100644 index 0000000..ff38ef3 --- /dev/null +++ b/apps/tech-news/store.md @@ -0,0 +1,25 @@ +The top 8 stories on the Hacker News front page, on the wrist. Each headline is wrapped to up to three lines, with +its points, comments and age under it in grey. Turn the crown to scroll, tap **Refresh** to ask again now. Tap a +headline to read the whole title with its points, comments and how long ago it was posted; turn the crown there to +step through the stories, tap or go back to return to the list. + +Long-press **Tech News** in Apps and choose **Add page** for the top three headlines one swipe from the watch face +(tap it for the next three), or **Add widget** for a card with the top story's points and headline. + +The watch asks the phone when you open the app or the page and every 15 minutes while it's shown, and keeps the last +headlines, so it opens at once without the phone and shows when they're from ("Stale" after an hour). Headlines +refresh only while the app or its page is open: the widget card shows the last ones the app or its page got. They +come from the public Hacker News search API at hn.algolia.com. Accents and typographic punctuation are shown as plain +letters, quotes and dashes; characters the watch can't draw (emoji, other scripts) are left out. + +The first time, the watch says "Allow on phone": open FMC Companion, Apps, Tech News, and allow +`http:hn.algolia.com`. The phone's prompt says the app wants to "read and change data" on that site because the +request's address is too long for the read-only web method, so it goes through the general one (`http.request`); the +app only ever sends a GET and reads the answer. Nothing about you goes over Bluetooth. + +## Requirements + +- A phone with **FMC Companion** (iOS or Android, [github.com/fmctools/companion](https://github.com/fmctools/companion)), + paired with the watch. In its Apps tab, allow Tech News to reach `http:hn.algolia.com`. +- The [patched firmware](/firmware) with the channel key (2026-11-13 or later) and the [App Loader](/firmware) + (2026-11-13 or later; 2026-11-15 or later for the page and the widget). diff --git a/apps/tech-news/store.toml b/apps/tech-news/store.toml new file mode 100644 index 0000000..ce5d40c --- /dev/null +++ b/apps/tech-news/store.toml @@ -0,0 +1,6 @@ +# The app's listing in the FMC store (README.md, "store.toml"). The page's body is store.md. +name = "Tech News" +summary = "The Hacker News front page from your phone, with a page next to the watch face and a widget card" +version = "0.1.0" +author = "Ziyad Eslam" +screenshots = ["shots/list.png", "shots/story.png", "shots/page.png"]