Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ An app runs on a watch with the patched firmware and the App Loader, both on the
| [`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 |
| [`trip-computer`](apps/trip-computer) | A GPS speedometer and trip computer on the watch's own GPS: speed, distance, moving time, average, top speed and ascent; a page next to the face and a widget card |
| [`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

Expand Down
14 changes: 14 additions & 0 deletions apps/tech-news/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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
26 changes: 26 additions & 0 deletions apps/tech-news/icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/tech-news/shots/list.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/tech-news/shots/page.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/tech-news/shots/story.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions apps/tech-news/src/fixtures/front.json
Original file line number Diff line number Diff line change
@@ -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}
315 changes: 315 additions & 0 deletions apps/tech-news/src/format.rs
Original file line number Diff line number Diff line change
@@ -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<u32>, 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());
}
}
Loading
Loading