From bf17802aa4a69fb300df49d834cfbab1f40f73e1 Mon Sep 17 00:00:00 2001 From: Vincent Bonduro Date: Thu, 25 Jun 2026 12:32:02 -0400 Subject: [PATCH] WIP platform/pico2w: integrate mousefood UI --- Cargo.lock | 285 +++++- platform/pico2w/Cargo.toml | 10 + .../pico2w/docs/mousefood-migration-plan.md | 132 +++ platform/pico2w/memory.x | 8 +- platform/pico2w/src/bin/menu_preview.rs | 461 ++++++++++ platform/pico2w/src/display/eg_target.rs | 267 ++++++ platform/pico2w/src/display/hw.rs | 339 ++++--- platform/pico2w/src/display/mod.rs | 28 +- platform/pico2w/src/display/ui.rs | 849 ++++++++++++++++++ platform/pico2w/src/flash_rom.rs | 4 +- platform/pico2w/src/input.rs | 12 +- platform/pico2w/src/state/in_game_menu.rs | 4 +- platform/pico2w/src/state/main_menu.rs | 4 +- platform/pico2w/src/state/mod.rs | 3 + platform/pico2w/src/state/rom_list.rs | 4 +- platform/pico2w/src/state/settings.rs | 4 +- platform/pico2w/src/state/wifi_menu.rs | 40 +- 17 files changed, 2208 insertions(+), 246 deletions(-) create mode 100644 platform/pico2w/docs/mousefood-migration-plan.md create mode 100644 platform/pico2w/src/bin/menu_preview.rs create mode 100644 platform/pico2w/src/display/eg_target.rs create mode 100644 platform/pico2w/src/display/ui.rs diff --git a/Cargo.lock b/Cargo.lock index 4b7a243..1d10c97 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -261,9 +261,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.11.1" +version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" dependencies = [ "serde_core", ] @@ -289,7 +289,7 @@ dependencies = [ "embedded-io 0.7.1", "embedded-io-async 0.7.0", "futures-intrusive", - "heapless 0.8.0", + "heapless 0.9.3", ] [[package]] @@ -331,6 +331,15 @@ version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + [[package]] name = "cc" version = "1.2.58" @@ -411,7 +420,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" dependencies = [ "termcolor", - "unicode-width", + "unicode-width 0.1.14", ] [[package]] @@ -420,6 +429,20 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "compact_str" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + [[package]] name = "concurrent-queue" version = "2.5.0" @@ -645,8 +668,18 @@ version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" dependencies = [ - "darling_core", - "darling_macro", + "darling_core 0.20.11", + "darling_macro 0.20.11", +] + +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core 0.23.0", + "darling_macro 0.23.0", ] [[package]] @@ -663,13 +696,37 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.117", +] + [[package]] name = "darling_macro" version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ - "darling_core", + "darling_core 0.20.11", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "darling_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +dependencies = [ + "darling_core 0.23.0", "quote", "syn 2.0.117", ] @@ -917,7 +974,7 @@ name = "embassy-executor-macros" version = "0.8.0" source = "git+https://github.com/embassy-rs/embassy#c722d94fd2a4a856fbd771d177ff34100674c7cd" dependencies = [ - "darling", + "darling 0.20.11", "proc-macro2", "quote", "syn 2.0.117", @@ -1396,6 +1453,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -1607,7 +1670,7 @@ checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ "allocator-api2", "equivalent", - "foldhash", + "foldhash 0.1.5", ] [[package]] @@ -1615,6 +1678,22 @@ name = "hashbrown" version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] [[package]] name = "hashlink" @@ -1923,6 +2002,28 @@ dependencies = [ "serde_core", ] +[[package]] +name = "indoc" +version = "2.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" +dependencies = [ + "rustversion", +] + +[[package]] +name = "instability" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb2d60ef19920a3a9193c3e371f726ec1dafc045dac788d0fb3704272458971" +dependencies = [ + "darling 0.23.0", + "indoc", + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "ipnet" version = "2.12.0" @@ -1985,6 +2086,18 @@ dependencies = [ "simple_asn1", ] +[[package]] +name = "kasuari" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde5057d6143cc94e861d90f591b9303d6716c6b9602309150bd068853c10899" +dependencies = [ + "hashbrown 0.16.1", + "portable-atomic", + "portable-atomic-util", + "thiserror", +] + [[package]] name = "keccak" version = "0.1.6" @@ -2059,7 +2172,7 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ddbf48fd451246b1f8c2610bd3b4ac0cc6e149d89832867093ab69a17194f08" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.0", "libc", "plain", "redox_syscall 0.7.3", @@ -2076,6 +2189,15 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "line-clipping" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f50e8f47623268b5407192d26876c4d7f89d686ca130fdc53bced4814cd29f8" +dependencies = [ + "bitflags 2.13.0", +] + [[package]] name = "linked_list_allocator" version = "0.10.6" @@ -2128,6 +2250,15 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "lru" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a860605968fce16869fd239cf4237a82f3ac470723415db603b0e8b6c8d4fb9" +dependencies = [ + "hashbrown 0.17.1", +] + [[package]] name = "lru-slab" version = "0.1.2" @@ -2227,6 +2358,17 @@ dependencies = [ "nb 1.1.0", ] +[[package]] +name = "mousefood" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f494a6d8c84e4be6de959c899bced1953fab377cd54dd1a9f911fa759486306" +dependencies = [ + "embedded-graphics", + "ratatui-core", + "thiserror", +] + [[package]] name = "nb" version = "0.1.3" @@ -2604,6 +2746,15 @@ version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" +[[package]] +name = "portable-atomic-util" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +dependencies = [ + "portable-atomic", +] + [[package]] name = "potential_utf" version = "0.1.4" @@ -2834,13 +2985,61 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "ratatui" +version = "0.30.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3274ba0a2c5e1bcad2a2005d20f4dc59dad26b2eb0940fb094500dba4099d57d" +dependencies = [ + "instability", + "ratatui-core", + "ratatui-widgets", +] + +[[package]] +name = "ratatui-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c" +dependencies = [ + "bitflags 2.13.0", + "compact_str", + "hashbrown 0.17.1", + "itertools", + "kasuari", + "lru", + "strum", + "thiserror", + "unicode-segmentation", + "unicode-truncate", + "unicode-width 0.2.2", +] + +[[package]] +name = "ratatui-widgets" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66e3d19bcc9130ca376277d93b60767ff121ace3be06f5f95f81dd68956407d1" +dependencies = [ + "bitflags 2.13.0", + "hashbrown 0.17.1", + "indoc", + "instability", + "itertools", + "line-clipping", + "ratatui-core", + "strum", + "unicode-segmentation", + "unicode-width 0.2.2", +] + [[package]] name = "redox_syscall" version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.0", ] [[package]] @@ -2849,7 +3048,7 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce70a74e890531977d37e532c34d45e9055d2409ed08ddba14529471ed0be16" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.0", ] [[package]] @@ -3024,7 +3223,7 @@ version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.0", "errno", "libc", "linux-raw-sys", @@ -3076,7 +3275,7 @@ checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" name = "rustyboy-core" version = "0.1.0" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.0", "bytemuck", "heapless 0.9.3", "png", @@ -3110,7 +3309,9 @@ dependencies = [ "fixed", "heapless 0.9.3", "mipidsi", + "mousefood", "png", + "ratatui", "rp-pac", "rustyboy-core", "static_cell", @@ -3551,7 +3752,7 @@ checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526" dependencies = [ "atoi", "base64", - "bitflags 2.11.1", + "bitflags 2.13.0", "byteorder", "bytes", "crc", @@ -3593,7 +3794,7 @@ checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" dependencies = [ "atoi", "base64", - "bitflags 2.11.1", + "bitflags 2.13.0", "byteorder", "crc", "dotenvy", @@ -3696,6 +3897,27 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "subtle" version = "2.6.1" @@ -3959,7 +4181,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.0", "bytes", "futures-util", "http", @@ -3984,7 +4206,7 @@ version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.0", "bytes", "futures-util", "http", @@ -4136,12 +4358,35 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-truncate" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width 0.2.2", +] + [[package]] name = "unicode-width" version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + [[package]] name = "unicode-xid" version = "0.2.6" @@ -4360,7 +4605,7 @@ version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.0", "hashbrown 0.15.5", "indexmap", "semver 1.0.27", @@ -4635,7 +4880,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" dependencies = [ "anyhow", - "bitflags 2.11.1", + "bitflags 2.13.0", "indexmap", "log", "serde", diff --git a/platform/pico2w/Cargo.toml b/platform/pico2w/Cargo.toml index b21e527..aa105f4 100644 --- a/platform/pico2w/Cargo.toml +++ b/platform/pico2w/Cargo.toml @@ -2,6 +2,7 @@ name = "rustyboy-pico2w" version = "0.1.0" edition = "2021" +default-run = "rustyboy-pico2w" [lib] name = "rustyboy_pico2w" @@ -13,6 +14,12 @@ path = "src/main.rs" required-features = ["firmware-bin"] test = false +[[bin]] +name = "menu-preview" +path = "src/bin/menu_preview.rs" +required-features = ["std"] +test = false + [features] default = ["firmware-bin"] # Keeps the embedded firmware binary enabled for normal builds while allowing @@ -42,6 +49,7 @@ embedded-graphics = "0.8" [target.'cfg(not(target_arch = "arm"))'.dependencies] png = "0.17" heapless = { version = "0.9", default-features = false } +ratatui = { version = "0.30", default-features = false, features = ["portable-atomic"] } # --------------------------------------------------------------------------- # Embedded (ARM bare-metal) only — excluded from host test builds @@ -103,3 +111,5 @@ embassy-net = { git = "https://github.com/embassy-rs/embassy", features = [ "defmt", "tcp", "udp", "dhcpv4", "medium-ethernet", ] } embedded-io-async = { version = "0.7" } +mousefood = { version = "0.5", default-features = false } +ratatui = { version = "0.30", default-features = false, features = ["portable-atomic"] } diff --git a/platform/pico2w/docs/mousefood-migration-plan.md b/platform/pico2w/docs/mousefood-migration-plan.md new file mode 100644 index 0000000..06aa188 --- /dev/null +++ b/platform/pico2w/docs/mousefood-migration-plan.md @@ -0,0 +1,132 @@ +# Migrate menus + loading screens to ratatui via mousefood + +## Context + +The firmware's menu/loading UI is currently a **hand-rolled, per-row pixel renderer** +(`display/menu.rs`, `display/loading.rs`, `display/text.rs`, `display/font.rs`) that +streams 480-byte rows straight to the ILI9341 over async SPI from +`display/hw.rs::GameDisplay`. It bypasses embedded-graphics entirely (raw +CASET/RASET/RAMWR commands) and carries bespoke optimizations: frame-hash skip, +single-item/text-only partial repaints, anti-tearing draw order, a 2× 8×8 palette +font, crash `!` badge, `*` marker, and **marquee scrolling**. + +We want **richer UI capability** for upcoming screens (scrollbars, tables, styled +layouts, popups) by adopting ratatui via the **mousefood** embedded-graphics backend. +A visual change from the current pixel-precise design is acceptable. Scope: **menus + +loading screens**. Splash animation and the 60 fps game-frame DMA path stay on the +existing custom code. Marquee scrolling for long ROM names is preserved via a custom +ratatui widget. + +The big enabler: menu **logic** is already cleanly separated from rendering. `menu.rs` +(state machines, `MenuInput`/`MenuEffect`, `MenuFrame` descriptor, fully unit-tested) +is reused unchanged. This is a **presentation-layer rewrite only**. + +mousefood targets embedded-graphics **0.8.2** (matches our `0.8`) and ratatui 0.30 / +no_std + alloc. We already run no_std with `embedded-alloc` (160 KiB heap). + +## Key design decision: framebuffer-backed DrawTarget + +mousefood needs a synchronous `DrawTarget`. A naive raw-SPI DrawTarget +would set a 1-pixel window per glyph pixel (`draw_iter`) — tens of thousands of blocking +window-sets per repaint, far too slow. Instead: + +- Render into an in-RAM **`&'static mut` Rgb565 framebuffer** (the DrawTarget is just a + memory write — fast), tracking a **dirty bounding box** (min/max y written). +- After `terminal.draw(...)`, **flush only the dirty rows** to the panel using the + existing async SPI DMA in `GameDisplay` (reuse `set_window` + `self.spi.write`). +- A **persistent ratatui `Terminal`** diffs cells across draws, so steady-state repaints + (e.g. marquee) touch only a few cells → a small dirty band → cheap DMA flush. This + replaces the hand-rolled hash-skip and `draw_menu_item`/`draw_menu_item_text` partials. + +**SRAM budget is the #1 risk — verify before building UI** (see Verification). A full +240×320×2 framebuffer is 153.6 KiB. Mitigation: menus and the 101 KiB +`CORE0_SCALE_BUF` (game-frame prescale) are **never live at the same time**, so back +both with **one shared `static_cell` region** sized for the framebuffer (net new SRAM +≈ 52 KiB, not 153 KiB). If even that doesn't fit alongside the 160 KiB heap + stacks, +fall back to flushing the terminal in horizontal bands with a smaller band buffer. + +## Implementation + +### 1. Dependencies (ARM-only block in `Cargo.toml`) +- `mousefood` with `default-features = false` (drop the alloc-heavy `fonts`/unicodefonts + feature; supply an embedded-graphics `MonoFont` via `EmbeddedBackendConfig` instead). +- `ratatui` `default-features = false`, features `["portable-atomic"]`; `ratatui-core`. +- Keep host (non-ARM) builds compiling: gate the new UI module behind + `#[cfg(target_arch = "arm")]` like `display/hw.rs`, OR pull ratatui host-side too for + the render unit tests (preferred — see Testing). +- **Verify at this step:** `cargo build --release` for `thumbv8m.main-none-eabihf` links, + and check binary size / a clean `cargo tree` (no accidental std). + +### 2. Framebuffer DrawTarget adapter — new `display/eg_target.rs` +- `struct FbTarget { buf: &'static mut [Rgb565; 240*320], dirty: Option<(u16,u16)> }`. +- Impl `DrawTarget` + `OriginDimensions` (240×320). `draw_iter` and + `fill_contiguous` write into `buf` and widen the dirty y-range. +- `fn take_dirty(&mut self) -> Option` returns and clears the band. +- Back `buf` with a shared `static_cell` region unioned with `CORE0_SCALE_BUF` (see SRAM + note). Reuse existing `RenderWindow` (`display/mod.rs`) for the flush window type. + +### 3. UI host object — new `display/ui.rs` (the ratatui layer) +- Owns the persistent `Terminal>` + `EmbeddedBackendConfig` + (MonoFont, ColorTheme mapping DMG palette C0–C3). +- `render_menu(frame: &MenuFrame, f: &mut ratatui::Frame)`: maps the existing `MenuFrame` + descriptor to widgets — `Block` title (header + crash `!` badge), a `List` with + highlight symbol `>`, dimmed style for `enabled[i] == false`, the `*` marker span, and + a footer line (`A:SELECT B:BACK`). Long selected items use the **marquee widget**. +- `render_loading(frame: &LoadingFrame, f)`: title/filename + a gauge for progress + (replaces `display/loading.rs` row renderer). +- Custom **`MarqueeLine` widget**: scrolls the selected item's text using `marquee_frame` + (already on `MenuFrame`); it must always write its cells (so ratatui's diff re-emits + them) → those cells land in the dirty band each animation tick. + +### 4. Wire into `GameDisplay` — keep call sites stable +- Embed the `Ui` (terminal + `FbTarget`) inside `GameDisplay` (or a sibling held next to + it). Reimplement the existing public methods so **no state file changes**: + - `draw_menu(&MenuFrame)` → `terminal.draw(|f| render_menu(frame, f))` then flush + `take_dirty()` band via DMA. + - `draw_loading_progress` / `draw_loading_bar` → `render_loading`. + - `draw_menu_item` / `draw_menu_item_text` become **thin wrappers over `draw_menu`** + (cell-diff handles partial updates) — or delete them and update the few `rom_list.rs` + callers. Marquee tick (`tick_marquee` in `state/rom_list.rs`) keeps calling a redraw; + diffing keeps it cheap. +- `draw_letterbox_bars` still resets caches; with ratatui, force a full repaint by + clearing the terminal's prev-buffer on the next menu open (so stale game pixels under + the menu are repainted). Keep the existing reset of `prev_frame_hash`. + +### 5. Remove/replace the old renderer +- Delete `display/menu.rs`, `display/loading.rs`, `display/text.rs`, `display/font.rs` + and their re-exports in `display/mod.rs` once `ui.rs` covers their surfaces. +- Keep `menu.rs` (logic) and `display/mod.rs` palette constants / `Display` / scaling + / splash untouched. `MenuFrame`, `LoadingFrame`, `menu_item_needs_marquee` stay as the + descriptor API consumed by `ui.rs`. + +## Critical files +- `platform/pico2w/Cargo.toml` — add deps (ARM block). +- `platform/pico2w/src/display/hw.rs` — `GameDisplay`: embed `Ui`, reimplement + `draw_menu*` / `draw_loading*`, share the framebuffer with `CORE0_SCALE_BUF`. +- `platform/pico2w/src/display/eg_target.rs` *(new)* — `FbTarget` DrawTarget + dirty box. +- `platform/pico2w/src/display/ui.rs` *(new)* — ratatui Terminal, `render_menu`, + `render_loading`, `MarqueeLine` widget. +- `platform/pico2w/src/display/mod.rs` — module wiring; drop old re-exports. +- Unchanged: `src/menu.rs`, `src/state/*.rs` (call sites preserved), splash, game DMA. + +## Testing +- **Logic:** `menu.rs` unit tests stay green (no changes). +- **Render (host):** pull ratatui on the host build and assert with a ratatui + `TestBackend`/`Buffer` that `render_menu`/`render_loading` produce the expected cells + (cursor `>`, dimmed disabled item, `*` marker, crash badge, footer, marquee offset) — + replacing the deleted `display/menu.rs`/`text.rs` pixel tests. +- Drop the old pixel-level tests in the deleted modules. + +## Verification (end-to-end) +1. **SRAM gate (do first):** after adding the shared framebuffer static, build release + and check the linker fits (`cargo size --release -- -A`, or map file) — confirm + `.bss` + stacks + 160 KiB heap + 153 KiB fb region ≤ 520 KiB. If not, switch to banded + flush before proceeding. +2. `cd platform/pico2w && cargo build --release` (target `thumbv8m.main-none-eabihf`). +3. Flash + RTT: `pkill -f probe-rs; sleep 1` then `cargo run --release` (per memory: + kill stale probe-rs first; runner is `rb-flash`). +4. On hardware, exercise each surface: main menu (with/without staged ROM), in-game + pause (LOAD greyed when no save), settings, wifi menu, ROM list paging, **marquee on a + long ROM name**, crash `!` badge, and a ROM **loading progress** screen. Confirm no + tearing on cursor moves and acceptable repaint latency. +5. Confirm game-frame path and splash are visually unchanged (untouched code). diff --git a/platform/pico2w/memory.x b/platform/pico2w/memory.x index b4cc027..a1b1d2c 100644 --- a/platform/pico2w/memory.x +++ b/platform/pico2w/memory.x @@ -5,10 +5,14 @@ * RAM: 512KB striped across SRAM0-SRAM7 (8 × 64KB banks, best for general use) * SRAM8/SRAM9: 4KB direct-mapped banks (dedicated use, e.g. per-core stacks) * - * NOTE: the first 512 KiB of flash are reserved for the firmware image. + * NOTE: the first 640 KiB of flash are reserved for the firmware image. * The remaining flash is available to runtime-managed data (currently a staged * ROM slot). * + * Flash budget was expanded from 512K to 640K to accommodate ratatui/mousefood + * UI layer added in the mousefood migration (adds ~82 KiB to .text/.rodata). + * The firmware slot constant in flash_rom.rs was updated to match. + * * Bead 1 uses a single-app layout (no bootloader). * Bead 8 (OTA) will restructure this into dual-bank partitions * for embassy-boot-rp: @@ -17,7 +21,7 @@ * APP_B : ORIGIN = 0x10200000, LENGTH = ~2M <- OTA staging slot */ MEMORY { - FLASH : ORIGIN = 0x10000000, LENGTH = 512K + FLASH : ORIGIN = 0x10000000, LENGTH = 640K RAM : ORIGIN = 0x20000000, LENGTH = 512K CORE1_STACK : ORIGIN = 0x20080000, LENGTH = 8K } diff --git a/platform/pico2w/src/bin/menu_preview.rs b/platform/pico2w/src/bin/menu_preview.rs new file mode 100644 index 0000000..74f35ad --- /dev/null +++ b/platform/pico2w/src/bin/menu_preview.rs @@ -0,0 +1,461 @@ +use std::error::Error; +use std::fs::{self, File}; +use std::io::{self, BufWriter, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ratatui::backend::TestBackend; +use ratatui::prelude::{Buffer, Color}; +use ratatui::Terminal; +use rustyboy_pico2w::display::font; +use rustyboy_pico2w::display::ui::draw_menu; +use rustyboy_pico2w::menu::{ + MainMenu, MenuEffect, MenuFrame, MenuInput, MenuLogic, RomListEffect, RomListLogic, + SettingsMenu, +}; + +const COLS: u16 = 30; +const ROWS: u16 = 24; +const CELL_W: usize = 8; +const CELL_H: usize = 13; +const PNG_W: usize = COLS as usize * CELL_W; +const PNG_H: usize = ROWS as usize * CELL_H; +const OUT_DIR: &str = "/tmp/rustyboy-menu-preview"; + +const ROM_ITEMS: [&str; 7] = [ + "ADVENTURE_ISLAND_II_SUPER_LONG_NAME.GB", + "CASTLEVANIA_THE_ADVENTURE.GB", + "DR_MARIO.GB", + "KIRBYS_DREAM_LAND.GB", + "LEGEND_OF_ZELDA_LINKS_AWAKENING_DX.GBC", + "METROID_II_RETURN_OF_SAMUS.GB", + "TETRIS.GB", +]; + +fn main() -> Result<(), Box> { + let args: Vec = std::env::args().collect(); + if args.iter().any(|arg| arg == "--dump") { + dump_screens(Path::new(OUT_DIR))?; + return Ok(()); + } + + let mut app = PreviewApp::new(); + let mut terminal = HostTerminal::enter()?; + app.render(&mut terminal, "ready")?; + + loop { + let key = read_key()?; + match key { + Key::Quit => break, + Key::Screenshot => { + let path = app.save_screenshot(Path::new(OUT_DIR))?; + app.render(&mut terminal, &format!("saved {}", path.display()))?; + } + Key::None => {} + _ => { + app.handle_key(key); + app.render(&mut terminal, "")?; + } + } + } + + Ok(()) +} + +struct PreviewApp { + screen: Screen, + shots: usize, +} + +impl PreviewApp { + fn new() -> Self { + Self { + screen: Screen::Main(MainMenu::new()), + shots: 0, + } + } + + fn handle_key(&mut self, key: Key) { + let input = key.input(); + match &mut self.screen { + Screen::Main(menu) => match menu.handle_main(input, false) { + MenuEffect::ShowRoms => { + self.screen = Screen::Roms(RomListLogic::new(ROM_ITEMS.len())) + } + MenuEffect::ShowSettings => self.screen = Screen::Settings(SettingsMenu::new()), + _ => {} + }, + Screen::Roms(logic) => match logic.handle(input) { + RomListEffect::Back => self.screen = Screen::Main(MainMenu::new()), + RomListEffect::NextPage => logic.reset(ROM_ITEMS.len()), + RomListEffect::PrevPage => logic.select_last(), + _ => {} + }, + Screen::Settings(menu) => match menu.handle(input) { + MenuEffect::Back => self.screen = Screen::Main(MainMenu::new()), + MenuEffect::ShowWifiMenu => self.screen = Screen::WifiPortal, + _ => {} + }, + Screen::WifiPortal => { + if input.back { + self.screen = Screen::Settings(SettingsMenu::new()); + } + } + Screen::WifiConfigured => { + if input.back { + self.screen = Screen::Settings(SettingsMenu::new()); + } else if input.confirm { + self.screen = Screen::WifiPortal; + } + } + } + } + + fn render(&self, terminal: &mut HostTerminal, status: &str) -> io::Result<()> { + let buf = self.render_buffer()?; + terminal.draw(&buf, status) + } + + fn render_buffer(&self) -> io::Result { + render_screen(&self.screen) + } + + fn save_screenshot(&mut self, dir: &Path) -> io::Result { + fs::create_dir_all(dir)?; + let name = format!("menu-preview-{:02}.png", self.shots); + self.shots += 1; + let path = dir.join(name); + let buf = self.render_buffer()?; + save_png(&buf, &path)?; + save_text(&buf, &path.with_extension("txt"))?; + Ok(path) + } +} + +enum Screen { + Main(MainMenu), + Roms(RomListLogic), + Settings(SettingsMenu), + WifiPortal, + WifiConfigured, +} + +fn render_screen(screen: &Screen) -> io::Result { + let mut terminal = + Terminal::new(TestBackend::new(COLS, ROWS)).expect("test backend is infallible"); + terminal + .draw(|f| match screen { + Screen::Main(menu) => { + let mut frame = menu.frame(false); + frame.crash_pending = true; + draw_menu(f, &frame); + } + Screen::Roms(logic) => { + let enabled = [true; 7]; + let frame = MenuFrame { + title: "ROMS", + items: &ROM_ITEMS, + selected: logic.selected(), + marquee_frame: 0, + enabled: &enabled, + marked: Some(4), + crash_pending: false, + }; + draw_menu(f, &frame); + } + Screen::Settings(menu) => { + let frame = menu.frame(false); + draw_menu(f, &frame); + } + Screen::WifiPortal => { + let items = ["JOIN WIFI", "RustyBoy", "OPEN", "192.168.4.1"]; + let enabled = [true; 4]; + let frame = MenuFrame { + title: "WIFI SETUP", + items: &items, + selected: usize::MAX, + marquee_frame: 0, + enabled: &enabled, + marked: None, + crash_pending: false, + }; + draw_menu(f, &frame); + } + Screen::WifiConfigured => { + let items = ["SSID: HomeNetwork-With-A-Long-Name.", "FORGET"]; + let enabled = [false, true]; + let frame = MenuFrame { + title: "WIFI", + items: &items, + selected: 1, + marquee_frame: 0, + enabled: &enabled, + marked: None, + crash_pending: false, + }; + draw_menu(f, &frame); + } + }) + .expect("test backend draw is infallible"); + Ok(terminal.backend().buffer().clone()) +} + +fn dump_screens(dir: &Path) -> io::Result<()> { + fs::create_dir_all(dir)?; + + let mut roms = RomListLogic::new(ROM_ITEMS.len()); + for _ in 0..4 { + let _ = roms.handle(MenuInput { + down: true, + ..MenuInput::default() + }); + } + + let screens = [ + ("main", Screen::Main(MainMenu::new())), + ("roms", Screen::Roms(roms)), + ("settings", Screen::Settings(SettingsMenu::new())), + ("wifi-setup", Screen::WifiPortal), + ("wifi-configured", Screen::WifiConfigured), + ]; + + for (name, screen) in screens { + let buf = render_screen(&screen)?; + let png = dir.join(format!("{name}.png")); + save_png(&buf, &png)?; + save_text(&buf, &dir.join(format!("{name}.txt")))?; + println!("{}", png.display()); + } + + Ok(()) +} + +#[derive(Clone, Copy)] +enum Key { + Up, + Down, + Confirm, + Back, + Screenshot, + Quit, + None, +} + +impl Key { + fn input(self) -> MenuInput { + match self { + Self::Up => MenuInput { + up: true, + ..MenuInput::default() + }, + Self::Down => MenuInput { + down: true, + ..MenuInput::default() + }, + Self::Confirm => MenuInput { + confirm: true, + ..MenuInput::default() + }, + Self::Back => MenuInput { + back: true, + ..MenuInput::default() + }, + _ => MenuInput::default(), + } + } +} + +fn read_key() -> io::Result { + let mut byte = [0u8; 1]; + io::stdin().read_exact(&mut byte)?; + Ok(match byte[0] { + b'q' | 0x03 => Key::Quit, + b's' => Key::Screenshot, + b'k' | b'w' => Key::Up, + b'j' => Key::Down, + b'a' | b'\r' | b'\n' => Key::Confirm, + b'b' | 0x7f | 0x08 => Key::Back, + 0x1b => read_escape_key()?, + _ => Key::None, + }) +} + +fn read_escape_key() -> io::Result { + let mut seq = [0u8; 2]; + if io::stdin().read_exact(&mut seq).is_err() { + return Ok(Key::None); + } + Ok(match seq { + [b'[', b'A'] => Key::Up, + [b'[', b'B'] => Key::Down, + [b'[', b'D'] => Key::Back, + [b'[', b'C'] => Key::Confirm, + _ => Key::None, + }) +} + +struct HostTerminal; + +impl HostTerminal { + fn enter() -> io::Result { + let _ = Command::new("stty").args(["raw", "-echo"]).status(); + let mut out = io::stdout().lock(); + write!(out, "\x1b[?1049h\x1b[?25l\x1b[2J\x1b[H")?; + out.flush()?; + Ok(Self) + } + + fn draw(&mut self, buf: &Buffer, status: &str) -> io::Result<()> { + let mut out = io::stdout().lock(); + write!(out, "\x1b[H")?; + for y in 0..buf.area.height { + for x in 0..buf.area.width { + let cell = buf + .cell(ratatui::layout::Position { x, y }) + .expect("cell inside buffer"); + let fg = rgb(cell.fg); + let bg = rgb(cell.bg); + write!( + out, + "\x1b[38;2;{};{};{}m\x1b[48;2;{};{};{}m{}", + fg.0, + fg.1, + fg.2, + bg.0, + bg.1, + bg.2, + cell.symbol() + )?; + } + write!(out, "\x1b[0m\r\n")?; + } + write!( + out, + "\x1b[0m\r\narrows/j/k move enter/a select b/backspace back s screenshot q quit\r\n{status}\x1b[K" + )?; + out.flush() + } +} + +impl Drop for HostTerminal { + fn drop(&mut self) { + let _ = Command::new("stty").arg("sane").status(); + let mut out = io::stdout().lock(); + let _ = write!(out, "\x1b[0m\x1b[?25h\x1b[?1049l"); + let _ = out.flush(); + } +} + +fn save_png(buf: &Buffer, path: &Path) -> io::Result<()> { + let file = File::create(path)?; + let writer = BufWriter::new(file); + let mut encoder = png::Encoder::new(writer, PNG_W as u32, PNG_H as u32); + encoder.set_color(png::ColorType::Rgb); + encoder.set_depth(png::BitDepth::Eight); + let mut png = encoder + .write_header() + .map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?; + let data = buffer_pixels(buf); + png.write_image_data(&data) + .map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string())) +} + +fn save_text(buf: &Buffer, path: &Path) -> io::Result<()> { + let mut file = File::create(path)?; + for y in 0..buf.area.height { + for x in 0..buf.area.width { + let symbol = buf + .cell(ratatui::layout::Position { x, y }) + .map(|c| c.symbol()) + .unwrap_or(" "); + write!(file, "{}", ascii_symbol(symbol))?; + } + writeln!(file)?; + } + Ok(()) +} + +fn buffer_pixels(buf: &Buffer) -> Vec { + let mut pixels = vec![0u8; PNG_W * PNG_H * 3]; + for y in 0..buf.area.height { + for x in 0..buf.area.width { + let cell = buf + .cell(ratatui::layout::Position { x, y }) + .expect("cell inside buffer"); + draw_cell( + &mut pixels, + x as usize * CELL_W, + y as usize * CELL_H, + ascii_symbol(cell.symbol()), + rgb(cell.fg), + rgb(cell.bg), + ); + } + } + pixels +} + +fn draw_cell( + pixels: &mut [u8], + x0: usize, + y0: usize, + ch: char, + fg: (u8, u8, u8), + bg: (u8, u8, u8), +) { + for y in 0..CELL_H { + for x in 0..CELL_W { + put_pixel(pixels, x0 + x, y0 + y, bg); + } + } + + if ch == ' ' { + return; + } + + let glyph = if ch.is_ascii() { ch as u8 } else { b'?' }; + for y in 0..8 { + let row = font::glyph_row(glyph, y); + for x in 0..CELL_W { + let glyph_x = x * 8 / CELL_W; + if (row >> glyph_x) & 1 != 0 { + put_pixel(pixels, x0 + x, y0 + y + 1, fg); + } + } + } +} + +fn put_pixel(pixels: &mut [u8], x: usize, y: usize, color: (u8, u8, u8)) { + if x >= PNG_W || y >= PNG_H { + return; + } + let offset = (y * PNG_W + x) * 3; + pixels[offset] = color.0; + pixels[offset + 1] = color.1; + pixels[offset + 2] = color.2; +} + +fn ascii_symbol(symbol: &str) -> char { + match symbol { + "\u{2500}" => '-', + "\u{2502}" => '|', + "\u{250c}" | "\u{2510}" | "\u{2514}" | "\u{2518}" => '+', + _ => symbol.chars().next().unwrap_or(' '), + } +} + +fn rgb(color: Color) -> (u8, u8, u8) { + match color { + Color::Black | Color::Reset => (0x08, 0x18, 0x20), + Color::Gray | Color::DarkGray => (0x34, 0x68, 0x56), + Color::Green | Color::LightGreen => (0x88, 0xC0, 0x70), + Color::White => (0xE0, 0xF8, 0xD0), + Color::Yellow | Color::LightYellow => (0xE0, 0xF8, 0xD0), + Color::Red | Color::LightRed => (0xE0, 0x20, 0x20), + Color::Blue | Color::LightBlue => (0x40, 0x80, 0xF0), + Color::Magenta | Color::LightMagenta => (0xC0, 0x80, 0xC0), + Color::Cyan | Color::LightCyan => (0x88, 0xC0, 0x70), + Color::Rgb(r, g, b) => (r, g, b), + Color::Indexed(_) => (0x88, 0xC0, 0x70), + } +} diff --git a/platform/pico2w/src/display/eg_target.rs b/platform/pico2w/src/display/eg_target.rs new file mode 100644 index 0000000..6d92b99 --- /dev/null +++ b/platform/pico2w/src/display/eg_target.rs @@ -0,0 +1,267 @@ +//! Rgb565 framebuffer DrawTarget for the ratatui/mousefood menu layer. +//! +//! `FbTarget` wraps a raw `*mut [u16; 240*320]` flat framebuffer storing native +//! RGB565 words and implements `DrawTarget` + `OriginDimensions`. +//! Every pixel write extends an internal dirty y-band; `take_dirty()` returns +//! and clears that band so `hw.rs` can DMA only the changed rows to the panel. +//! +//! The buffer is a **raw pointer**, not a `&'static mut`, because the same +//! backing memory is shared (in time, never concurrently) with the game-frame +//! pre-scale buffer in `hw.rs`. Holding two overlapping `&'static mut` would be +//! instant UB (aliasing); instead each method materializes a short-lived `&mut` +//! that is dropped before control returns, so only one live borrow of the shared +//! region exists at any instant. See the SAFETY note in +//! `GameDisplay::new_after_splash`. +//! +use embedded_graphics::draw_target::DrawTarget; +use embedded_graphics::geometry::{OriginDimensions, Size}; +use embedded_graphics::pixelcolor::Rgb565; +use embedded_graphics::prelude::IntoStorage; +use embedded_graphics::primitives::Rectangle; +use embedded_graphics::Pixel; + +use super::{RenderWindow, SCREEN_H, SCREEN_W}; + +/// Number of pixels in the full 240×320 framebuffer. +pub const FB_PIXELS: usize = SCREEN_W as usize * SCREEN_H as usize; + +/// A 240×320 RGB565 framebuffer backed by raw `u16` storage. +/// +/// Tracks the minimum/maximum Y row written since the last `take_dirty` call so +/// the async SPI flush only transfers the changed band. +pub struct FbTarget { + /// Raw pointer to the framebuffer pixels (native-endian RGB565 words). + /// + /// Row y, column x: element `y * SCREEN_W + x`. Held as a raw pointer so + /// the same backing memory can be shared with the game-frame pre-scale + /// buffer; each method derefs it to a transient `&mut`/`&` (see module docs). + buf: *mut [u16; FB_PIXELS], + /// Inclusive dirty Y range: `(y_min, y_max)`. `None` = nothing written. + dirty: Option<(u16, u16)>, +} + +impl FbTarget { + /// Construct from a raw pointer to the shared framebuffer region. + /// + /// Called once from `GameDisplay::new_after_splash`. The pointer must be + /// valid for the lifetime of the program and must not be mutably accessed + /// through any other live `&mut` while a render is in flight (the game-frame + /// and menu paths are mutually exclusive — see the SAFETY note there). + pub fn new(buf: *mut [u16; FB_PIXELS]) -> Self { + Self { buf, dirty: None } + } + + /// Materialize a transient mutable slice view of the framebuffer. + /// + /// # Safety + /// No other `&mut` to the shared region may be live (guaranteed by the + /// game/menu mutual-exclusion invariant). + #[inline(always)] + fn buf_mut(&mut self) -> &mut [u16; FB_PIXELS] { + // SAFETY: `buf` is valid for the program lifetime; the game-frame path + // (the only other user of this memory) is never in flight during a menu + // render, so this is the sole live `&mut` to the region. + unsafe { &mut *self.buf } + } + + /// Mark a row as dirty, widening the tracked band. + #[inline(always)] + fn mark_dirty_row(&mut self, y: i32) { + if y < 0 || y >= SCREEN_H { + return; + } + let y = y as u16; + self.dirty = Some(match self.dirty { + None => (y, y), + Some((mn, mx)) => (mn.min(y), mx.max(y)), + }); + } + + /// Return the dirty [`RenderWindow`] (exclusive y_end) and clear the band. + /// + /// Returns `None` when nothing has been written since the last call. + pub fn take_dirty(&mut self) -> Option { + let (y_min, y_max) = self.dirty.take()?; + Some(RenderWindow::full_width_rows(y_min, y_max + 1)) + } + + /// Force the entire screen into the dirty band. + /// + /// Call before the first `terminal.draw()` after returning from the game + /// (so stale game pixels under the menu area are repainted). + pub fn mark_all_dirty(&mut self) { + self.dirty = Some((0, SCREEN_H as u16 - 1)); + } + + /// Read a row of native-endian RGB565 words into `dst_be` as big-endian + /// bytes for SPI transmission. + /// + /// `dst_be` must be exactly 480 bytes (240 pixels × 2 bytes). + pub fn read_row_be(&self, y: u16, dst_be: &mut [u8; 480]) { + let row_start = y as usize * SCREEN_W as usize; + // SAFETY: shared-region invariant (no concurrent game-frame write); this + // is a transient shared view dropped before the function returns. + let buf = unsafe { &*self.buf }; + let row = &buf[row_start..row_start + SCREEN_W as usize]; + for (i, &px) in row.iter().enumerate() { + let bytes = px.to_be_bytes(); + dst_be[i * 2] = bytes[0]; + dst_be[i * 2 + 1] = bytes[1]; + } + } +} + +impl OriginDimensions for FbTarget { + fn size(&self) -> Size { + Size::new(SCREEN_W as u32, SCREEN_H as u32) + } +} + +impl DrawTarget for FbTarget { + type Color = Rgb565; + type Error = core::convert::Infallible; + + fn draw_iter(&mut self, pixels: I) -> Result<(), Self::Error> + where + I: IntoIterator>, + { + for Pixel(pt, color) in pixels { + if pt.x < 0 || pt.x >= SCREEN_W || pt.y < 0 || pt.y >= SCREEN_H { + continue; + } + let idx = pt.y as usize * SCREEN_W as usize + pt.x as usize; + self.buf_mut()[idx] = color.into_storage(); + self.mark_dirty_row(pt.y); + } + Ok(()) + } + + fn fill_contiguous(&mut self, area: &Rectangle, colors: I) -> Result<(), Self::Error> + where + I: IntoIterator, + { + let x0 = area.top_left.x.max(0); + let y0 = area.top_left.y.max(0); + let x1 = (area.top_left.x + area.size.width as i32).min(SCREEN_W); + let y1 = (area.top_left.y + area.size.height as i32).min(SCREEN_H); + if x1 <= x0 || y1 <= y0 { + return Ok(()); + } + let mut colors = colors.into_iter(); + for ay in area.top_left.y..area.top_left.y + area.size.height as i32 { + for ax in area.top_left.x..area.top_left.x + area.size.width as i32 { + let c = match colors.next() { + Some(c) => c, + None => return Ok(()), + }; + if ax < 0 || ax >= SCREEN_W || ay < 0 || ay >= SCREEN_H { + continue; + } + let idx = ay as usize * SCREEN_W as usize + ax as usize; + self.buf_mut()[idx] = c.into_storage(); + self.mark_dirty_row(ay); + } + } + Ok(()) + } + + fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> { + let x0 = area.top_left.x.max(0) as usize; + let y0 = area.top_left.y.max(0) as usize; + let x1 = (area.top_left.x + area.size.width as i32).min(SCREEN_W) as usize; + let y1 = (area.top_left.y + area.size.height as i32).min(SCREEN_H) as usize; + if x1 <= x0 || y1 <= y0 { + return Ok(()); + } + let buf = self.buf_mut(); + for y in y0..y1 { + let row_start = y * SCREEN_W as usize; + for x in x0..x1 { + buf[row_start + x] = color.into_storage(); + } + } + for y in y0..y1 { + self.mark_dirty_row(y as i32); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use embedded_graphics::{geometry::Point, pixelcolor::RgbColor, primitives::Rectangle}; + use std::convert::TryInto; + + fn backing() -> Box<[u16; FB_PIXELS]> { + vec![0u16; FB_PIXELS] + .into_boxed_slice() + .try_into() + .ok() + .unwrap() + } + + #[test] + fn draw_iter_writes_native_rgb565_storage_and_tracks_dirty_rows() { + let mut backing = backing(); + let mut target = FbTarget::new(backing.as_mut() as *mut [u16; FB_PIXELS]); + + target + .draw_iter([ + Pixel(Point::new(5, 7), Rgb565::RED), + Pixel(Point::new(9, 3), Rgb565::GREEN), + Pixel(Point::new(-1, 4), Rgb565::BLUE), + ]) + .unwrap(); + + assert_eq!( + backing[7 * SCREEN_W as usize + 5], + Rgb565::RED.into_storage() + ); + assert_eq!( + backing[3 * SCREEN_W as usize + 9], + Rgb565::GREEN.into_storage() + ); + assert_eq!( + target.take_dirty(), + Some(RenderWindow::full_width_rows(3, 8)) + ); + assert_eq!(target.take_dirty(), None); + } + + #[test] + fn fill_solid_tracks_clipped_dirty_band() { + let mut backing = backing(); + let mut target = FbTarget::new(backing.as_mut() as *mut [u16; FB_PIXELS]); + + target + .fill_solid( + &Rectangle::new(Point::new(238, 318), Size::new(8, 8)), + Rgb565::BLUE, + ) + .unwrap(); + + assert_eq!( + backing[318 * SCREEN_W as usize + 238], + Rgb565::BLUE.into_storage() + ); + assert_eq!( + target.take_dirty(), + Some(RenderWindow::full_width_rows(318, 320)) + ); + } + + #[test] + fn read_row_be_exports_numeric_rgb565_in_panel_byte_order() { + let mut backing = backing(); + backing[0] = Rgb565::RED.into_storage(); + backing[1] = Rgb565::GREEN.into_storage(); + backing[2] = Rgb565::BLUE.into_storage(); + let target = FbTarget::new(backing.as_mut() as *mut [u16; FB_PIXELS]); + + let mut row = [0u8; 480]; + target.read_row_be(0, &mut row); + + assert_eq!(&row[0..6], &[0xF8, 0x00, 0x07, 0xE0, 0x00, 0x1F]); + } +} diff --git a/platform/pico2w/src/display/hw.rs b/platform/pico2w/src/display/hw.rs index 5f1f8c9..faea3d4 100644 --- a/platform/pico2w/src/display/hw.rs +++ b/platform/pico2w/src/display/hw.rs @@ -19,30 +19,40 @@ use mipidsi::Builder; use static_cell::ConstStaticCell; +use super::eg_target::{FbTarget, FB_PIXELS}; +use super::ui::Ui; use super::{ - loading_bar_window, menu_item_text_window, menu_item_window, render_loading_row, - render_menu_row, scale_native_to_rgb565_range, Display, LoadingFrame, LoadingProgress, - NativeFrame, RenderWindow, ScaledFrame, SCALED_FRAME_PIXELS, + scale_native_to_rgb565_range, Display, LoadingFrame, LoadingProgress, NativeFrame, + RenderWindow, ScaledFrame, }; use crate::menu::MenuFrame; // --------------------------------------------------------------------------- -// Core 0 pre-scale buffer +// Shared Core 0 pixel buffer // -// `send_frame` scales the dirty row range from the native GB framebuffer (23 KB) -// into this 101 KB static, then issues a single DMA burst. Keeping the buffer -// as a `ConstStaticCell`-backed `&'static mut` field on `GameDisplay` avoids -// placing 101 KB on the stack or heap and lets the linker pack it into BSS. +// This single static backs BOTH the game-frame pre-scale buffer (101 KiB, the +// first SCALED_FRAME_PIXELS elements) AND the ratatui RGB565 framebuffer for +// menus/loading (150 KiB, full FB_PIXELS elements). // -// `ConstStaticCell` is const-initialized to all-zeros, so the buffer lands in -// `.bss` with no flash overhead. `GameDisplay::new_after_splash` calls -// `.take()` once to claim the exclusive `&'static mut ScaledFrame`; after that -// `&mut self.scale_buf` in `send_frame` / `send_frame_raw` provides safe, -// uniquely-owned mutable access — no unsafe required. +// The two uses are NEVER live simultaneously: +// - Game mode: `send_frame` / `send_frame_raw` use the first 101 KiB as a +// ScaledFrame. The Ui object is idle. +// - Menu mode: `Ui::render_menu` / `render_loading` use the full 150 KiB as +// a native-endian RGB565 framebuffer. The scale path is not called. +// +// Both views use raw `[u16]` storage, so the same backing memory is re-used +// without relying on `Rgb565` layout. Game mode stores pre-swapped RGB565 words +// for zero-copy SPI; menu mode stores native-endian RGB565 words that +// `FbTarget::read_row_be` exports as panel-order bytes. +// +// `ConstStaticCell` zero-initialises into BSS (no flash cost). // --------------------------------------------------------------------------- -static CORE0_SCALE_BUF: ConstStaticCell = - ConstStaticCell::new([0u16; SCALED_FRAME_PIXELS]); +/// Total size of the shared buffer (the larger of the two uses). +const SHARED_BUF_LEN: usize = FB_PIXELS; // 240*320 = 76800 u16s = 153 600 bytes + +static CORE0_SHARED_BUF: ConstStaticCell<[u16; SHARED_BUF_LEN]> = + ConstStaticCell::new([0u16; SHARED_BUF_LEN]); // Embassy's RP2350 SPI divider picks the nearest realizable rate at or below // the requested frequency. 62.5 MHz is exact at 250 MHz sysclk, but at 280 MHz @@ -149,10 +159,25 @@ pub struct GameDisplay<'d> { dc: Output<'d>, _rst: Output<'d>, _bl: Output<'d>, - /// Exclusively-owned 101 KB scale buffer, backed by the `CORE0_SCALE_BUF` - /// BSS static. Claimed once in `new_after_splash`; accessed via `&mut - /// self.scale_buf` in `send_frame` / `send_frame_raw`. - scale_buf: &'static mut ScaledFrame, + /// Game-frame pre-scale buffer, as a **raw pointer** into the first + /// SCALED_FRAME_PIXELS elements of `CORE0_SHARED_BUF`. + /// + /// Raw (not `&'static mut`) because the same backing memory is shared with + /// the ratatui framebuffer in `ui` — holding two overlapping `&'static mut` + /// would be instant UB. `send_frame` / `send_frame_raw` deref this to a + /// transient `&mut` that is dropped before they return; menus are never in + /// flight at the same time, so only one live borrow of the region ever + /// exists. Idle while menus are active. + scale_buf: *mut ScaledFrame, + /// ratatui UI layer (terminal + FbTarget framebuffer). + /// + /// The FbTarget holds a raw pointer into the same `CORE0_SHARED_BUF` + /// backing store (the full FB_PIXELS range). Idle while the game loop is + /// running. + ui: Ui, + /// Last loading-screen filename, retained so `draw_loading_bar` can redraw + /// via ratatui without erasing static title/filename text. + loading_filename: heapless::String<64>, /// Multiplicative hash of the last frame successfully sent to the display. /// /// Compared against each new frame's hash before deciding whether to @@ -160,17 +185,6 @@ pub struct GameDisplay<'d> { /// the display refreshes its own GRAM with no scan-line race. /// Cost: 4 bytes (vs 103 KB for a full shadow copy). prev_frame_hash: u32, - /// Hash of the last [`MenuFrame`] passed to [`draw_menu`]. - /// - /// Hashed at the struct level (before any rendering) using the same Knuth - /// multiplicative step as [`knuth_hash`]. If the incoming frame hashes - /// identically to this cached value, `draw_menu` returns immediately - /// without rendering or DMA-ing anything — the display already shows the - /// correct content. - /// - /// Zeroed in `draw_letterbox_bars` so the first `draw_menu` call after a - /// game session always performs a full repaint. Cost: 4 bytes. - prev_menu_frame_hash: u32, } impl<'d> GameDisplay<'d> { @@ -219,6 +233,28 @@ impl<'d> GameDisplay<'d> { let rst = Output::new(rst_pin, Level::High); let bl = Output::new(bl_pin, Level::High); + // Claim the shared pixel buffer once and derive TWO overlapping raw + // pointers that view the same backing memory for two purposes that are + // never live simultaneously: + // scale_buf: first SCALED_FRAME_PIXELS elements (game-frame pre-scale) + // fb_buf: full FB_PIXELS elements (ratatui RGB565 framebuffer) + // + // SAFETY: + // - `CORE0_SHARED_BUF.take()` yields the sole `&'static mut` to the + // region; we immediately convert it to a base raw pointer and let + // that `&mut` expire on the same line, so no long-lived `&mut` + // covering the region is ever stored (which would be aliasing UB). + // - Both `scale_buf` and `fb_buf` are raw pointers derived from that + // base; each is deref'd to a transient `&mut`/`&` only at the point + // of use (see `send_frame*` and `FbTarget`), and the game-frame and + // menu paths are mutually exclusive, so at most one live borrow of + // the region exists at any instant. + let base: *mut u16 = CORE0_SHARED_BUF.take().as_mut_ptr(); + let scale_buf: *mut ScaledFrame = base as *mut ScaledFrame; + let fb_buf: *mut [u16; FB_PIXELS] = base as *mut [u16; FB_PIXELS]; + let fb_target = FbTarget::new(fb_buf); + let ui = Ui::new(fb_target); + info!("display: async SPI re-initialised for game loop"); Self { spi, @@ -226,9 +262,10 @@ impl<'d> GameDisplay<'d> { dc, _rst: rst, _bl: bl, - scale_buf: CORE0_SCALE_BUF.take(), + scale_buf, + ui, + loading_filename: heapless::String::new(), prev_frame_hash: 0, - prev_menu_frame_hash: 0, } } @@ -236,17 +273,19 @@ impl<'d> GameDisplay<'d> { /// game loop. The bars are never repainted — `send_frame` only touches the /// 240×216 game area. /// - /// Also resets both frame-hash caches: - /// - `prev_menu_frame_hash` → 0: next `draw_menu` always does a full repaint. + /// Also resets frame-hash caches and drops ratatui's menu buffers: /// - `prev_frame_hash` → 0: next `send_frame` always DMA-s the game area, /// even if the native frame content is unchanged. This is required because /// `draw_menu` paints the entire 240×320 display (including the game area), /// so the game area contains stale menu pixels after the menu closes; without /// this reset, `send_frame` would see a matching hash and skip the DMA, /// leaving menu remnants visible in the game region. + /// - `ui.release_terminal()`: frees ratatui's heap-backed cell buffers while + /// the game and save-state load path are active. The next menu render + /// recreates the terminal and repaints the full screen from scratch. pub async fn draw_letterbox_bars(&mut self) { - self.prev_menu_frame_hash = 0; self.prev_frame_hash = 0; // force game-area DMA on first send_frame after menu + self.ui.release_terminal(); info!("display: drawing letterbox bars"); // Top bar: rows 0..51, colour C3 @@ -317,19 +356,21 @@ impl<'d> GameDisplay<'d> { } let (sy_start, sy_end) = Self::dirty_display_range(dirty).unwrap_or((0, 216)); self.commit_frame_hash(hash); - // Pre-scale only the dirty row range into the exclusively-owned scale buffer. - scale_native_to_rgb565_range(native, self.scale_buf, sy_start, sy_end); + // Materialize the scale buffer as a transient `&mut` from the shared raw + // pointer. SAFETY: no menu render is in flight (game and menu paths are + // mutually exclusive), so this is the only live `&mut` to the region; it + // points into `CORE0_SHARED_BUF`, not into `self`, so it does not alias + // the `&mut self.spi` / `&mut self.cs` borrows used below. + let scale_buf: &mut ScaledFrame = unsafe { &mut *self.scale_buf }; + // Pre-scale only the dirty row range into the scale buffer. + scale_native_to_rgb565_range(native, scale_buf, sy_start, sy_end); // Blocking setup: CASET + RASET + RAMWR (~2 µs). Completing synchronously // here ensures that the pixel-DMA future below is reached and armed within // the same `poll_once` call, so the DMA runs during the emulation step. self.setup_frame_range(sy_start, sy_end); - // Access `self.spi` and `self.cs` directly (not through a `&mut self` - // method) so that Rust's field-level borrow splitting allows the shared - // borrow of `self.scale_buf` (via `bytes`) and the mutable borrows of - // `self.spi` / `self.cs` to coexist. let pix_start = sy_start * 240; let pix_end = sy_end * 240; - let bytes: &[u8] = bytemuck::cast_slice(&self.scale_buf[pix_start..pix_end]); + let bytes: &[u8] = bytemuck::cast_slice(&scale_buf[pix_start..pix_end]); self.spi.write(bytes).await.ok(); self.cs.set_high(); } @@ -342,85 +383,108 @@ impl<'d> GameDisplay<'d> { /// then streams via async pixel DMA; compatible with the `poll_once` / /// emulation-overlap pattern. pub async fn send_frame_raw(&mut self, native: &NativeFrame) { - scale_native_to_rgb565_range(native, self.scale_buf, 0, 216); + // SAFETY: see `send_frame` — transient sole `&mut` to the shared region, + // disjoint from `self`'s fields. + let scale_buf: &mut ScaledFrame = unsafe { &mut *self.scale_buf }; + scale_native_to_rgb565_range(native, scale_buf, 0, 216); self.setup_frame_range(0, 216); - // Access fields directly (not via a `&mut self` method) so that the - // shared borrow of `self.scale_buf` and the mutable borrows of - // `self.spi` / `self.cs` coexist via field-level borrow splitting. - let bytes: &[u8] = bytemuck::cast_slice(self.scale_buf.as_ref()); + let bytes: &[u8] = bytemuck::cast_slice(scale_buf.as_ref()); self.spi.write(bytes).await.ok(); self.cs.set_high(); } /// Paint the full 240×320 screen with a ROM loading progress screen. /// - /// Uses a 480-byte stack buffer; no heap allocation. + /// Delegates to the ratatui UI layer. Only the dirty pixel band is + /// transferred via async SPI DMA. pub async fn draw_loading_progress(&mut self, frame: LoadingFrame<'_>) { - self.draw_rendered_rows(RenderWindow::screen(), |y, row| { - render_loading_row(&frame, y, row); - }) - .await; + self.remember_loading_filename(frame.filename); + if let Some(window) = self.ui.render_loading(&frame) { + self.flush_fb_window(window).await; + } } - /// Repaint only the loading progress bar. The title/filename stay static. + /// Repaint only the loading progress bar. + /// + /// With ratatui cell-diffing this is equivalent to a full `draw_loading_progress`: + /// the terminal only emits changed cells, and only those rows land in the dirty band. pub async fn draw_loading_bar(&mut self, progress: LoadingProgress) { - let frame = LoadingFrame::new("", progress, 0); - self.draw_rendered_rows(loading_bar_window(), |y, row| { - render_loading_row(&frame, y, row); - }) - .await; + let window = { + let frame = LoadingFrame::new(self.loading_filename.as_str(), progress, 0); + self.ui.render_loading(&frame) + }; + if let Some(window) = window { + self.flush_fb_window(window).await; + } } - /// Paint the full 240×320 screen with a menu, row by row. + /// Paint the menu, or just the changed cells if nothing moved. /// - /// Hashes the [`MenuFrame`] descriptor **before** rendering. If the frame - /// is identical to the previously rendered one (same title, items, selected - /// cursor, enabled mask, marked slot, and crash badge state), the function - /// returns immediately without issuing any DMA — the display already shows - /// the correct content. + /// ratatui's persistent terminal diffs the current frame against the + /// previous one and only emits changed cells to the DrawTarget. On + /// steady-state (no cursor move, no marquee) the dirty band is empty and + /// the function returns without issuing any DMA. /// - /// The skip is transparent to all callers; no state-machine code needs to - /// change. The cached hash is reset in `draw_letterbox_bars` so the first - /// `draw_menu` call after a game session always performs a full repaint. - /// - /// Uses a 480-byte stack buffer; no heap allocation. + /// After a game session `draw_letterbox_bars` drops the terminal buffers; + /// the next menu render recreates them, so the first `draw_menu` call + /// repaints the full screen. pub async fn draw_menu(&mut self, frame: &MenuFrame<'_>) { - let hash = Self::hash_menu_frame(frame); - if hash == self.prev_menu_frame_hash { - return; // identical frame — display already shows this content + if let Some(window) = self.ui.render_menu(frame) { + self.flush_fb_window(window).await; } - self.prev_menu_frame_hash = hash; - self.draw_rendered_rows(RenderWindow::screen(), |y, row| { - render_menu_row(frame, y, row); - }) - .await; } - /// Repaint a single menu item row. Used by marquee animation to avoid - /// full-screen refresh jitter while the rest of the ROM menu is static. - pub async fn draw_menu_item(&mut self, frame: &MenuFrame<'_>, slot: usize) { - let Some(window) = menu_item_window(slot) else { - return; - }; + /// Repaint a single menu item row. + /// + /// With ratatui cell-diffing, this is now a thin wrapper over `draw_menu`: + /// the terminal only re-emits the cells that changed. The `slot` parameter + /// is accepted for API compatibility but is not used to restrict the render + /// area — ratatui's diff is the efficient gate. + pub async fn draw_menu_item(&mut self, frame: &MenuFrame<'_>, _slot: usize) { + if let Some(window) = self.ui.render_menu(frame) { + self.flush_fb_window(window).await; + } + } - self.draw_rendered_rows(window, |y, row| { - render_menu_row(frame, y, row); - }) - .await; + /// Repaint only the text area of a menu item. + /// + /// Thin wrapper over `draw_menu` — ratatui's cell diff naturally restricts + /// the dirty band to the cells that changed (typically one row of text). + pub async fn draw_menu_item_text(&mut self, frame: &MenuFrame<'_>, _slot: usize) { + if let Some(window) = self.ui.render_menu(frame) { + self.flush_fb_window(window).await; + } } - /// Repaint only the text window inside a menu item. This keeps marquee - /// animation from touching static rows, cursor, or loaded marker pixels. - pub async fn draw_menu_item_text(&mut self, frame: &MenuFrame<'_>, slot: usize) { - let marked = frame.marked == Some(slot); - let Some(window) = menu_item_text_window(slot, marked) else { + // --- Framebuffer flush helper --- + + /// DMA the rows in `window` from the ratatui Rgb565 framebuffer to the panel. + /// + /// Reads each row from `FbTarget` (via `Ui`) as big-endian bytes (480 bytes + /// per row) then streams via async SPI. The same CASET/RASET/RAMWR setup + /// covers the entire band; the ILI9341 auto-increments its write pointer. + /// + /// Each row is read into a 480-byte stack buffer before the `.await` so that + /// the borrow of `self.ui` is released before `self.spi` is borrowed. + async fn flush_fb_window(&mut self, window: RenderWindow) { + if window.is_empty() { return; - }; + } + self.set_window(window); + self.write_command(0x2C, &[]); + self.dc.set_high(); + self.cs.set_low(); - self.draw_rendered_rows(window, |y, row| { - render_menu_row(frame, y, row); - }) - .await; + let mut row_buf = [0u8; ROW_BYTES]; + for y in window.y_start..window.y_end { + // Read row into local buffer (borrows self.ui, released before await). + self.ui + .terminal_backend_display_mut() + .read_row_be(y, &mut row_buf); + // Borrow of self.ui is now released; we can borrow self.spi. + self.spi.write(&row_buf).await.ok(); + } + self.cs.set_high(); } // --- differential DMA helpers --- @@ -523,51 +587,13 @@ impl<'d> GameDisplay<'d> { self.prev_frame_hash = hash; } - /// Compute a fast hash of a [`MenuFrame`] descriptor. - /// - /// Hashes each field that affects rendering: title text, item strings, - /// cursor position (`selected`), animation counter (`marquee_frame`), - /// enabled mask, marked slot, and crash badge flag. - /// - /// Feeds each field's bytes through [`knuth_hash`], mixing the results - /// together with the same Knuth multiplicative step. The result is - /// non-zero as long as any field contains non-zero bytes (seeded from - /// `knuth_hash`'s `0xdead_beef` seed), keeping 0 safe as the - /// "never-rendered" / "invalidated" sentinel stored in - /// `prev_menu_frame_hash`. - fn hash_menu_frame(frame: &MenuFrame<'_>) -> u32 { - const M: u32 = 0x9e37_79b9; - // Start from the title bytes. - let mut h = Self::knuth_hash(frame.title.as_bytes()); - // Mix in each item string. - for item in frame.items { - h ^= Self::knuth_hash(item.as_bytes()); - h = h.wrapping_mul(M); - h ^= h >> 16; - } - // Mix in selected cursor index. - h ^= frame.selected as u32; - h = h.wrapping_mul(M); - h ^= h >> 16; - // Mix in marquee animation counter. - h ^= frame.marquee_frame; - h = h.wrapping_mul(M); - h ^= h >> 16; - // Mix in the enabled-flag bitmask (one bool per item). - for &enabled in frame.enabled { - h ^= enabled as u32; - h = h.wrapping_mul(M); - h ^= h >> 16; + fn remember_loading_filename(&mut self, filename: &str) { + self.loading_filename.clear(); + for ch in filename.chars() { + if self.loading_filename.push(ch).is_err() { + break; + } } - // Mix in the "currently loaded" marker (None → 0, Some(n) → n+1). - h ^= frame.marked.map_or(0u32, |n| n as u32 + 1); - h = h.wrapping_mul(M); - h ^= h >> 16; - // Mix in crash-badge flag. - h ^= frame.crash_pending as u32; - h = h.wrapping_mul(M); - h ^= h >> 16; - h } // --- helpers --- @@ -659,37 +685,6 @@ impl<'d> GameDisplay<'d> { /// Render and DMA all rows in `window`. /// - /// For each row, calls `render_row(y, &mut row_buf)` to fill a 480-byte - /// pixel buffer, then streams the window's x-column slice to the display - /// via async SPI DMA. A single CASET/RASET/RAMWR setup covers the entire - /// window; the ILI9341 auto-increments its write pointer across rows. - /// - /// Frame-level deduplication (whole-menu skip when nothing changed) is - /// handled by the callers — see [`draw_menu`]. This function always - /// renders and transfers every row it is given. - async fn draw_rendered_rows(&mut self, window: RenderWindow, mut render_row: F) - where - F: FnMut(u16, &mut [u8; ROW_BYTES]), - { - if window.is_empty() { - return; - } - - self.set_window(window); - self.write_command(0x2C, &[]); - self.dc.set_high(); - self.cs.set_low(); - - let mut row = [0u8; ROW_BYTES]; - let byte_range = window.byte_range(); - for y in window.y_start..window.y_end { - render_row(y, &mut row); - self.spi.write(&row[byte_range.clone()]).await.ok(); - } - - self.cs.set_high(); - } - async fn fill_rect_raw(&mut self, n_pixels: usize, pixel_be: &[u8; 2]) { // Send 240 pixels (480 bytes) per row to keep the stack usage bounded. let mut row = [0u8; ROW_BYTES]; diff --git a/platform/pico2w/src/display/mod.rs b/platform/pico2w/src/display/mod.rs index cf5ed27..3b6ceef 100644 --- a/platform/pico2w/src/display/mod.rs +++ b/platform/pico2w/src/display/mod.rs @@ -14,15 +14,31 @@ pub mod fb; pub mod font; #[cfg(target_arch = "arm")] pub mod hw; -mod loading; -mod menu; +// --------------------------------------------------------------------------- +// ratatui / mousefood UI layer +// --------------------------------------------------------------------------- +// eg_target is used by the ARM firmware and is host-compiled for framebuffer +// adapter tests. +pub mod eg_target; +// ui.rs compiles on both ARM and host; ARM-specific parts are gated inside. +pub mod ui; +// `loading` is retained for the `LoadingFrame` / `LoadingProgress` descriptor +// types consumed by the ratatui `ui` layer; `menu` / `text` are retained only +// for host-side pixel tests. The firmware renders through `ui`, so the old +// `render_*_row` paths are dead on ARM. TODO: relocate the descriptor types and +// delete the dead renderers (`text`, `font`, `render_*_row`). +pub mod loading; +pub mod menu; mod text; pub use loading::{loading_bar_window, render_loading_row, LoadingFrame, LoadingProgress}; -pub use menu::{ - menu_item_needs_marquee, menu_item_text_window, menu_item_window, render_menu_row, - MENU_MARQUEE_REDRAW_FRAMES, -}; +pub use menu::{menu_item_text_window, menu_item_window, render_menu_row}; + +// `menu_item_needs_marquee` and `MENU_MARQUEE_REDRAW_FRAMES` come from the +// ratatui ui module on both ARM and host (column-based logic). +// The old pixel-based versions in menu.rs are kept for host test coverage only +// and remain accessible as `display::menu::menu_item_needs_marquee` etc. +pub use ui::{menu_item_needs_marquee, MENU_MARQUEE_REDRAW_FRAMES}; use core::ops::Range; use embedded_graphics::draw_target::DrawTarget; diff --git a/platform/pico2w/src/display/ui.rs b/platform/pico2w/src/display/ui.rs new file mode 100644 index 0000000..d1ee6c2 --- /dev/null +++ b/platform/pico2w/src/display/ui.rs @@ -0,0 +1,849 @@ +//! ratatui UI layer for menus and loading screens. +//! +//! Compiles on both ARM (embedded) and host (tests). ARM-specific parts +//! — the `FbTarget` DrawTarget, `Ui` struct, and `mousefood` colour theme — +//! are gated by `#[cfg(target_arch = "arm")]`. +//! +//! `draw_menu` / `draw_loading` are pure ratatui render functions compiled for +//! ARM firmware and host unit tests; the host test suite exercises them via +//! `TestBackend`. + +extern crate alloc; + +#[cfg(any(target_arch = "arm", test, feature = "std"))] +use alloc::string::ToString; + +#[cfg(any(target_arch = "arm", test, feature = "std"))] +use ratatui::{ + layout::{Alignment, Constraint, Direction, Layout, Rect}, + style::{Color, Modifier, Style}, + text::{Line, Span}, + widgets::{Block, Borders, Gauge, Paragraph, Widget}, + Frame, +}; + +#[cfg(target_arch = "arm")] +use ratatui::Terminal; + +#[cfg(any(target_arch = "arm", test, feature = "std"))] +use crate::display::LoadingFrame; +#[cfg(any(target_arch = "arm", test, feature = "std"))] +use crate::menu::MenuFrame; + +// ARM-specific imports — mousefood + FbTarget +#[cfg(target_arch = "arm")] +use super::eg_target::FbTarget; +#[cfg(target_arch = "arm")] +use mousefood::{ + embedded_graphics::{ + mono_font::ascii::FONT_8X13, + pixelcolor::{Rgb565, Rgb888}, + prelude::RgbColor, + }, + ColorTheme, EmbeddedBackend, EmbeddedBackendConfig, TerminalAlignment, +}; + +// --------------------------------------------------------------------------- +// Marquee constants +// --------------------------------------------------------------------------- + +/// Columns visible in the item text area (30 cols total, minus cursor+gap). +/// +/// The embedded terminal uses a 30-column grid (240 px / 8 px font width). +/// Regular rows reserve 2 columns for the cursor and, for marked ROMs, 2 +/// columns for the marker. +pub const MARQUEE_TEXT_COLS: usize = 28; +pub const MARQUEE_HOLD_FRAMES: u32 = 30; +pub const MARQUEE_FRAMES_PER_STEP: u32 = 1; +/// How many animation-tick calls between redraws (mirrors menu.rs constant). +pub const MENU_MARQUEE_REDRAW_FRAMES: u32 = MARQUEE_FRAMES_PER_STEP; + +/// Return true if `text` is too long to fit without scrolling. +/// +/// `marked` items reserve two columns for the `*` marker, shrinking the window. +pub fn menu_item_needs_marquee(text: &str, marked: bool) -> bool { + let cols = if marked { + MARQUEE_TEXT_COLS.saturating_sub(2) + } else { + MARQUEE_TEXT_COLS + }; + text.len() > cols +} + +/// Compute the horizontal scroll offset in *characters* for a marquee. +/// +/// Mirrors the pixel-level logic from `display/menu.rs::marquee_scroll_px` +/// but operates in column units. +pub fn marquee_char_offset(text: &str, marquee_frame: u32, cols: usize) -> usize { + let text_len = text.len(); + if text_len <= cols { + return 0; + } + // Gap: 3 blank characters between end and re-start of the scroll loop. + const GAP: usize = 3; + let period = text_len + GAP; + let scroll_steps = period; // 1 step = 1 char + let scroll_frames = (scroll_steps as u32).saturating_mul(MARQUEE_FRAMES_PER_STEP); + let phase = marquee_frame % (MARQUEE_HOLD_FRAMES + scroll_frames); + if phase < MARQUEE_HOLD_FRAMES { + 0 + } else { + ((phase - MARQUEE_HOLD_FRAMES) / MARQUEE_FRAMES_PER_STEP) as usize % period + } +} + +// --------------------------------------------------------------------------- +// MarqueeLine widget +// --------------------------------------------------------------------------- + +/// A single-row widget that renders a scrolling text line. +/// +/// If the text fits within `cols`, it is rendered without scrolling. +/// Otherwise `offset` characters are skipped from the start and the text +/// wraps (period = text + 3-char gap). +#[cfg(any(target_arch = "arm", test, feature = "std"))] +struct MarqueeLine<'a> { + text: &'a str, + offset: usize, + cols: usize, + style: Style, +} + +#[cfg(any(target_arch = "arm", test, feature = "std"))] +impl<'a> MarqueeLine<'a> { + fn new(text: &'a str, offset: usize, cols: usize, style: Style) -> Self { + Self { + text, + offset, + cols, + style, + } + } +} + +#[cfg(any(target_arch = "arm", test, feature = "std"))] +impl Widget for MarqueeLine<'_> { + fn render(self, area: Rect, buf: &mut ratatui::prelude::Buffer) { + if area.height == 0 || area.width == 0 || self.text.is_empty() { + return; + } + let cols = area.width.min(self.cols as u16) as usize; + let text = self.text; + let text_len = text.len(); + let text_bytes = text.as_bytes(); + + for col in 0..cols { + let src_char = if text_len <= cols { + // No scrolling: render text left-aligned, pad with space. + if col < text_len { + text_bytes[col] + } else { + b' ' + } + } else { + // Scrolling: wrap around with 3-char gap. + const GAP: usize = 3; + let period = text_len + GAP; + let src = (col + self.offset) % period; + if src < text_len { + text_bytes[src] + } else { + b' ' + } + }; + let x = area.x + col as u16; + if x < buf.area.x + buf.area.width { + let cell = buf.cell_mut(ratatui::layout::Position { x, y: area.y }); + if let Some(cell) = cell { + let ch = char::from(src_char); + cell.set_char(ch); + cell.set_style(self.style); + } + } + } + } +} + +// --------------------------------------------------------------------------- +// DMG palette as Rgb888 (ARM-only: used for ColorTheme mapping) +// --------------------------------------------------------------------------- + +#[cfg(target_arch = "arm")] +const DMG_C0: Rgb888 = Rgb888::new(0xE0, 0xF8, 0xD0); +#[cfg(target_arch = "arm")] +const DMG_C1: Rgb888 = Rgb888::new(0x88, 0xC0, 0x70); +#[cfg(target_arch = "arm")] +const DMG_C2: Rgb888 = Rgb888::new(0x34, 0x68, 0x56); +#[cfg(target_arch = "arm")] +const DMG_C3: Rgb888 = Rgb888::new(0x08, 0x18, 0x20); + +/// Build a `ColorTheme` that maps ANSI terminal colours to the DMG palette. +#[cfg(target_arch = "arm")] +fn dmg_theme() -> ColorTheme { + ColorTheme { + foreground: DMG_C0, + background: DMG_C3, + white: DMG_C0, + black: DMG_C3, + red: Rgb888::RED, + green: DMG_C1, + yellow: Rgb888::YELLOW, + blue: Rgb888::BLUE, + magenta: Rgb888::MAGENTA, + cyan: DMG_C1, + light_red: Rgb888::RED, + light_green: DMG_C0, + light_yellow: Rgb888::YELLOW, + light_blue: DMG_C1, + light_magenta: Rgb888::MAGENTA, + light_cyan: DMG_C1, + gray: DMG_C2, + dark_gray: DMG_C3, + } +} + +// --------------------------------------------------------------------------- +// Ui struct (ARM-only — owns FbTarget + Terminal) +// --------------------------------------------------------------------------- + +/// Persistent ratatui terminal + FbTarget. +/// +/// Owns the `Terminal>`. +/// `GameDisplay` holds a `Ui` inside `GameDisplay::ui` and calls +/// `render_menu` / `render_loading`. +#[cfg(target_arch = "arm")] +pub struct Ui { + fb: *mut FbTarget, + terminal: Option>>, +} + +#[cfg(target_arch = "arm")] +impl Ui { + /// Construct from a freshly-claimed static framebuffer. + pub fn new(fb: FbTarget) -> Self { + // Leak `fb` into a `&'static mut FbTarget` by boxing it and leaking. + // SAFETY: `GameDisplay` is the sole owner of this Ui; it is constructed + // once in `new_after_splash` and lives for the lifetime of the program. + let fb_ref: &'static mut FbTarget = alloc::boxed::Box::leak(alloc::boxed::Box::new(fb)); + Self { + fb: fb_ref as *mut FbTarget, + terminal: None, + } + } + + fn terminal_mut(&mut self) -> &mut Terminal> { + if self.terminal.is_none() { + // SAFETY: `self.terminal` is the only owner of an EmbeddedBackend + // borrowing this FbTarget. We only materialize a new &'static mut + // when no terminal exists; `release_terminal` drops the previous + // backend before this path can run again. + let fb_ref: &'static mut FbTarget = unsafe { &mut *self.fb }; + + let config = EmbeddedBackendConfig { + color_theme: dmg_theme(), + font_regular: FONT_8X13, + vertical_alignment: TerminalAlignment::Center, + flush_callback: alloc::boxed::Box::new(|_| {}), // we flush manually + ..EmbeddedBackendConfig::default() + }; + + let backend = EmbeddedBackend::new(fb_ref, config); + self.terminal = Some(Terminal::new(backend).expect("ratatui Terminal::new")); + } + self.terminal.as_mut().expect("terminal was just created") + } + + /// Force a full-screen repaint on the next `render_*` call. + /// + /// Call from `draw_letterbox_bars` after returning from a game session so + /// that stale game pixels are overwritten. + pub fn mark_full_repaint(&mut self) { + if let Some(terminal) = self.terminal.as_mut() { + terminal.backend_mut().display_mut().mark_all_dirty(); + // Also clear ratatui's previous-frame buffer so it re-emits every cell. + let _ = terminal.clear(); + } + } + + /// Drop ratatui's heap-backed cell buffers before entering game mode. + pub fn release_terminal(&mut self) { + self.terminal = None; + } + + /// Render a [`MenuFrame`] into the framebuffer and return the dirty band. + /// + /// Returns `None` when ratatui's cell-diff determined nothing changed. + pub fn render_menu(&mut self, frame: &MenuFrame<'_>) -> Option { + let terminal = self.terminal_mut(); + let _ = terminal.draw(|f| draw_menu(f, frame)); + terminal.backend_mut().display_mut().take_dirty() + } + + /// Render a [`LoadingFrame`] into the framebuffer and return the dirty band. + pub fn render_loading(&mut self, frame: &LoadingFrame<'_>) -> Option { + let terminal = self.terminal_mut(); + let _ = terminal.draw(|f| draw_loading(f, frame)); + terminal.backend_mut().display_mut().take_dirty() + } + + /// Borrow the `FbTarget` for row-by-row DMA flushing. + /// + /// Called by `GameDisplay::flush_fb_window` to read pixel rows. + pub fn terminal_backend_display_mut(&mut self) -> &mut FbTarget { + self.terminal + .as_mut() + .expect("framebuffer flush requires an active terminal") + .backend_mut() + .display_mut() + } +} + +// --------------------------------------------------------------------------- +// Menu render function (works on both ARM and host) +// --------------------------------------------------------------------------- + +#[cfg(any(target_arch = "arm", test, feature = "std"))] +pub fn draw_menu(f: &mut Frame, frame: &MenuFrame<'_>) { + let area = f.area(); + + const HEADER_ROWS: u16 = 3; + const ITEM_ROWS: u16 = 2; + const FOOTER_ROWS: u16 = 3; + const CONTENT_MAX_COLS: u16 = 30; + + f.render_widget( + Block::default().style(Style::default().bg(Color::Black)), + area, + ); + + let footer_h = FOOTER_ROWS.min(area.height); + let footer_y = area.y + area.height.saturating_sub(footer_h); + let header_h = HEADER_ROWS.min(footer_y.saturating_sub(area.y)); + let header_area = Rect::new(area.x, area.y, area.width, header_h); + let items_bottom = footer_y; + let items_area = Rect::new( + area.x, + area.y + header_h, + area.width, + items_bottom.saturating_sub(area.y + header_h), + ); + let footer_area = Rect::new(area.x, footer_y, area.width, footer_h); + let content_w = area.width.min(CONTENT_MAX_COLS).max(1); + let content_x = area.x + area.width.saturating_sub(content_w) / 2; + + // --- Header --- + if header_area.height > 0 { + let title_style = Style::default() + .fg(Color::White) + .bg(Color::Black) + .add_modifier(Modifier::BOLD); + let title_text = if frame.crash_pending { + alloc::format!("{} !", frame.title) + } else { + frame.title.to_string() + }; + let title_line = Line::from(Span::styled(title_text, title_style)).centered(); + let header = Paragraph::new(title_line) + .block( + Block::default() + .borders(Borders::BOTTOM) + .border_style(Style::default().fg(Color::Gray)), + ) + .alignment(Alignment::Center); + f.render_widget(header, header_area); + } + + // --- Items --- + if frame.selected >= frame.items.len() { + draw_info_lines(f, frame, items_area, content_x, content_w); + } else { + let rendered_items = frame.items.len() as u16; + let item_block_h = rendered_items + .saturating_mul(ITEM_ROWS) + .min(items_area.height); + let mut item_y = items_area.y + items_area.height.saturating_sub(item_block_h) / 2; + + for (i, &item_text) in frame.items.iter().enumerate() { + if item_y >= items_bottom { + break; + } + + let item_h = ITEM_ROWS.min(items_bottom - item_y); + let item_area = Rect::new(content_x, item_y, content_w, item_h); + item_y = item_y.saturating_add(ITEM_ROWS); + + let selected = i == frame.selected; + let enabled = frame.enabled.get(i).copied().unwrap_or(true); + let marked = frame.marked == Some(i); + + let row_bg = if selected { Color::Gray } else { Color::Black }; + // Disabled items use C2 (Color::Gray) so they stay visible on the + // C3 (Color::Black) unselected background — matching the old renderer. + let text_fg = if !enabled { + Color::Gray + } else if selected { + Color::White + } else { + Color::Green + }; + + if selected { + f.render_widget( + Block::default().style(Style::default().bg(row_bg)), + item_area, + ); + } + + let text_row_y = item_area.y + item_area.height / 2; + let line_area = Rect::new(item_area.x, text_row_y, item_area.width, 1); + let marker_w = if marked { 2u16 } else { 0u16 }; + let inner = Layout::default() + .direction(Direction::Horizontal) + .constraints([ + Constraint::Length(2), + Constraint::Min(1), + Constraint::Length(marker_w), + ]) + .split(line_area); + + let cursor_area = inner[0]; + let text_area = inner[1]; + let marker_area = inner[2]; + + let cursor_sym = if selected { ">" } else { " " }; + let cursor_span = Span::styled(cursor_sym, Style::default().fg(text_fg).bg(row_bg)); + f.render_widget(Paragraph::new(Line::from(cursor_span)), cursor_area); + + let text_style = Style::default().fg(text_fg).bg(row_bg); + let marquee_cols = text_area.width as usize; + let needs_scroll = selected && item_text.len() > marquee_cols; + if needs_scroll { + let offset = marquee_char_offset(item_text, frame.marquee_frame, marquee_cols); + let marquee = MarqueeLine::new(item_text, offset, marquee_cols, text_style); + f.render_widget(marquee, text_area); + } else { + let visible_cols = text_area.width as usize; + let visible = truncate_to_cols(item_text, visible_cols); + f.render_widget( + Paragraph::new(Line::from(Span::styled(visible, text_style))), + text_area, + ); + } + + if marked { + let marker_span = Span::styled("*", Style::default().fg(Color::White).bg(row_bg)); + f.render_widget(Paragraph::new(Line::from(marker_span)), marker_area); + } + } + } + + // --- Footer --- + if footer_area.height > 0 { + let footer_style = Style::default().fg(Color::Green).bg(Color::Black); + let footer_text = if frame.selected >= frame.items.len() { + "B:BACK" + } else { + "A:SELECT B:BACK" + }; + let footer_line = Line::from(Span::styled(footer_text, footer_style)).centered(); + let footer = Paragraph::new(footer_line) + .block( + Block::default() + .borders(Borders::TOP) + .border_style(Style::default().fg(Color::Gray)), + ) + .alignment(Alignment::Center); + f.render_widget(footer, footer_area); + } +} + +#[cfg(any(target_arch = "arm", test, feature = "std"))] +fn draw_info_lines( + f: &mut Frame, + frame: &MenuFrame<'_>, + items_area: Rect, + content_x: u16, + content_w: u16, +) { + let line_count = frame.items.len() as u16; + if line_count == 0 || items_area.height == 0 { + return; + } + + let block_h = line_count.min(items_area.height); + let first_y = items_area.y + items_area.height.saturating_sub(block_h) / 2; + let style = Style::default().fg(Color::Green).bg(Color::Black); + + for (i, &line) in frame.items.iter().enumerate() { + let y = first_y + i as u16; + if y >= items_area.y + items_area.height { + break; + } + let visible = truncate_to_cols(line, content_w as usize); + let area = Rect::new(content_x, y, content_w, 1); + f.render_widget( + Paragraph::new(Line::from(Span::styled(visible, style))).alignment(Alignment::Center), + area, + ); + } +} + +#[cfg(any(target_arch = "arm", test, feature = "std"))] +fn truncate_to_cols(text: &str, cols: usize) -> &str { + if text.len() <= cols { + return text; + } + match text.char_indices().nth(cols) { + Some((idx, _)) => &text[..idx], + None => text, + } +} + +// --------------------------------------------------------------------------- +// Loading render function (works on both ARM and host) +// --------------------------------------------------------------------------- + +#[cfg(any(target_arch = "arm", test, feature = "std"))] +pub fn draw_loading(f: &mut Frame, frame: &LoadingFrame<'_>) { + let area = f.area(); + + // Clear background + let bg = Block::default().style(Style::default().bg(Color::Black)); + f.render_widget(bg, area); + + // Split: header / spacer / filename / spacer / progress + let chunks = Layout::default() + .direction(Direction::Vertical) + .constraints([ + Constraint::Length(3), + Constraint::Min(1), + Constraint::Length(3), + Constraint::Length(1), + Constraint::Length(3), + Constraint::Min(1), + ]) + .split(area); + + let header_area = chunks[0]; + let filename_area = chunks[2]; + let gauge_area = chunks[4]; + + // --- Header --- + let title_style = Style::default() + .fg(Color::White) + .bg(Color::Black) + .add_modifier(Modifier::BOLD); + let header = Paragraph::new(Line::from(Span::styled("LOADING", title_style)).centered()).block( + Block::default() + .borders(Borders::BOTTOM) + .border_style(Style::default().fg(Color::Gray)), + ); + f.render_widget(header, header_area); + + // --- Filename --- + let filename_style = Style::default().fg(Color::Green).bg(Color::Black); + let filename = frame.filename; + let filename_cols = filename_area.width as usize; + let visible_name: &str = if filename.len() > filename_cols { + &filename[..filename_cols] + } else { + filename + }; + let filename_widget = + Paragraph::new(Line::from(Span::styled(visible_name, filename_style)).centered()) + .block(Block::default()); + f.render_widget(filename_widget, filename_area); + + // --- Progress gauge --- + let pct = if frame.progress.total_banks == 0 { + 0u16 + } else { + ((frame.progress.banks_done as u64 * 100) / frame.progress.total_banks as u64).min(100) + as u16 + }; + let gauge = Gauge::default() + .gauge_style(Style::default().fg(Color::White).bg(Color::Gray)) + .percent(pct) + .label(Span::styled( + alloc::format!("{pct}%"), + Style::default().fg(Color::Black), + )); + f.render_widget(gauge, gauge_area); +} + +// --------------------------------------------------------------------------- +// Tests (host-only via ratatui TestBackend) +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::display::loading::LoadingProgress; + use crate::menu::MenuFrame; + use ratatui::backend::TestBackend; + use ratatui::Terminal; + + fn make_terminal(width: u16, height: u16) -> Terminal { + Terminal::new(TestBackend::new(width, height)).unwrap() + } + + fn make_frame<'a>( + title: &'a str, + items: &'a [&'a str], + selected: usize, + enabled: &'a [bool], + marked: Option, + crash_pending: bool, + marquee_frame: u32, + ) -> MenuFrame<'a> { + MenuFrame { + title, + items, + selected, + enabled, + marked, + crash_pending, + marquee_frame, + } + } + + fn buf_has_symbol(buf: &ratatui::prelude::Buffer, sym: &str) -> bool { + (0..buf.area.height).any(|y| { + (0..buf.area.width).any(|x| { + buf.cell(ratatui::layout::Position { x, y }) + .map_or(false, |c| c.symbol() == sym) + }) + }) + } + + /// True if any cell renders `sym` with foreground `fg`. + fn buf_has_symbol_with_fg(buf: &ratatui::prelude::Buffer, sym: &str, fg: Color) -> bool { + (0..buf.area.height).any(|y| { + (0..buf.area.width).any(|x| { + buf.cell(ratatui::layout::Position { x, y }) + .map_or(false, |c| c.symbol() == sym && c.fg == fg) + }) + }) + } + + fn buf_to_text(buf: &ratatui::prelude::Buffer) -> alloc::string::String { + (0..buf.area.height) + .map(|y| { + (0..buf.area.width) + .map(|x| { + buf.cell(ratatui::layout::Position { x, y }) + .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' ')) + }) + .collect::() + }) + .collect::>() + .join("\n") + } + + fn row_text(buf: &ratatui::prelude::Buffer, y: u16) -> alloc::string::String { + (0..buf.area.width) + .map(|x| { + buf.cell(ratatui::layout::Position { x, y }) + .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' ')) + }) + .collect() + } + + fn row_has_bg(buf: &ratatui::prelude::Buffer, y: u16, bg: Color) -> bool { + (0..buf.area.width).any(|x| { + buf.cell(ratatui::layout::Position { x, y }) + .map_or(false, |c| c.bg == bg) + }) + } + + #[test] + fn cursor_symbol_present_on_selected_item() { + let items = ["RESUME", "SAVE", "LOAD"]; + let enabled = [true, true, true]; + let menu_frame = make_frame("PAUSED", &items, 0, &enabled, None, false, 0); + + let mut terminal = make_terminal(40, 20); + terminal.draw(|f| draw_menu(f, &menu_frame)).unwrap(); + let buf = terminal.backend().buffer().clone(); + assert!( + buf_has_symbol(&buf, ">"), + "cursor '>' should appear for selected item" + ); + } + + #[test] + fn disabled_item_uses_visible_muted_fg() { + let items = ["RESUME", "LOAD"]; + let enabled = [true, false]; // LOAD is disabled, unselected + let menu_frame = make_frame("PAUSED", &items, 0, &enabled, None, false, 0); + + let mut terminal = make_terminal(40, 20); + terminal.draw(|f| draw_menu(f, &menu_frame)).unwrap(); + let buf = terminal.backend().buffer().clone(); + // The disabled, unselected LOAD item must use Gray (C2), NOT DarkGray + // (C3) — DarkGray maps to the same colour as the unselected row + // background and would be invisible. Check the 'L' glyph specifically + // (the footer's 'L' in "SELECT" is Green, so this is unambiguous). + assert!( + buf_has_symbol_with_fg(&buf, "L", Color::Gray), + "disabled LOAD item should render its text with the visible Gray fg" + ); + } + + #[test] + fn marker_star_present_for_marked_item() { + let items = ["ROM.GB"]; + let enabled = [true]; + let menu_frame = make_frame("ROMS", &items, 0, &enabled, Some(0), false, 0); + + let mut terminal = make_terminal(40, 20); + terminal.draw(|f| draw_menu(f, &menu_frame)).unwrap(); + let buf = terminal.backend().buffer().clone(); + assert!( + buf_has_symbol(&buf, "*"), + "marked item should show '*' marker" + ); + } + + #[test] + fn crash_badge_shows_exclamation_in_title() { + let items = ["ROMS"]; + let enabled = [true]; + let menu_frame = make_frame("MAIN", &items, 0, &enabled, None, true, 0); + + let mut terminal = make_terminal(40, 20); + terminal.draw(|f| draw_menu(f, &menu_frame)).unwrap(); + let buf = terminal.backend().buffer().clone(); + assert!( + buf_has_symbol(&buf, "!"), + "crash_pending should show '!' in header" + ); + } + + #[test] + fn footer_contains_help_text() { + let items = ["ROM"]; + let enabled = [true]; + let menu_frame = make_frame("TEST", &items, 0, &enabled, None, false, 0); + + let mut terminal = make_terminal(40, 20); + terminal.draw(|f| draw_menu(f, &menu_frame)).unwrap(); + let buf = terminal.backend().buffer().clone(); + let text = buf_to_text(&buf); + assert!( + text.contains("A:SELECT"), + "footer should contain 'A:SELECT', got:\n{text}" + ); + } + + #[test] + fn short_menus_use_compact_fixed_item_rows() { + let items = ["ROMS", "SETTINGS"]; + let enabled = [true, true]; + let menu_frame = make_frame("MAIN", &items, 0, &enabled, None, false, 0); + + let mut terminal = make_terminal(30, 24); + terminal.draw(|f| draw_menu(f, &menu_frame)).unwrap(); + let buf = terminal.backend().buffer().clone(); + + assert!(row_text(&buf, 11).contains("ROMS")); + assert!(row_text(&buf, 13).contains("SETTINGS")); + for y in 3..10 { + let row = row_text(&buf, y); + assert!( + !row.contains("ROMS") && !row.contains("SETTINGS"), + "item text leaked into top spacer row {y}: {row:?}" + ); + } + for y in 15..21 { + let row = row_text(&buf, y); + assert!( + !row.contains("ROMS") && !row.contains("SETTINGS"), + "item text leaked into bottom spacer row {y}: {row:?}" + ); + } + } + + #[test] + fn selected_last_rom_row_does_not_absorb_footer_spacer() { + let items = ["A", "B", "C", "D", "E", "F", "G"]; + let enabled = [true; 7]; + let menu_frame = make_frame("ROMS", &items, 6, &enabled, None, false, 0); + + let mut terminal = make_terminal(30, 24); + terminal.draw(|f| draw_menu(f, &menu_frame)).unwrap(); + let buf = terminal.backend().buffer().clone(); + + assert!(row_has_bg(&buf, 17, Color::Gray)); + assert!(row_has_bg(&buf, 18, Color::Gray)); + assert!( + !row_has_bg(&buf, 19, Color::Gray), + "selected last item should stop after its fixed 2-row band" + ); + } + + #[test] + fn selected_long_item_uses_centered_row_width() { + let long_name = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.GB"; + let items = [long_name]; + let enabled = [true]; + let menu_frame = make_frame("ROMS", &items, 0, &enabled, None, false, 0); + + let mut terminal = make_terminal(30, 24); + terminal.draw(|f| draw_menu(f, &menu_frame)).unwrap(); + let buf = terminal.backend().buffer().clone(); + let text = buf_to_text(&buf); + + assert!( + text.contains("ABCDEFGHIJKLMNOPQRSTUVWXYZ01"), + "selected row should use the full 28-column text window, got:\n{text}" + ); + } + + #[test] + fn marquee_offset_changes_render() { + let long_name = "AVERYLONGROMNAMETHATSHOULDSCROLLFORALONGTIME.GB"; + let items = [long_name]; + let enabled = [true]; + let frame0 = make_frame("ROMS", &items, 0, &enabled, None, false, 0); + let frame_later = make_frame( + "ROMS", + &items, + 0, + &enabled, + None, + false, + MARQUEE_HOLD_FRAMES + 5, + ); + + let mut terminal0 = make_terminal(40, 20); + terminal0.draw(|f| draw_menu(f, &frame0)).unwrap(); + let buf0 = terminal0.backend().buffer().clone(); + + let mut terminal1 = make_terminal(40, 20); + terminal1.draw(|f| draw_menu(f, &frame_later)).unwrap(); + let buf1 = terminal1.backend().buffer().clone(); + + let text0 = buf_to_text(&buf0); + let text1 = buf_to_text(&buf1); + assert!( + text0 != text1, + "marquee should produce different output at different frames" + ); + } + + #[test] + fn loading_screen_shows_percentage_or_loading_text() { + let progress = LoadingProgress::new(1, 4); // 25% + let frame = LoadingFrame::new("ROM.GB", progress, 0); + + let mut terminal = make_terminal(40, 20); + terminal.draw(|f| draw_loading(f, &frame)).unwrap(); + let buf = terminal.backend().buffer().clone(); + let text = buf_to_text(&buf); + assert!( + text.contains("25%") || text.contains("LOADING"), + "loading screen should show percentage or LOADING, got:\n{text}" + ); + } +} diff --git a/platform/pico2w/src/flash_rom.rs b/platform/pico2w/src/flash_rom.rs index 98baee8..ff58c71 100644 --- a/platform/pico2w/src/flash_rom.rs +++ b/platform/pico2w/src/flash_rom.rs @@ -8,7 +8,9 @@ use rustyboy_core::memory::RomReader; use rustyboy_core::storage::{RomHasher, RomId}; pub const FLASH_CAPACITY_BYTES: usize = 4 * 1024 * 1024; -pub const FIRMWARE_SLOT_BYTES: usize = 512 * 1024; +/// Firmware image slot size. Must match the `FLASH LENGTH` in `memory.x`. +/// Expanded from 512 KiB to 640 KiB to accommodate ratatui/mousefood UI layer. +pub const FIRMWARE_SLOT_BYTES: usize = 640 * 1024; pub const ROM_METADATA_BYTES: usize = ERASE_SIZE; pub const ROM_SLOT_OFFSET: usize = FIRMWARE_SLOT_BYTES; pub const ROM_DATA_OFFSET: usize = ROM_SLOT_OFFSET + ROM_METADATA_BYTES; diff --git a/platform/pico2w/src/input.rs b/platform/pico2w/src/input.rs index e016070..50d6e9d 100644 --- a/platform/pico2w/src/input.rs +++ b/platform/pico2w/src/input.rs @@ -18,7 +18,7 @@ use embassy_time::Instant; use rustyboy_core::cpu::peripheral::joypad::Button; /// Debounce window in milliseconds. -const DEBOUNCE_MS: u64 = 10; +const DEBOUNCE_MS: u64 = 5; /// How long Start+Select must be held together to trigger the menu combo. const MENU_HOLD_MS: u64 = 1_000; @@ -354,10 +354,10 @@ mod tests { ..Default::default() }; - // Raw changes at t=0, stable at t=5 — not yet past 10 ms window + // Raw changes at t=0, stable at t=4 — not yet past the 5 ms window. state.update(pressed, 0); - let (deb, _) = state.update(pressed, 5); - assert!(!deb.a, "should not be debounced yet at 5 ms"); + let (deb, _) = state.update(pressed, 4); + assert!(!deb.a, "should not be debounced yet at 4 ms"); } #[test] @@ -369,8 +369,8 @@ mod tests { }; state.update(pressed, 0); - let (deb, _) = state.update(pressed, 10); - assert!(deb.a, "should be debounced after 10 ms"); + let (deb, _) = state.update(pressed, 5); + assert!(deb.a, "should be debounced after 5 ms"); } #[test] diff --git a/platform/pico2w/src/state/in_game_menu.rs b/platform/pico2w/src/state/in_game_menu.rs index 86cd98e..61e023a 100644 --- a/platform/pico2w/src/state/in_game_menu.rs +++ b/platform/pico2w/src/state/in_game_menu.rs @@ -7,7 +7,7 @@ use rustyboy_pico2w::menu::{InGameMenu, MenuEffect, MenuInput, MenuLogic}; use rustyboy_pico2w::multicore::PicoGameBoy; use rustyboy_pico2w::save_storage::SaveSlot; -use super::{MainMenuState, RunningState}; +use super::{MainMenuState, RunningState, MENU_POLL_MS}; use crate::{flush_battery_save, App, AppState, PicoSdMgr}; pub struct InGameMenuState { @@ -31,7 +31,7 @@ impl InGameMenuState { input: &mut InputHandler<'static>, sd_mgr: &mut PicoSdMgr, ) { - Timer::after(Duration::from_millis(33)).await; + Timer::after(Duration::from_millis(MENU_POLL_MS)).await; let (current_buttons, _) = input.poll(); let menu_input = MenuInput::from_diff(app.previous_buttons, current_buttons); diff --git a/platform/pico2w/src/state/main_menu.rs b/platform/pico2w/src/state/main_menu.rs index 08931a9..9e57a77 100644 --- a/platform/pico2w/src/state/main_menu.rs +++ b/platform/pico2w/src/state/main_menu.rs @@ -3,7 +3,7 @@ use rustyboy_pico2w::display::hw::GameDisplay; use rustyboy_pico2w::input::InputHandler; use rustyboy_pico2w::menu::{MainMenu, MenuEffect, MenuInput, MenuLogic}; -use super::{RomListState, RunningState, SettingsState}; +use super::{RomListState, RunningState, SettingsState, MENU_POLL_MS}; use crate::{App, AppState, PicoSdMgr}; pub struct MainMenuState { @@ -26,7 +26,7 @@ impl MainMenuState { input: &mut InputHandler<'static>, sd_mgr: &mut PicoSdMgr, ) { - Timer::after(Duration::from_millis(33)).await; + Timer::after(Duration::from_millis(MENU_POLL_MS)).await; let (current_buttons, _) = input.poll(); let menu_input = MenuInput::from_diff(app.previous_buttons, current_buttons); diff --git a/platform/pico2w/src/state/mod.rs b/platform/pico2w/src/state/mod.rs index a1fe085..ebb4a45 100644 --- a/platform/pico2w/src/state/mod.rs +++ b/platform/pico2w/src/state/mod.rs @@ -6,6 +6,9 @@ mod running; mod settings; mod wifi_menu; +const MENU_POLL_MS: u64 = 4; +const PORTAL_POLL_MS: u64 = 16; + pub use in_game_menu::InGameMenuState; pub use loading::LoadingState; pub use main_menu::MainMenuState; diff --git a/platform/pico2w/src/state/rom_list.rs b/platform/pico2w/src/state/rom_list.rs index 6b17194..70855c3 100644 --- a/platform/pico2w/src/state/rom_list.rs +++ b/platform/pico2w/src/state/rom_list.rs @@ -8,7 +8,7 @@ use rustyboy_pico2w::menu::{ }; use rustyboy_pico2w::sd::RomListEntry; -use super::{LoadingState, MainMenuState}; +use super::{LoadingState, MainMenuState, MENU_POLL_MS}; use crate::{App, AppState, PicoSdMgr}; const ROM_PAGE_SIZE: usize = 7; @@ -175,7 +175,7 @@ impl RomListState { input: &mut InputHandler<'static>, sd_mgr: &mut PicoSdMgr, ) { - Timer::after(Duration::from_millis(33)).await; + Timer::after(Duration::from_millis(MENU_POLL_MS)).await; let menu_input = poll_menu_input(app, input); if !menu_input.any() { diff --git a/platform/pico2w/src/state/settings.rs b/platform/pico2w/src/state/settings.rs index 364cf61..436ce06 100644 --- a/platform/pico2w/src/state/settings.rs +++ b/platform/pico2w/src/state/settings.rs @@ -6,7 +6,7 @@ use rustyboy_pico2w::flash_rom::OnboardFlash; use rustyboy_pico2w::input::InputHandler; use rustyboy_pico2w::menu::{MenuEffect, MenuInput, MenuLogic, SettingsMenu}; -use super::main_menu::MainMenuState; +use super::{main_menu::MainMenuState, MENU_POLL_MS}; use crate::{App, AppState}; use super::wifi_menu::WifiMenuState; @@ -31,7 +31,7 @@ impl SettingsState { input: &mut InputHandler<'static>, #[allow(unused_variables)] flash: &mut OnboardFlash<'_>, ) { - Timer::after(Duration::from_millis(33)).await; + Timer::after(Duration::from_millis(MENU_POLL_MS)).await; let (current_buttons, _) = input.poll(); let menu_input = MenuInput::from_diff(app.previous_buttons, current_buttons); diff --git a/platform/pico2w/src/state/wifi_menu.rs b/platform/pico2w/src/state/wifi_menu.rs index 1b5873e..be80838 100644 --- a/platform/pico2w/src/state/wifi_menu.rs +++ b/platform/pico2w/src/state/wifi_menu.rs @@ -10,7 +10,7 @@ use rustyboy_pico2w::menu::{MenuFrame, MenuInput}; use rustyboy_pico2w::wifi::config::WifiConfig; use rustyboy_pico2w::wifi::portal::PORTAL_RESULT; -use super::settings::SettingsState; +use super::{settings::SettingsState, MENU_POLL_MS, PORTAL_POLL_MS}; use crate::{App, AppState}; use core::sync::atomic::{AtomicBool, Ordering}; @@ -79,19 +79,16 @@ impl WifiMenuConfigured { app: &App, ssid: heapless::String<32>, ) -> Self { - let state = Self { ssid, selected: 0 }; + let state = Self { ssid, selected: 1 }; state.draw(game_disp, app).await; state } async fn draw(&self, game_disp: &mut GameDisplay<'static>, app: &App) { - // Build the SSID display string "SSID: ". The menu item area only - // fits 13 chars (CHAR_W 8 * SCALE 2 = 16 px / glyph); "SSID: " eats 6, so - // the name is truncated to 7 chars (with a trailing '.' when cut) to keep - // the whole line on screen instead of being clipped mid-glyph. + // Keep the display-only SSID row inside the centered 34-column text area. let mut ssid_label = heapless::String::<40>::new(); let _ = ssid_label.push_str("SSID: "); - const SSID_MAX: usize = 7; + const SSID_MAX: usize = 27; let name = self.ssid.as_str(); let cut = name .char_indices() @@ -124,7 +121,7 @@ impl WifiMenuConfigured { input: &mut InputHandler<'static>, flash: &mut OnboardFlash<'_>, ) { - Timer::after(Duration::from_millis(33)).await; + Timer::after(Duration::from_millis(MENU_POLL_MS)).await; let (current_buttons, _) = input.poll(); let menu_input = MenuInput::from_diff(app.previous_buttons, current_buttons); @@ -140,14 +137,7 @@ impl WifiMenuConfigured { return; } - if menu_input.up && self.selected > 0 { - self.selected -= 1; - self.draw(game_disp, app).await; - return; - } - if menu_input.down && self.selected < 1 { - self.selected += 1; - self.draw(game_disp, app).await; + if menu_input.up || menu_input.down { return; } @@ -187,20 +177,8 @@ impl WifiPortalScreen { } async fn draw(&self, game_disp: &mut GameDisplay<'static>, app: &App) { - // Custom info screen drawn as a menu with non-selectable text items. - // The menu text window is only 13 chars wide (CHAR_W 8 * SCALE 2 = 16 px - // per glyph across the 208 px item area), so every line must stay <= 13 - // chars or render_menu_row truncates it — which previously clipped the - // instructions and dropped the last digit of the IP address. - let items: [&str; 6] = [ - "", - "Join WiFi:", - " RustyBoy", - "Then visit:", - " 192.168.4.1", - "", - ]; - let enabled = [false; 6]; + let items: [&str; 4] = ["JOIN WIFI", "RustyBoy", "OPEN", "192.168.4.1"]; + let enabled = [true; 4]; let frame = MenuFrame { title: "WIFI SETUP", items: &items, @@ -232,7 +210,7 @@ impl WifiPortalScreen { } } - Timer::after(Duration::from_millis(100)).await; + Timer::after(Duration::from_millis(PORTAL_POLL_MS)).await; let (current_buttons, _) = input.poll(); let menu_input = MenuInput::from_diff(app.previous_buttons, current_buttons);