diff --git a/README.md b/README.md
index 3fe30b5..d44d426 100644
--- a/README.md
+++ b/README.md
@@ -9,6 +9,7 @@ An app runs on a watch with the patched firmware and the App Loader, both on the
| App | What it is |
|---|---|
+| [`storage`](apps/storage) | Writable capacity, installed apps, watch faces and system reservations |
| [`vibration-lab`](apps/vibration-lab) | A test bench for the vibration motor. The template for new apps |
| [`ui-gallery`](apps/ui-gallery) | The stock firmware's widgets as an app can use them |
| [`orbit`](apps/orbit) | Round-screen Pong: turn the crown to keep the ball inside the ring |
diff --git a/apps/Cargo.lock b/apps/Cargo.lock
index 1a2ed0c..7d9c5db 100644
--- a/apps/Cargo.lock
+++ b/apps/Cargo.lock
@@ -92,6 +92,14 @@ dependencies = [
"cmf-wp2-ui",
]
+[[package]]
+name = "storage"
+version = "0.1.0"
+dependencies = [
+ "cmf-wp2-app",
+ "wp2-core",
+]
+
[[package]]
name = "twenty48"
version = "0.1.0"
diff --git a/apps/Cargo.toml b/apps/Cargo.toml
index d5a7f92..b055d0a 100644
--- a/apps/Cargo.toml
+++ b/apps/Cargo.toml
@@ -24,3 +24,7 @@ panic = "abort"
opt-level = "s"
lto = true
codegen-units = 1
+
+# Storage is a read-mostly utility; keep its package small without changing other apps.
+[profile.release.package.storage]
+opt-level = "z"
diff --git a/apps/storage/Cargo.toml b/apps/storage/Cargo.toml
new file mode 100644
index 0000000..2c28d66
--- /dev/null
+++ b/apps/storage/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "storage"
+edition.workspace = true
+license.workspace = true
+version.workspace = true
+
+[dependencies]
+cmf-wp2-app.workspace = true
+
+[dev-dependencies]
+wp2-core.workspace = true
+
+[[bin]]
+name = "storage"
+bench = false
diff --git a/apps/storage/LICENSE-Material-Symbols.txt b/apps/storage/LICENSE-Material-Symbols.txt
new file mode 100644
index 0000000..7a4a3ea
--- /dev/null
+++ b/apps/storage/LICENSE-Material-Symbols.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
\ No newline at end of file
diff --git a/apps/storage/THIRD-PARTY-NOTICES.md b/apps/storage/THIRD-PARTY-NOTICES.md
new file mode 100644
index 0000000..f0e1c22
--- /dev/null
+++ b/apps/storage/THIRD-PARTY-NOTICES.md
@@ -0,0 +1,7 @@
+# Third-party artwork
+
+The Storage launcher icon uses Google's Material Symbols `donut_large`, Rounded, unfilled, 24px variant. It is adapted with watch-native sizing, a circular charcoal plate and an orange upper-right segment.
+
+Source: https://github.com/google/material-design-icons/blob/master/symbols/web/donut_large/materialsymbolsrounded/donut_large_24px.svg
+
+Copyright Google LLC. Licensed under the Apache License, Version 2.0. The complete license is in `LICENSE-Material-Symbols.txt`.
diff --git a/apps/storage/icon.svg b/apps/storage/icon.svg
new file mode 100644
index 0000000..36d5af8
--- /dev/null
+++ b/apps/storage/icon.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apps/storage/shots/apps-more.png b/apps/storage/shots/apps-more.png
new file mode 100644
index 0000000..386a8e5
Binary files /dev/null and b/apps/storage/shots/apps-more.png differ
diff --git a/apps/storage/shots/apps.png b/apps/storage/shots/apps.png
new file mode 100644
index 0000000..9fbc299
Binary files /dev/null and b/apps/storage/shots/apps.png differ
diff --git a/apps/storage/shots/overview.png b/apps/storage/shots/overview.png
new file mode 100644
index 0000000..9b0b7d2
Binary files /dev/null and b/apps/storage/shots/overview.png differ
diff --git a/apps/storage/shots/system.png b/apps/storage/shots/system.png
new file mode 100644
index 0000000..01c2ec8
Binary files /dev/null and b/apps/storage/shots/system.png differ
diff --git a/apps/storage/shots/usage.png b/apps/storage/shots/usage.png
new file mode 100644
index 0000000..e3c5cf9
Binary files /dev/null and b/apps/storage/shots/usage.png differ
diff --git a/apps/storage/shots/watchfaces.png b/apps/storage/shots/watchfaces.png
new file mode 100644
index 0000000..9e3709e
Binary files /dev/null and b/apps/storage/shots/watchfaces.png differ
diff --git a/apps/storage/src/inventory.rs b/apps/storage/src/inventory.rs
new file mode 100644
index 0000000..e0df992
--- /dev/null
+++ b/apps/storage/src/inventory.rs
@@ -0,0 +1,263 @@
+//! File lengths are logical bytes, never inferred allocation-chain lengths.
+use cmf_wp2_app::storage::Storage;
+#[derive(Clone, Copy, Default, PartialEq, Debug)]
+pub enum Category {
+ App(u8),
+ Loader,
+ Face,
+ #[default]
+ Other,
+}
+#[derive(Clone, Copy)]
+pub struct File {
+ pub path: [u8; 96],
+ pub size: u32,
+ pub category: Category,
+}
+pub const EMPTY_FILE: File = File {
+ path: [0; 96],
+ size: 0,
+ category: Category::Other,
+};
+impl File {
+ pub fn path(&self) -> &str {
+ let n = self.path.iter().position(|&b| b == 0).unwrap_or(96);
+ core::str::from_utf8(&self.path[..n]).unwrap_or("Invalid filename")
+ }
+ pub fn name(&self) -> &str {
+ self.path().rsplit('/').next().unwrap_or(self.path())
+ }
+}
+#[derive(Clone, Copy)]
+pub struct App {
+ pub name: [u8; 24],
+ pub version: u32,
+ pub valid: bool,
+ pub icon: bool,
+}
+impl App {
+ pub fn name(&self) -> &str {
+ let n = self.name.iter().position(|&b| b == 0).unwrap_or(24);
+ core::str::from_utf8(&self.name[..n]).unwrap_or("Unknown app")
+ }
+}
+const EMPTY_APP: App = App {
+ name: [0; 24],
+ version: 0,
+ valid: false,
+ icon: false,
+};
+#[derive(Clone, Copy)]
+pub struct Inventory {
+ pub files: [File; 96],
+ pub count: usize,
+ pub apps: [App; 16],
+ pub ready: bool,
+ pub partial: bool,
+ pub error: i32,
+}
+impl Inventory {
+ pub const fn new() -> Self {
+ Self {
+ files: [EMPTY_FILE; 96],
+ count: 0,
+ apps: [EMPTY_APP; 16],
+ ready: false,
+ partial: false,
+ error: 0,
+ }
+ }
+ #[inline(never)]
+ pub fn reset(&mut self) {
+ self.count = 0;
+ self.ready = false;
+ self.partial = false;
+ self.error = 0;
+ for a in &mut self.apps {
+ a.valid = false;
+ }
+ }
+ #[inline(never)]
+ pub fn copy_from(&mut self, other: &Self) {
+ unsafe {
+ core::ptr::copy_nonoverlapping(other, self, 1);
+ }
+ }
+ pub fn load_file(&mut self, s: &Storage<'_>, i: usize) -> Result<(), i32> {
+ let entry = s.file(i as u16)?;
+ let mut f = File {
+ path: entry.path,
+ size: entry.size,
+ category: Category::Other,
+ };
+ f.category = classify(f.path());
+ self.files[i] = f;
+ self.count = i + 1;
+ Ok(())
+ }
+ pub fn load_apps(&mut self, s: &Storage<'_>) {
+ let slots = match s.capabilities() {
+ Ok(c) => {
+ if c.app_slots > 16 {
+ self.partial = true;
+ }
+ c.app_slots.min(16)
+ }
+ Err(e) => {
+ self.error = e;
+ self.partial = true;
+ return;
+ }
+ };
+ for i in 0..slots {
+ let mut a = EMPTY_APP;
+ match s.installed_app(i) {
+ Ok(Some(info)) => {
+ a.valid = true;
+ a.icon = info.has_icon;
+ a.version = info.version;
+ a.name = info.name;
+ }
+ Ok(None) => {}
+ Err(e) => {
+ self.error = e;
+ self.partial = true;
+ }
+ }
+ self.apps[i as usize] = a;
+ }
+ }
+ pub fn sum(&self, cat: Category) -> u32 {
+ self.files[..self.count]
+ .iter()
+ .filter(|f| same_group(f.category, cat))
+ .fold(0u32, |a, f| a.saturating_add(f.size))
+ }
+ pub fn app_total(&self, slot: u8) -> u32 {
+ self.files[..self.count]
+ .iter()
+ .filter(|f| f.category == Category::App(slot))
+ .fold(0u32, |a, f| a.saturating_add(f.size))
+ }
+ pub fn all_bytes(&self) -> u32 {
+ self.files[..self.count]
+ .iter()
+ .fold(0u32, |a, f| a.saturating_add(f.size))
+ }
+}
+pub fn same_group(a: Category, b: Category) -> bool {
+ match (a, b) {
+ (Category::App(_), Category::App(_)) => true,
+ _ => a == b,
+ }
+}
+pub fn classify(path: &str) -> Category {
+ if let Some((dir, name)) = path.rsplit_once('/') {
+ if dir.eq_ignore_ascii_case("/NAND:/WP2APPS") {
+ if name.eq_ignore_ascii_case("L.PKG") {
+ return Category::Loader;
+ }
+ let b = name.as_bytes();
+ let slot = match b.first().copied() {
+ Some(c @ b'0'..=b'9') => Some(c - b'0'),
+ Some(c @ b'A'..=b'F') => Some(c - b'A' + 10),
+ Some(c @ b'a'..=b'f') => Some(c - b'a' + 10),
+ _ => None,
+ };
+ if b.len() == 5
+ && b[1] == b'.'
+ && slot.is_some()
+ && [b"PKG", b"DAT", b"WGT", b"PSH"]
+ .iter()
+ .any(|e| b[2..].eq_ignore_ascii_case(*e))
+ {
+ return Category::App(slot.unwrap());
+ }
+ }
+ }
+ if path
+ .rsplit('.')
+ .next()
+ .is_some_and(|e| e.eq_ignore_ascii_case("wfc"))
+ {
+ Category::Face
+ } else {
+ Category::Other
+ }
+}
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn groups_only_sdk_owned_paths() {
+ assert_eq!(classify("/NAND:/wp2apps/0.pkg"), Category::App(0));
+ assert_eq!(classify("/NAND:/wp2apps/7.DAT"), Category::App(7));
+ assert_eq!(classify("/NAND:/0.pkg"), Category::Other);
+ assert_eq!(classify("/NAND:/wp2apps/8.pkg"), Category::App(8));
+ assert_eq!(classify("/NAND:/wp2apps/F.psh"), Category::App(15));
+ assert_eq!(classify("/NAND:/wp2apps/G.pkg"), Category::Other);
+ assert_eq!(classify("/NAND:/wp2apps/0.tmp"), Category::Other);
+ assert_eq!(classify("/NAND:/wp2apps/L.PKG"), Category::Loader);
+ }
+ #[test]
+ fn face_extension_is_a_file_category() {
+ assert_eq!(classify("/NAND:/foo.WFC"), Category::Face);
+ assert_eq!(classify("/NAND:/a.wfc.tmp"), Category::Other);
+ }
+}
+
+/// Logical file groups plus the remaining measured allocation. Never imply per-file cluster-chain accounting.
+pub fn breakdown(fs: &cmf_wp2_app::storage::Filesystem, inv: &Inventory) -> Option<[u32; 4]> {
+ if !inv.ready || inv.partial {
+ return None;
+ }
+ let used = fs.total.checked_sub(fs.free)?;
+ if inv.all_bytes() > used {
+ return None;
+ }
+ let apps = inv.sum(Category::App(0));
+ let faces = inv.sum(Category::Face);
+ let loader = inv.sum(Category::Loader);
+ Some([
+ apps,
+ loader,
+ faces,
+ used.checked_sub(apps)?
+ .checked_sub(faces)?
+ .checked_sub(loader)?,
+ ])
+}
+
+#[cfg(test)]
+mod breakdown_tests {
+ use super::*;
+ #[test]
+ fn allocation_remainder_is_explicit_and_inconsistent_scans_are_hidden() {
+ let mut inv = Inventory::new();
+ inv.ready = true;
+ inv.count = 4;
+ for (i, (category, size)) in [
+ (Category::App(0), 20),
+ (Category::Face, 10),
+ (Category::Loader, 30),
+ (Category::Other, 5),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ inv.files[i].category = category;
+ inv.files[i].size = size;
+ }
+ let mut fs = cmf_wp2_app::storage::Filesystem {
+ total: 200,
+ free: 100,
+ ..Default::default()
+ };
+ assert_eq!(breakdown(&fs, &inv), Some([20, 30, 10, 40]));
+ inv.partial = true;
+ assert_eq!(breakdown(&fs, &inv), None);
+ inv.partial = false;
+ fs.free = 190;
+ assert_eq!(breakdown(&fs, &inv), None);
+ }
+}
diff --git a/apps/storage/src/main.rs b/apps/storage/src/main.rs
new file mode 100644
index 0000000..9b26515
--- /dev/null
+++ b/apps/storage/src/main.rs
@@ -0,0 +1,335 @@
+#![cfg_attr(target_os = "none", no_std, no_main)]
+mod inventory;
+#[cfg_attr(not(target_os = "none"), allow(dead_code))]
+mod model;
+#[cfg(any(target_os = "none", test))]
+mod ui;
+#[cfg(test)]
+mod ui_tests;
+#[cfg(not(target_os = "none"))]
+fn main() {}
+#[cfg(target_os = "none")]
+mod device {
+ use crate::{model, ui};
+ use cmf_wp2_app::{
+ Api, BUTTON, PAUSE, RESUME,
+ lv::*,
+ stock,
+ storage::{Filesystem, Partition, Storage},
+ };
+ cmf_wp2_app::entry!(main);
+ cmf_wp2_app::app_icon!();
+ #[unsafe(no_mangle)]
+ static mut STORAGE_STATS: [i32; 12] = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
+ #[unsafe(no_mangle)]
+ static mut STORAGE_UI: [i32; 3] = [0, 0, 0]; // detail, pager page, last UI error
+ static mut PARTS: [Partition; 30] = [Partition {
+ name: [0; 8],
+ kind: 0,
+ file_id: 0,
+ device: 0,
+ mirror: 0,
+ offset: 0,
+ allocated: 0,
+ }; 30];
+ fn stat(i: usize, v: i32) {
+ unsafe { (&raw mut STORAGE_STATS[i]).write_volatile(v) }
+ }
+ fn state(detail: u8, at: usize, error: i32) {
+ unsafe { (&raw mut STORAGE_UI).write_volatile([detail as i32, at as i32, error]) }
+ }
+ fn refresh(s: &Storage<'_>) -> Option {
+ match s.filesystem() {
+ Ok(f) if model::valid_filesystem(&f) => {
+ for (i, v) in [
+ f.total,
+ f.free,
+ f.apps,
+ f.app_data,
+ f.widgets,
+ f.loader,
+ f.installed_apps,
+ f.allocation_unit,
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ stat(i + 3, v as i32)
+ }
+ stat(11, 0);
+ Some(f)
+ }
+ Ok(_) => {
+ stat(11, -11);
+ None
+ }
+ Err(e) => {
+ stat(11, e);
+ None
+ }
+ }
+ }
+
+ #[inline(never)]
+ fn run(api: &'static Api, b: &mut Batch, lv: &Lv) -> Result<(), LvError> {
+ use crate::inventory::Inventory;
+ use ui::Page;
+ stock::font(b)?;
+ b.font(1, StockFont::F24M)?;
+ b.font(2, StockFont::F48M)?;
+ b.font(3, StockFont::F36M)?;
+ b.submit(lv)?;
+ let storage = Storage::open(api);
+ let mut n = 0;
+ let mut fs = None;
+ let mut error = 0;
+ if let Ok(s) = &storage {
+ match s.partition_count() {
+ Ok(count) => {
+ for i in 0..count.min(30) {
+ match s.partition(i) {
+ Ok(p) => {
+ unsafe {
+ PARTS[i as usize] = p;
+ }
+ n = i as usize + 1;
+ }
+ Err(e) => {
+ error = e;
+ break;
+ }
+ }
+ }
+ }
+ Err(e) => error = e,
+ }
+ fs = refresh(s);
+ } else if let Err(e) = &storage {
+ error = *e;
+ }
+ stat(1, error);
+ stat(2, n as i32);
+ let parts = unsafe { &(&raw const PARTS).as_ref().unwrap()[..n] };
+ static mut INVENTORY: Inventory = Inventory::new();
+ static mut NEXT: Inventory = Inventory::new();
+ let inv = unsafe { &mut *core::ptr::addr_of_mut!(INVENTORY) };
+ let next = unsafe { &mut *core::ptr::addr_of_mut!(NEXT) };
+ if error < 0 {
+ inv.error = error;
+ }
+ let mut reading = false;
+ let mut scan_count = None;
+ let mut read_at = 0usize;
+ let mut stale = false;
+ if let Ok(s) = &storage {
+ reading = s.begin_scan().is_ok();
+ if !reading {
+ inv.error = -95;
+ inv.partial = true;
+ }
+ }
+ let mut views: [Option; 4] = [None, None, None, None];
+ let mut depth = 0usize;
+ views[0] = Some(ui::render(
+ b,
+ lv,
+ Page::Home,
+ parts,
+ fs,
+ inv,
+ reading,
+ stale,
+ )?);
+ stat(0, 0);
+ api.own_back(true);
+ let mut paused = false;
+ loop {
+ let e = api.event(if reading && !paused { 16 } else { u32::MAX });
+ if let Some(e) = e {
+ if e.kind == PAUSE {
+ paused = true;
+ continue;
+ }
+ if e.kind == RESUME {
+ paused = false;
+ continue;
+ }
+ if paused {
+ continue;
+ }
+ let action = if e.kind == BUTTON {
+ ui::BACK
+ } else {
+ views[depth].as_ref().unwrap().action(&e)
+ };
+ if action == ui::BACK {
+ if depth == 0 {
+ break;
+ }
+ let old = views[depth].take().unwrap();
+ b.del(old.root)?;
+ depth -= 1;
+ if !views[depth].as_ref().unwrap().complete && inv.ready {
+ let previous = views[depth].take().unwrap();
+ let page = previous.page;
+ b.del(previous.root)?;
+ b.submit(lv)?;
+ views[depth] =
+ Some(ui::render(b, lv, page, parts, fs, inv, reading, stale)?);
+ } else {
+ views[depth].as_ref().unwrap().visible(b, true)?;
+ b.submit(lv)?;
+ }
+ state(depth as u8, 0, 0);
+ continue;
+ }
+ if action == ui::REFRESH {
+ if let Ok(s) = &storage {
+ if reading {
+ s.cancel_scan().ok();
+ reading = false;
+ if inv.ready {
+ stale = true;
+ } else {
+ inv.partial = true;
+ inv.error = -125;
+ }
+ } else {
+ let fresh = refresh(s);
+ stale = fresh.is_none();
+ if fresh.is_some() {
+ fs = fresh;
+ }
+ next.reset();
+ reading = s.begin_scan().is_ok();
+ scan_count = None;
+ read_at = 0;
+ }
+ }
+ let old = views[depth].take().unwrap();
+ b.del(old.root)?;
+ b.submit(lv)?;
+ views[depth] = Some(ui::render(
+ b,
+ lv,
+ Page::Home,
+ parts,
+ fs,
+ inv,
+ reading,
+ stale,
+ )?);
+ continue;
+ }
+ let mut replace = false;
+ let page = match action {
+ 1 => Some(Page::Apps),
+ 2 => Some(Page::Faces(0)),
+ 3 => Some(Page::Other(0)),
+ 4 => Some(Page::System),
+ 5 => Some(Page::Nand),
+ 6 => Some(Page::Nor),
+ 8 => Some(Page::Accounting),
+ 16..=31 => Some(Page::App((action - 16) as u8)),
+ 32..=127 => Some(Page::File((action - 32) as u8)),
+ 128..=157 => Some(Page::Partition((action - 128) as u8)),
+ 200 | 201 => {
+ replace = true;
+ let delta = if action == 200 { 1 } else { -1 };
+ match views[depth].as_ref().unwrap().page {
+ Page::Faces(i) => Some(Page::Faces((i as i16 + delta).max(0) as u8)),
+ Page::Other(i) => Some(Page::Other((i as i16 + delta).max(0) as u8)),
+ _ => None,
+ }
+ }
+ _ => None,
+ };
+ if let Some(page) = page {
+ if replace {
+ let old = views[depth].take().unwrap();
+ b.del(old.root)?;
+ b.submit(lv)?;
+ } else if depth < 3 {
+ views[depth].as_ref().unwrap().visible(b, false)?;
+ b.submit(lv)?;
+ depth += 1;
+ } else {
+ continue;
+ }
+ views[depth] = Some(ui::render(b, lv, page, parts, fs, inv, reading, stale)?);
+ state(depth as u8, action as usize, 0);
+ }
+ }
+ if reading && !paused {
+ if let Ok(s) = &storage {
+ if scan_count.is_none() {
+ match s.scan_step() {
+ Ok(v) if v.complete => {
+ scan_count = Some((v.files as usize).min(next.files.len()));
+ next.partial = v.partial || (v.files as usize)>next.files.len();
+ next.error = v.error;
+ }
+ Ok(_) => {}
+ Err(e) => {
+ next.error = e;
+ next.partial = true;
+ scan_count = Some(0);
+ }
+ }
+ } else if read_at < scan_count.unwrap() {
+ if let Err(e) = next.load_file(s, read_at) {
+ next.error = e;
+ next.partial = true;
+ scan_count = Some(read_at);
+ } else {
+ read_at += 1;
+ }
+ } else {
+ next.load_apps(s);
+ next.ready = true;
+ s.cancel_scan().ok();
+ if next.error < 0 && inv.ready {
+ stale = true;
+ } else {
+ inv.copy_from(next);
+ }
+ reading = false;
+ // Update the visible screen. Hidden parent pages keep their scroll position.
+ let page = views[depth].as_ref().unwrap().page;
+ let old = views[depth].take().unwrap();
+ b.del(old.root)?;
+ b.submit(lv)?;
+ views[depth] = Some(ui::render(b, lv, page, parts, fs, inv, false, stale)?);
+ stat(0, 0);
+ }
+ } else {
+ reading = false;
+ }
+ }
+ }
+ if let Ok(s) = &storage {
+ s.cancel_scan().ok();
+ }
+ Ok(())
+ }
+ fn main(api: &'static Api) -> i32 {
+ let Some(lv) = api.lv() else { return -95 };
+ let Some(mut b) = Batch::new() else {
+ return -12;
+ };
+ let result = run(api, &mut b, &lv);
+ api.own_back(false);
+ match result {
+ Ok(()) => 0,
+ Err(e) => {
+ let code = match e {
+ LvError::Code(code) => code,
+ LvError::Full => -7,
+ LvError::Budget => -12,
+ };
+ state(0, 0, code);
+ code
+ }
+ }
+ }
+}
diff --git a/apps/storage/src/model.rs b/apps/storage/src/model.rs
new file mode 100644
index 0000000..d98f864
--- /dev/null
+++ b/apps/storage/src/model.rs
@@ -0,0 +1,641 @@
+use cmf_wp2_app::storage::{Filesystem, Partition};
+use core::fmt::{self, Write};
+
+pub struct Text {
+ buf: [u8; 64],
+ len: usize,
+}
+impl Text {
+ pub fn new() -> Self {
+ Self {
+ buf: [0; 64],
+ len: 0,
+ }
+ }
+ pub fn as_str(&self) -> &str {
+ core::str::from_utf8(&self.buf[..self.len]).unwrap_or("?")
+ }
+ pub fn bytes(n: u32) -> Self {
+ let mut s = Self::new();
+ if n >= 1048576 && n % 1048576 == 0 {
+ let _ = write!(s, "{} MiB", n / 1048576);
+ } else if n >= 1048576 {
+ let _ = write!(
+ s,
+ "{}.{:02} MiB",
+ n / 1048576,
+ (u64::from(n % 1048576) * 100 / 1048576)
+ );
+ } else if n >= 1024 {
+ if n % 1024 == 0 {
+ let _ = write!(s, "{} KiB", n / 1024);
+ } else {
+ let _ = write!(s, "{}.{:02} KiB", n / 1024, (n % 1024) * 100 / 1024);
+ }
+ } else {
+ let _ = write!(s, "{} B", n);
+ }
+ s
+ }
+}
+impl Write for Text {
+ fn write_str(&mut self, s: &str) -> fmt::Result {
+ if self.len + s.len() > self.buf.len() {
+ return Err(fmt::Error);
+ }
+ self.buf[self.len..self.len + s.len()].copy_from_slice(s.as_bytes());
+ self.len += s.len();
+ Ok(())
+ }
+}
+pub fn total(parts: &[Partition], device: u8) -> Option {
+ let mut total = 0u32;
+ for (i, p) in parts.iter().enumerate().filter(|(_, p)| p.device == device) {
+ let end = p.offset.checked_add(p.allocated)?;
+ for q in &parts[..i] {
+ if q.device == device && p.offset < q.offset.checked_add(q.allocated)? && q.offset < end
+ {
+ return None;
+ }
+ }
+ total = total.checked_add(p.allocated)?;
+ }
+ Some(total)
+}
+pub fn other(fs: &Filesystem) -> Option {
+ fs.total
+ .checked_sub(fs.free)?
+ .checked_sub(fs.apps)?
+ .checked_sub(fs.app_data)?
+ .checked_sub(fs.widgets)?
+ .checked_sub(fs.loader)
+}
+pub fn percent(used: u32, total: u32) -> i16 {
+ if total == 0 {
+ 0
+ } else {
+ (u64::from(used).min(total as u64) * 100 / total as u64) as i16
+ }
+}
+
+#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
+pub struct Rect {
+ pub x: i16,
+ pub y: i16,
+ pub w: i16,
+ pub h: i16,
+}
+impl Rect {
+ pub const fn new(x: i16, y: i16, w: i16, h: i16) -> Self {
+ Self { x, y, w, h }
+ }
+ pub fn in_round_screen(self, margin: i32) -> bool {
+ let r = 233 - margin;
+ [self.x as i32, self.x as i32 + self.w as i32]
+ .into_iter()
+ .all(|x| {
+ [self.y as i32, self.y as i32 + self.h as i32]
+ .into_iter()
+ .all(|y| (x - 233) * (x - 233) + (y - 233) * (y - 233) <= r * r)
+ })
+ }
+}
+pub const TITLE: Rect = Rect::new(113, 46, 240, 42);
+pub const MAP: Rect = Rect::new(78, 142, 310, 174);
+pub const BOTTOM: Rect = Rect::new(128, 376, 210, 52);
+pub const CATEGORY_NAMES: [&str; 4] = ["Apps", "Saved data", "App loader", "Other + allocation"];
+pub fn used_categories(f: &Filesystem) -> Option<[u32; 4]> {
+ Some([
+ f.apps,
+ f.app_data.checked_add(f.widgets)?,
+ f.loader,
+ other(f)?,
+ ])
+}
+/// Binary treemap. Preserve proportions; tiny categories are selected in the details list.
+pub fn treemap(values: [u32; 4], bounds: Rect) -> [Rect; 4] {
+ fn split(items: &[(usize, u32)], r: Rect, out: &mut [Rect; 4]) {
+ if items.is_empty() {
+ return;
+ }
+ if items.len() == 1 {
+ out[items[0].0] = r;
+ return;
+ }
+ let total: u64 = items.iter().map(|i| i.1 as u64).sum();
+ let mut left = 0u64;
+ let mut cut = 1;
+ let mut best = u64::MAX;
+ for i in 1..items.len() {
+ left += items[i - 1].1 as u64;
+ let distance = (2 * left).abs_diff(total);
+ if distance < best {
+ best = distance;
+ cut = i;
+ }
+ }
+ let part: u64 = items[..cut].iter().map(|i| i.1 as u64).sum();
+ let mut a = r;
+ let mut b = r;
+ if r.w >= r.h {
+ a.w = (r.w as u64 * part / total) as i16;
+ b.x += a.w;
+ b.w -= a.w;
+ } else {
+ a.h = (r.h as u64 * part / total) as i16;
+ b.y += a.h;
+ b.h -= a.h;
+ }
+ split(&items[..cut], a, out);
+ split(&items[cut..], b, out);
+ }
+ let mut items = [(0usize, 0u32); 4];
+ let mut n = 0;
+ for (i, v) in values.into_iter().enumerate() {
+ if v > 0 {
+ items[n] = (i, v);
+ n += 1;
+ }
+ }
+ items[..n].sort_unstable_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
+ let mut out = [Rect::default(); 4];
+ split(&items[..n], bounds, &mut out);
+ out
+}
+/// Exclusive allocation categories: firmware/boot, resources, writable files, reserved/settings/other.
+pub fn allocation_groups(parts: &[Partition]) -> Option<[u32; 4]> {
+ let mut out = [0u32; 4];
+ for p in parts {
+ let i = match p.file_id {
+ 1..=5 => 0,
+ 10..=39 => 1,
+ 40 => 2,
+ _ => 3,
+ };
+ out[i] = out[i].checked_add(p.allocated)?;
+ }
+ for dev in 0..16 {
+ total(parts, dev)?;
+ }
+ Some(out)
+}
+pub fn widths(values: &[u32], width: u32) -> [u32; 5] {
+ let mut out = [0; 5];
+ let total: u64 = values.iter().map(|&x| u64::from(x)).sum();
+ if total == 0 {
+ return out;
+ }
+ let mut sum = 0u64;
+ let mut previous = 0;
+ for (i, &v) in values.iter().take(5).enumerate() {
+ sum += u64::from(v);
+ let end = (sum * u64::from(width) / total) as u32;
+ out[i] = end - previous;
+ previous = end;
+ }
+ out
+}
+/// Reserve separators only for segments that are visible at the current pixel width.
+pub fn separated_widths(values: &[u32], width: u32) -> [u32; 5] {
+ // Pick visible segments once, then remove only segments that cannot retain a pixel after reserving gaps.
+ // Removed segments never reappear, so tiny values cannot oscillate at a separator boundary.
+ let initial = widths(values, width);
+ let mut filtered = [0u32; 5];
+ for i in 0..values.len().min(5) {
+ if initial[i] > 0 {
+ filtered[i] = values[i];
+ }
+ }
+ for _ in 0..5 {
+ let n = filtered.iter().filter(|&&v| v > 0).count();
+ let out = widths(
+ &filtered,
+ width.saturating_sub(n.saturating_sub(1) as u32 * 2),
+ );
+ if out.iter().all(|&v| v == 0) && filtered.iter().any(|&v| v > 0) {
+ let best = (0..5).max_by_key(|&i| filtered[i]).unwrap();
+ let v = filtered[best];
+ filtered = [0; 5];
+ filtered[best] = v;
+ continue;
+ }
+ let mut removed = false;
+ for i in 0..5 {
+ if filtered[i] > 0 && out[i] == 0 {
+ filtered[i] = 0;
+ removed = true;
+ }
+ }
+ if !removed {
+ return out;
+ }
+ }
+ widths(&filtered, width)
+}
+#[cfg(test)]
+mod separator_tests {
+ use super::*;
+ #[test]
+ fn separators_fill_requested_bounds() {
+ for v in [
+ [20, 30, 10, 40, 900],
+ [1, 0, 0, 0, 999999],
+ [10, 10, 10, 10, 0],
+ [0; 5],
+ [1, 373, 0, 0, 0],
+ ] {
+ let w = separated_widths(&v, 374);
+ let n = w.iter().filter(|&&x| x > 0).count();
+ assert_eq!(
+ w.iter().sum::() + n.saturating_sub(1) as u32 * 2,
+ if n > 0 { 374 } else { 0 }
+ );
+ }
+ }
+}
+pub fn purpose(p: &Partition) -> &'static str {
+ match p.file_id {
+ 1 => "Bootloader",
+ 2 => "Partition table",
+ 3 => "Recovery",
+ 4 => "Firmware",
+ 5 => "System files",
+ 6..=8 => "Settings",
+ 12 | 13 => "Fonts / watch faces",
+ 10 | 11 => "UI resources",
+ 14 => "Exercise animations",
+ 20 => "Boot / sound assets",
+ 40 => "Writable files",
+ 248 => "Reserved",
+ 249 => "Settings / history",
+ 250 | 251 => "Logs",
+ 253 => "Crash records",
+ 254 => "OTA staging",
+ _ => "Other allocation",
+ }
+}
+
+pub const NAND_MAIN: u32 = 128 * 1048576;
+pub const NAND_LOGICAL: u32 = 123 * 1048576;
+pub const NOR_MAIN: u32 = 4 * 1048576;
+pub const FTL_MANAGEMENT: u32 = 5 * 1048576;
+pub const LOGICAL_TAIL: u32 = 11010048;
+const VERIFIED_LAYOUT: &[(u8, u8, u32, u32)] = &[
+ (0, 1, 0x00000000, 4096),
+ (0, 2, 0x00001000, 4096),
+ (0, 1, 0x00002000, 4096),
+ (0, 2, 0x00003000, 4096),
+ (0, 3, 0x00004000, 131072),
+ (0, 4, 0x00024000, 3452928),
+ (0, 248, 0x0036f000, 409600),
+ (0, 5, 0x003d3000, 65536),
+ (0, 6, 0x003e3000, 4096),
+ (0, 7, 0x003e4000, 8192),
+ (0, 8, 0x003e6000, 8192),
+ (0, 251, 0x003e8000, 16384),
+ (2, 249, 0x00480000, 2097152),
+ (0, 253, 0x003ec000, 81920),
+ (2, 10, 0x01280000, 10485760),
+ (2, 12, 0x00680000, 12582912),
+ (2, 11, 0x01c80000, 8388608),
+ (2, 14, 0x02480000, 67108864),
+ (2, 20, 0x00380000, 1048576),
+ (2, 254, 0x00000000, 3670016),
+ (2, 250, 0x06480000, 2097152),
+ (2, 40, 0x06680000, 10485760),
+];
+pub fn reference_layout(parts: &[Partition]) -> bool {
+ parts.len() == VERIFIED_LAYOUT.len()
+ && VERIFIED_LAYOUT
+ .iter()
+ .all(|&(device, id, offset, allocated)| {
+ parts
+ .iter()
+ .filter(|p| {
+ p.device == device
+ && p.file_id == id
+ && p.offset == offset
+ && p.allocated == allocated
+ })
+ .count()
+ == 1
+ })
+}
+pub fn valid_filesystem(f: &Filesystem) -> bool {
+ f.total > 0
+ && f.allocation_unit.is_power_of_two()
+ && f.total % f.allocation_unit == 0
+ && f.free % f.allocation_unit == 0
+ && other(f).is_some()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn verified_reference_requires_exact_device_layout() {
+ let mut parts: [Partition; 22] = [Partition::default(); 22];
+ for (p, &(device, file_id, offset, allocated)) in parts.iter_mut().zip(VERIFIED_LAYOUT) {
+ *p = Partition {
+ device,
+ file_id,
+ offset,
+ allocated,
+ ..Default::default()
+ };
+ }
+ assert!(reference_layout(&parts));
+ assert_eq!(total(&parts, 2), Some(1125 * 1048576 / 10));
+ assert_eq!(total(&parts, 0), Some(NOR_MAIN));
+ assert_eq!(NAND_LOGICAL - total(&parts, 2).unwrap(), LOGICAL_TAIL);
+ assert_eq!(NAND_MAIN - NAND_LOGICAL, FTL_MANAGEMENT);
+ parts[0].allocated += 1;
+ assert!(!reference_layout(&parts));
+ }
+ #[test]
+ fn invalid_live_counters_are_not_presented_as_usage() {
+ assert!(!valid_filesystem(&Filesystem::default()));
+ assert!(!valid_filesystem(&Filesystem {
+ total: 1024,
+ free: 2048,
+ allocation_unit: 1024,
+ ..Default::default()
+ }));
+ assert!(valid_filesystem(&Filesystem {
+ total: 10240,
+ free: 8192,
+ apps: 1024,
+ allocation_unit: 1024,
+ ..Default::default()
+ }));
+ }
+ #[test]
+ fn units() {
+ assert_eq!(Text::bytes(1048576).as_str(), "1 MiB");
+ assert_eq!(Text::bytes(0).as_str(), "0 B");
+ }
+ #[test]
+ fn never_double_counts_overlaps() {
+ let a = Partition {
+ device: 2,
+ offset: 0,
+ allocated: 100,
+ ..Default::default()
+ };
+ assert_eq!(total(&[a, a], 2), None);
+ assert_eq!(total(&[a, Partition { offset: 100, ..a }], 2), Some(200));
+ }
+ #[test]
+ fn inconsistent_live_snapshot_is_unknown() {
+ assert_eq!(
+ other(&Filesystem {
+ total: 10,
+ free: 11,
+ ..Default::default()
+ }),
+ None
+ );
+ }
+ #[test]
+ fn bar_is_bounded() {
+ assert_eq!(percent(u32::MAX, u32::MAX), 100);
+ assert_eq!(percent(3, 0), 0);
+ }
+ #[test]
+ fn segments_cover_exact_width() {
+ assert_eq!(widths(&[1, 1, 1], 370).iter().sum::(), 370);
+ assert_eq!(widths(&[0, 0], 370), [0; 5]);
+ }
+ #[test]
+ fn fixed_controls_fit_the_round_safe_area() {
+ for r in [
+ TITLE,
+ MAP,
+ BOTTOM,
+ Rect::new(123, 376, 104, 52),
+ Rect::new(239, 376, 104, 52),
+ Rect::new(63, 332, 340, 34),
+ Rect::new(68, 136, 330, 86),
+ Rect::new(68, 234, 330, 86),
+ ] {
+ assert!(r.in_round_screen(8), "{r:?}");
+ }
+ }
+ #[test]
+ fn treemap_covers_area_without_overlaps() {
+ for values in [
+ [17982, 0, 49944, 6802],
+ [0, 0, 0, 1],
+ [1, 1, 1, 1],
+ [u32::MAX, 1, 3, 0],
+ ] {
+ let rects = treemap(values, MAP);
+ assert_eq!(
+ rects
+ .iter()
+ .map(|r| i32::from(r.w) * i32::from(r.h))
+ .sum::(),
+ i32::from(MAP.w) * i32::from(MAP.h)
+ );
+ for (i, a) in rects.iter().enumerate().filter(|(_, r)| r.w > 0 && r.h > 0) {
+ assert!(
+ a.x >= MAP.x
+ && a.y >= MAP.y
+ && a.x + a.w <= MAP.x + MAP.w
+ && a.y + a.h <= MAP.y + MAP.h
+ );
+ for b in &rects[..i] {
+ assert!(
+ b.w == 0
+ || b.h == 0
+ || a.x >= b.x + b.w
+ || b.x >= a.x + a.w
+ || a.y >= b.y + b.h
+ || b.y >= a.y + a.h
+ );
+ }
+ }
+ }
+ assert_eq!(treemap([0; 4], MAP), [Rect::default(); 4]);
+ }
+}
+
+/// Nominal integer glyph advances from the extracted WP2 font48M (hash in design/VISUAL-REVISION.md).
+/// Used for the unit's position, not claimed to be a full kerning engine.
+pub fn number_width(s: &str) -> i16 {
+ const DIGITS: [i16; 10] = [31, 19, 29, 30, 31, 29, 30, 27, 30, 30];
+ s.bytes()
+ .map(|b| match b {
+ b'0'..=b'9' => DIGITS[(b - b'0') as usize],
+ b'.' => 14,
+ _ => 24,
+ })
+ .sum()
+}
+
+/// Visible-ink centering for the actual WP2 font32M. Native baseline measured at26px.
+/// Nominal ASCII advances/bearings come from the extracted font, not string length.
+pub fn button_label_position(text: &str, height: i16) -> (i16, i16) {
+ const GLYPHS: [(i16, i16, i16, i16, i16); 95] = [
+ (8, 0, 0, 0, 0),
+ (9, 2, 0, 6, 24),
+ (15, 3, 14, 10, 10),
+ (20, 0, 0, 20, 24),
+ (20, 1, -3, 19, 31),
+ (31, 3, 0, 26, 24),
+ (20, 1, 0, 20, 24),
+ (10, 3, 14, 4, 10),
+ (11, 3, -4, 8, 30),
+ (11, 1, -4, 8, 30),
+ (16, 2, 10, 13, 14),
+ (21, 2, 2, 17, 16),
+ (9, 1, -6, 7, 10),
+ (14, 2, 8, 11, 4),
+ (9, 2, 0, 6, 5),
+ (11, 0, -4, 12, 29),
+ (20, 1, 0, 18, 24),
+ (13, 1, 0, 10, 24),
+ (19, 2, 0, 16, 24),
+ (20, 1, 0, 18, 24),
+ (21, 1, 0, 19, 24),
+ (19, 2, 0, 17, 24),
+ (20, 1, 0, 18, 24),
+ (18, 1, 0, 16, 24),
+ (20, 1, 0, 18, 24),
+ (20, 1, 0, 18, 24),
+ (9, 2, 0, 6, 17),
+ (10, 1, -6, 7, 23),
+ (21, 2, 0, 16, 19),
+ (21, 3, 4, 15, 11),
+ (21, 3, 0, 16, 19),
+ (16, 1, 0, 15, 24),
+ (31, 1, -7, 29, 30),
+ (22, 0, 0, 22, 24),
+ (21, 2, 0, 18, 24),
+ (23, 1, 0, 21, 24),
+ (23, 2, 0, 20, 24),
+ (19, 2, 0, 16, 24),
+ (18, 2, 0, 16, 24),
+ (23, 1, 0, 22, 24),
+ (23, 2, 0, 20, 24),
+ (8, 2, 0, 5, 24),
+ (18, 1, 0, 15, 24),
+ (22, 2, 0, 20, 24),
+ (18, 2, 0, 15, 24),
+ (29, 2, 0, 25, 24),
+ (24, 2, 0, 20, 24),
+ (24, 1, 0, 22, 24),
+ (20, 2, 0, 17, 24),
+ (24, 1, -2, 22, 26),
+ (20, 2, 0, 18, 24),
+ (20, 1, 0, 19, 24),
+ (20, 1, 0, 19, 24),
+ (23, 2, 0, 20, 24),
+ (22, 0, 0, 22, 24),
+ (32, 0, 0, 32, 24),
+ (22, 0, 0, 22, 24),
+ (22, 0, 0, 22, 24),
+ (20, 1, 0, 18, 24),
+ (11, 3, -4, 7, 30),
+ (11, 0, -4, 12, 29),
+ (11, 1, -4, 8, 30),
+ (15, 1, 13, 14, 10),
+ (14, 0, -3, 15, 3),
+ (10, 2, 20, 7, 5),
+ (18, 1, 0, 15, 18),
+ (19, 2, 0, 17, 24),
+ (18, 1, 0, 17, 18),
+ (19, 1, 0, 17, 24),
+ (18, 1, 0, 17, 18),
+ (12, 0, 0, 12, 25),
+ (19, 1, -7, 17, 25),
+ (19, 2, 0, 15, 24),
+ (8, 1, 0, 6, 25),
+ (8, -1, -7, 8, 32),
+ (17, 2, 0, 16, 24),
+ (8, 2, 0, 4, 24),
+ (28, 2, 0, 25, 18),
+ (19, 2, 0, 15, 18),
+ (19, 1, 0, 17, 18),
+ (19, 2, -7, 17, 25),
+ (19, 1, -7, 17, 25),
+ (12, 2, 0, 10, 18),
+ (17, 1, 0, 15, 18),
+ (10, 0, 0, 11, 22),
+ (19, 2, 0, 15, 18),
+ (18, 0, 0, 18, 18),
+ (26, 0, 0, 26, 18),
+ (17, 0, 0, 17, 18),
+ (18, 0, -7, 18, 25),
+ (17, 1, 0, 15, 18),
+ (14, 2, -4, 11, 30),
+ (11, 3, -8, 5, 39),
+ (14, 1, -4, 11, 30),
+ (21, 2, 6, 17, 7),
+ ];
+ let (mut pen, mut left, mut right, mut top, mut bottom) =
+ (0i16, i16::MAX, i16::MIN, i16::MAX, i16::MIN);
+ for c in text.bytes() {
+ if !(32..127).contains(&c) {
+ continue;
+ }
+ let (a, x, y, w, h) = GLYPHS[(c - 32) as usize];
+ if w > 0 && h > 0 {
+ left = left.min(pen + x);
+ right = right.max(pen + x + w);
+ top = top.min(-y - h);
+ bottom = bottom.max(-y);
+ }
+ pen += a;
+ }
+ if left == i16::MAX {
+ return (0, (height - 32) / 2);
+ }
+ (
+ (pen - left - right) / 2,
+ (height - (bottom - top)) / 2 - (26 + top),
+ )
+}
+
+/// Each overview band covers one third of this same filesystem, not a separate chip.
+pub fn band_used(used: u32, total: u32, index: u8) -> u32 {
+ if total == 0 || index >= 3 {
+ return 0;
+ }
+ ((u64::from(used.min(total)) * 3).saturating_sub(u64::from(index) * u64::from(total)))
+ .min(u64::from(total)) as u32
+}
+#[cfg(test)]
+mod visual_tests {
+ use super::*;
+ #[test]
+ fn storage_bands_preserve_usage() {
+ for total in [1, 3, 1000, 10223616, u32::MAX] {
+ for used in [0, total / 100, total / 3, total / 2, total - 1, total] {
+ let sum: u64 = (0..3).map(|i| u64::from(band_used(used, total, i))).sum();
+ assert_eq!(sum, u64::from(used) * 3);
+ }
+ }
+ assert_eq!(band_used(200, 100, 0), 100);
+ assert_eq!(band_used(1, 0, 0), 0);
+ assert_eq!(band_used(100, 100, 3), 0);
+ }
+ #[test]
+ fn action_text_uses_visible_ink() {
+ assert_eq!(button_label_position("Back", 72), (-1, 22));
+ assert_eq!(button_label_position("Refresh", 72), (0, 22));
+ }
+}
+
+/// Nominal advances for the compact24M legend labels.
+pub fn legend_width(s: &str) -> i16 {
+ match s {
+ "Apps" => 57,
+ "Faces" => 66,
+ "Loader" => 77,
+ "Other" => 63,
+ "Free" => 51,
+ "Used" => 57,
+ _ => 100,
+ }
+}
diff --git a/apps/storage/src/ui.rs b/apps/storage/src/ui.rs
new file mode 100644
index 0000000..3851be8
--- /dev/null
+++ b/apps/storage/src/ui.rs
@@ -0,0 +1,1100 @@
+//! Native LVGL list, stock fonts, curved stock scrollbar. Cards are reserved for actions.
+use crate::{
+ inventory::{Category, Inventory},
+ model::{self, Rect, Text},
+};
+use cmf_wp2_app::{
+ Event,
+ lv::*,
+ stock,
+ storage::{Filesystem, Partition},
+};
+use core::fmt::Write;
+const SURFACE: i32 = 0x2966; // Stock WP2 Settings card reference: (39,42,47) at full brightness
+const SECONDARY: i32 = 0x8c51; // sampled WP3 #8E8B8E
+// Semantic chart colors; surfaces and text retain the native watch theme.
+const CHART_COLORS: [i32; 5] = [0xda67, 0xe4c6, 0xf649, 0xbe18, 0x2966];
+pub const BACK: u16 = 250;
+pub const REFRESH: u16 = 251;
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Page {
+ Home,
+ Apps,
+ Faces(u8),
+ Other(u8),
+ System,
+ Nand,
+ Nor,
+ App(u8),
+ File(u8),
+ Partition(u8),
+ Accounting,
+}
+pub struct Screen {
+ pub root: Obj,
+ bar: Obj,
+ pub page: Page,
+ pub complete: bool,
+ buttons: [(Obj, u16); 32],
+ n: usize,
+}
+impl Screen {
+ pub fn action(&self, e: &Event) -> u16 {
+ if e.kind != cmf_wp2_app::LV || e.y != 7 {
+ return 0;
+ }
+ self.buttons[..self.n]
+ .iter()
+ .find(|(o, _)| o.0 == e.x as u16)
+ .map_or(0, |(_, a)| *a)
+ }
+ pub fn visible(&self, b: &mut Batch, on: bool) -> Result<(), LvError> {
+ for o in [self.root, self.bar] {
+ if on {
+ b.flags(o, &[], &[Flag::Hidden])?;
+ } else {
+ b.flags(o, &[Flag::Hidden], &[])?;
+ }
+ }
+ if on {
+ b.knob(self.root)?;
+ }
+ Ok(())
+ }
+ fn bind(&mut self, b: &mut Batch, o: Obj, action: u16) -> Result<(), LvError> {
+ b.events(o, &[Ev::Clicked])?;
+ self.buttons[self.n] = (o, action);
+ self.n += 1;
+ Ok(())
+ }
+}
+fn label(
+ b: &mut Batch,
+ p: Obj,
+ text: &str,
+ r: Rect,
+ font: i32,
+ color: i32,
+ align: i32,
+ wrap: bool,
+) -> Result {
+ let o = b.create(Class::Label, p)?;
+ b.size(o, r.w as i32, r.h as i32)?;
+ b.align(o, Align::TopLeft, r.x, r.y)?;
+ b.text(o, text)?;
+ b.style(o, Prop::TextFont, 0, font)?;
+ b.style(o, Prop::TextColor, 0, color)?;
+ b.style(o, Prop::TextAlign, 0, align)?;
+ b.long_mode(o, if wrap { LongMode::Wrap } else { LongMode::Dot })?;
+ b.flags(o, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ Ok(o)
+}
+fn block(b: &mut Batch, p: Obj, h: i32) -> Result {
+ let o = b.create(Class::Obj, p)?;
+ b.size(o, 418, h)?;
+ for prop in [
+ Prop::PadTop,
+ Prop::PadBottom,
+ Prop::PadLeft,
+ Prop::PadRight,
+ Prop::BorderWidth,
+ Prop::BgOpa,
+ ] {
+ b.style(o, prop, 0, 0)?;
+ }
+ b.flags(o, &[], &[Flag::Scrollable, Flag::Clickable])?;
+ Ok(o)
+}
+fn heading(b: &mut Batch, p: Obj, text: &str, accent: bool) -> Result<(), LvError> {
+ let o = b.create(Class::Label, p)?;
+ b.size(o, 418, 42)?;
+ b.text(o, text)?;
+ b.style(o, Prop::TextAlign, 0, 2)?;
+ b.style(o, Prop::TextFont, 0, 0)?;
+ b.style(
+ o,
+ Prop::TextColor,
+ 0,
+ if accent { stock::ACCENT } else { stock::WHITE },
+ )?;
+ b.long_mode(o, LongMode::Dot)?;
+ Ok(())
+}
+fn note(b: &mut Batch, lv: &Lv, p: Obj, text: &str) -> Result<(), LvError> {
+ let lines = ((text.len() + 25) / 26).max(1) as i32;
+ let o = block(b, p, lines * 32 + 20)?;
+ label(
+ b,
+ o,
+ text,
+ Rect::new(40, 6, 338, (lines * 32 + 8) as i16),
+ 1,
+ SECONDARY,
+ 0,
+ true,
+ )?;
+ b.submit(lv)
+}
+// Category pictograms follow the filled stock Settings vocabulary. Storage/folder symbols
+// are app-specific LVGL geometry; they are not claimed to be extracted stock artwork.
+#[derive(Clone, Copy)]
+enum Icon {
+ Apps,
+ Face,
+ Folder,
+ Chip,
+ Drive,
+ Usage,
+ App(char),
+ Installed(u8),
+ Document,
+}
+fn shape(
+ b: &mut Batch,
+ p: Obj,
+ x: i16,
+ y: i16,
+ w: i16,
+ h: i16,
+ color: i32,
+ radius: i32,
+) -> Result {
+ let o = b.create(Class::Obj, p)?;
+ b.size(o, w as i32, h as i32)?;
+ b.align(o, Align::TopLeft, x, y)?;
+ for prop in [
+ Prop::PadTop,
+ Prop::PadBottom,
+ Prop::PadLeft,
+ Prop::PadRight,
+ Prop::BorderWidth,
+ ] {
+ b.style(o, prop, 0, 0)?;
+ }
+ b.style(o, Prop::BgColor, 0, color)?;
+ b.style(o, Prop::BgOpa, 0, 255)?;
+ b.style(o, Prop::Radius, 0, radius)?;
+ b.flags(o, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ Ok(o)
+}
+/// Square internal ends, two-pixel separators, and rounded outside ends only.
+fn chart(b: &mut Batch, p: Obj, x: i16, y: i16, width: u16, values: &[u32]) -> Result<(), LvError> {
+ let widths = model::separated_widths(values, u32::from(width));
+ let first = widths.iter().position(|&w| w > 0).unwrap_or(0);
+ let last = widths.iter().rposition(|&w| w > 0).unwrap_or(0);
+ let mut cursor = x;
+ for i in 0..5 {
+ let w = widths[i] as i16;
+ if w == 0 {
+ continue;
+ }
+ let radius = if i == first || i == last {
+ 6.min(w as i32 / 2)
+ } else {
+ 0
+ };
+ shape(b, p, cursor, y, w, 24, CHART_COLORS[i], radius)?;
+ if first != last && radius > 0 {
+ let r = radius as i16;
+ if i == first {
+ shape(b, p, cursor + w - r, y, r, 24, CHART_COLORS[i], 0)?;
+ }
+ if i == last {
+ shape(b, p, cursor, y, r, 24, CHART_COLORS[i], 0)?;
+ }
+ }
+ cursor += w + 2;
+ }
+ Ok(())
+}
+fn icon(b: &mut Batch, lv: &Lv, p: Obj, kind: Icon, x: i16, y: i16) -> Result<(), LvError> {
+ b.submit(lv)?;
+ match kind {
+ Icon::Installed(slot) => {
+ let o = shape(b, p, 16, 16, 96, 96, SURFACE, 0)?;
+ b.style(o, Prop::BgOpa, 0, 0)?;
+ b.installed_app_icon(o, slot, IconSize::Native)?;
+ }
+ Icon::Apps => {
+ for row in 0..3 {
+ for col in 0..3 {
+ shape(
+ b,
+ p,
+ x + 4 + col * 14,
+ y + 4 + row * 14,
+ 8,
+ 8,
+ stock::WHITE,
+ 4,
+ )?;
+ }
+ b.submit(lv)?;
+ }
+ }
+ Icon::Face => {
+ shape(b, p, x + 13, y - 3, 18, 50, stock::WHITE, 4)?;
+ shape(b, p, x + 4, y + 5, 36, 36, stock::WHITE, 18)?;
+ shape(b, p, x + 9, y + 10, 26, 26, SURFACE, 13)?;
+ shape(b, p, x + 20, y + 14, 3, 12, stock::WHITE, 1)?;
+ shape(b, p, x + 20, y + 24, 10, 3, stock::ACCENT, 1)?;
+ }
+ Icon::Folder => {
+ shape(b, p, x + 1, y + 6, 20, 12, stock::WHITE, 4)?;
+ shape(b, p, x + 1, y + 13, 42, 28, stock::WHITE, 5)?;
+ }
+ Icon::Document => {
+ shape(b, p, x + 7, y + 2, 30, 40, stock::WHITE, 4)?;
+ shape(b, p, x + 13, y + 13, 18, 3, SURFACE, 1)?;
+ shape(b, p, x + 13, y + 21, 18, 3, SURFACE, 1)?;
+ shape(b, p, x + 13, y + 29, 12, 3, SURFACE, 1)?;
+ }
+ Icon::Chip => {
+ // Fit the reference's visible silhouette to the full44px slot, rather than its padded viewBox.
+ for offset in [14, 25] {
+ shape(b, p, x + offset, y, 5, 44, stock::WHITE, 0)?;
+ shape(b, p, x, y + offset, 44, 5, stock::WHITE, 0)?;
+ }
+ b.submit(lv)?;
+ shape(b, p, x + 5, y + 5, 34, 34, stock::WHITE, 5)?;
+ shape(b, p, x + 10, y + 10, 24, 24, SURFACE, 0)?;
+ shape(b, p, x + 14, y + 14, 16, 16, stock::WHITE, 0)?;
+ }
+ Icon::Drive => {
+ for i in 0..3 {
+ shape(
+ b,
+ p,
+ x,
+ y + i * 16,
+ 46,
+ 12,
+ if i == 0 { stock::WHITE } else { SECONDARY },
+ 4,
+ )?;
+ }
+ shape(b, p, x + 35, y + 3, 5, 5, stock::ACCENT, 3)?;
+ }
+ Icon::Usage => {
+ shape(b, p, x, y, 44, 44, stock::WHITE, 22)?;
+ shape(b, p, x + 20, y + 10, 4, 4, SURFACE, 2)?;
+ shape(b, p, x + 20, y + 20, 4, 14, SURFACE, 2)?;
+ }
+ Icon::App(letter) => {
+ let circle = shape(b, p, x - 2, y - 2, 48, 48, stock::LETTER_BG, 24)?;
+ let mut initial = Text::new();
+ let _ = write!(initial, "{}", letter.to_ascii_uppercase());
+ let (dx, ty) = model::button_label_position(initial.as_str(), 48);
+ label(
+ b,
+ circle,
+ initial.as_str(),
+ Rect::new(dx, ty, 48, 38),
+ 0,
+ stock::WHITE,
+ 2,
+ false,
+ )?;
+ }
+ }
+ b.submit(lv)
+}
+fn navigation(
+ b: &mut Batch,
+ lv: &Lv,
+ s: &mut Screen,
+ name: &str,
+ value: &str,
+ action: u16,
+ kind: Icon,
+) -> Result<(), LvError> {
+ let app_row = matches!(s.page, Page::Apps);
+ let height = 128;
+ let text_x = if app_row { 132 } else { 96 };
+ let o = block(b, s.root, height)?;
+ b.style(o, Prop::BgColor, 0, SURFACE)?;
+ b.style(o, Prop::BgOpa, 0, 255)?;
+ b.style(o, Prop::Radius, 0, height / 2)?;
+ b.flags(o, &[Flag::Clickable], &[])?;
+ b.style(o, Prop::BgColor, stock::PRESSED, stock::ROW_PRESSED)?;
+ s.bind(b, o, action)?;
+ icon(b, lv, o, kind, 34, 42)?;
+ label(
+ b,
+ o,
+ name,
+ Rect::new(
+ text_x,
+ if app_row {
+ 22
+ } else if value.is_empty() {
+ 48
+ } else {
+ 25
+ },
+ 390 - text_x,
+ 46,
+ ),
+ 3,
+ stock::WHITE,
+ 0,
+ false,
+ )?;
+ if !value.is_empty() {
+ label(
+ b,
+ o,
+ value,
+ Rect::new(text_x, if app_row { 72 } else { 75 }, 390 - text_x, 38),
+ 0,
+ SECONDARY,
+ 0,
+ false,
+ )?;
+ }
+ b.submit(lv)
+}
+fn action_button(
+ b: &mut Batch,
+ lv: &Lv,
+ s: &mut Screen,
+ name: &str,
+ action: u16,
+) -> Result<(), LvError> {
+ let outer = block(b, s.root, 92)?;
+ let w = 280;
+ let button = shape(
+ b,
+ outer,
+ ((418 - w) / 2) as i16,
+ 8,
+ w as i16,
+ 72,
+ if action == REFRESH {
+ stock::ACCENT
+ } else {
+ stock::ROW_BG
+ },
+ 36,
+ )?;
+ b.flags(button, &[Flag::Clickable], &[])?;
+ b.style(button, Prop::BgColor, stock::PRESSED, stock::ROW_PRESSED)?;
+ s.bind(b, button, action)?;
+ let (dx, ty) = model::button_label_position(name, 72);
+ label(
+ b,
+ button,
+ name,
+ Rect::new(12 + dx, ty, (w - 24) as i16, 42),
+ 0,
+ stock::WHITE,
+ 2,
+ false,
+ )?;
+ b.submit(lv)
+}
+fn row(
+ b: &mut Batch,
+ lv: &Lv,
+ s: &mut Screen,
+ name: &str,
+ value: &str,
+ action: u16,
+ _filled: bool,
+) -> Result<(), LvError> {
+ if action == BACK || action == REFRESH || action == 200 || action == 201 {
+ return action_button(b, lv, s, name, action);
+ }
+ if (128..=157).contains(&action) {
+ let o = block(b, s.root, 104)?;
+ b.flags(o, &[Flag::Clickable], &[])?;
+ b.style(o, Prop::BgColor, stock::PRESSED, stock::ROW_PRESSED)?;
+ b.style(o, Prop::BgOpa, stock::PRESSED, 255)?;
+ b.style(o, Prop::Radius, 0, 52)?;
+ s.bind(b, o, action)?;
+ label(
+ b,
+ o,
+ name,
+ Rect::new(40, 10, 338, 42),
+ 0,
+ stock::WHITE,
+ 0,
+ false,
+ )?;
+ label(
+ b,
+ o,
+ value,
+ Rect::new(40, 59, 338, 32),
+ 1,
+ SECONDARY,
+ 0,
+ false,
+ )?;
+ return b.submit(lv);
+ }
+ if action != 0 {
+ let kind = match action {
+ 1 => Icon::Apps,
+ 2 => Icon::Face,
+ 3 => Icon::Folder,
+ 4..=6 => Icon::Chip,
+ 8 => Icon::Usage,
+ 16..=31 => {
+ if name == "Storage" {
+ Icon::Drive
+ } else {
+ Icon::App(name.chars().next().unwrap_or('A'))
+ }
+ }
+ 32..=127 => {
+ if matches!(s.page, Page::Faces(_)) {
+ Icon::Face
+ } else {
+ Icon::Document
+ }
+ }
+ _ => Icon::Drive,
+ };
+ return navigation(b, lv, s, name, value, action, kind);
+ }
+ // Read-only facts use compact text/value spacing, not button surfaces.
+ let o = block(b, s.root, 94)?;
+ label(
+ b,
+ o,
+ name,
+ Rect::new(40, 10, 338, 40),
+ 0,
+ stock::WHITE,
+ 0,
+ false,
+ )?;
+ label(
+ b,
+ o,
+ value,
+ Rect::new(40, 55, 338, 32),
+ 1,
+ SECONDARY,
+ 0,
+ false,
+ )?;
+ b.submit(lv)
+}
+fn value(b: &mut Batch, lv: &Lv, s: &mut Screen, name: &str, n: u32) -> Result<(), LvError> {
+ row(b, lv, s, name, Text::bytes(n).as_str(), 0, false)
+}
+fn count_label(inv: &Inventory, cat: Category) -> Text {
+ let mut t = Text::new();
+ if inv.error < 0 && !inv.ready {
+ let _ = write!(t, "Scan unavailable");
+ } else if !inv.ready {
+ let _ = write!(t, "Reading files...");
+ } else {
+ let _ = write!(
+ t,
+ "{}{}",
+ Text::bytes(inv.sum(cat)).as_str(),
+ if inv.partial { " found" } else { "" }
+ );
+ }
+ t
+}
+fn start(b: &mut Batch, lv: &Lv, page: Page, title: &str) -> Result {
+ stock::theme(b)?;
+ let (root, bar) = stock::page(b)?;
+ // Keep the final action inside the circular safe area without centering it.
+ b.style(root, Prop::PadBottom, 0, 48)?;
+ b.style(root, Prop::PadLeft, 0, 24)?;
+ b.style(root, Prop::PadRight, 0, 24)?;
+ b.flex(
+ root,
+ Flow::Column,
+ FlexAlign::Start,
+ FlexAlign::Start,
+ FlexAlign::Start,
+ )?;
+ b.style(root, Prop::PadRow, 0, 10)?;
+ heading(b, root, title, page == Page::Home)?;
+ b.submit(lv)?;
+ Ok(Screen {
+ root,
+ bar,
+ page,
+ complete: false,
+ buttons: [(ROOT, 0); 32],
+ n: 0,
+ })
+}
+pub fn render(
+ b: &mut Batch,
+ lv: &Lv,
+ page: Page,
+ parts: &[Partition],
+ fs: Option,
+ inv: &Inventory,
+ reading: bool,
+ stale: bool,
+) -> Result {
+ let title = match page {
+ Page::Home => "Storage",
+ Page::Apps => "Apps",
+ Page::Faces(_) => "Watch faces",
+ Page::Other(_) => "Other files",
+ Page::System => "System storage",
+ Page::Nand => "NAND",
+ Page::Nor => "System flash",
+ Page::App(slot) => {
+ if inv.apps[slot as usize].valid {
+ inv.apps[slot as usize].name()
+ } else {
+ "App details"
+ }
+ }
+ Page::File(_) => "File details",
+ Page::Partition(_) => "Reservation",
+ Page::Accounting => "Usage details",
+ };
+ let mut s = start(b, lv, page, title)?;
+ s.complete = inv.ready;
+ match page {
+ Page::Home => {
+ if let Some(f) = fs {
+ let complete = crate::inventory::breakdown(&f, inv);
+ let values = if let Some(v) = complete {
+ [v[0], v[1], v[2], v[3], f.free]
+ } else {
+ [f.total - f.free, 0, 0, 0, f.free]
+ };
+ let names = if complete.is_some() {
+ ["Apps", "Loader", "Faces", "Other", "Free"]
+ } else {
+ ["Used", "Loader", "Faces", "Other", "Free"]
+ };
+ let visible = values[..4].iter().filter(|&&v| v > 0).count();
+ let legend_width: i16 = values
+ .iter()
+ .enumerate()
+ .filter(|(i, v)| *i < 4 && **v > 0)
+ .map(|(i, _)| model::legend_width(names[i]) + 14)
+ .sum::()
+ + visible.saturating_sub(1) as i16 * 18;
+ let rows = if legend_width > 374 { 2 } else { 1 };
+ // Keep the legend clear of the bar, with breathing room before the cards.
+ let summary = block(b, s.root, 156 + rows * 32)?;
+ let free = Text::bytes(f.free);
+ let (number, unit) = free
+ .as_str()
+ .split_once(' ')
+ .unwrap_or((free.as_str(), "B"));
+ let mut free_unit = Text::new();
+ let _ = write!(free_unit, "{} free", unit);
+ let nw = model::number_width(number);
+ let uw = match unit {
+ "MiB" => 94,
+ "KiB" => 89,
+ _ => 67,
+ };
+ let left = (418 - nw - 12 - uw) / 2;
+ label(
+ b,
+ summary,
+ number,
+ Rect::new(left, 0, nw + 4, 64),
+ 2,
+ stock::WHITE,
+ 0,
+ false,
+ )?;
+ label(
+ b,
+ summary,
+ free_unit.as_str(),
+ Rect::new(left + nw + 12, 29, uw + 4, 36),
+ 1,
+ SECONDARY,
+ 0,
+ false,
+ )?;
+ let mut caption = Text::new();
+ let _ = write!(
+ caption,
+ "{} used / {}",
+ Text::bytes(f.total - f.free).as_str(),
+ Text::bytes(f.total).as_str()
+ );
+ label(
+ b,
+ summary,
+ caption.as_str(),
+ Rect::new(40, 64, 338, 36),
+ 1,
+ SECONDARY,
+ 2,
+ false,
+ )?;
+ b.submit(lv)?;
+ chart(b, summary, 22, 106, 374, &values)?;
+ b.flags(summary, &[Flag::Clickable], &[])?;
+ s.bind(b, summary, 8)?;
+ b.submit(lv)?;
+ let mut indices = [0usize; 5];
+ let mut n = 0;
+ for i in 0..5 {
+ if i < 4 && values[i] > 0 {
+ indices[n] = i;
+ n += 1;
+ }
+ }
+ let first = if rows > 1 { (n + 1) / 2 } else { n };
+ for row in 0..rows {
+ let range = if row == 0 { 0..first } else { first..n };
+ let mut width = 0;
+ for (position, k) in range.clone().enumerate() {
+ width += model::legend_width(names[indices[k]]) + 14;
+ if position > 0 {
+ width += 18;
+ }
+ }
+ let mut x = 22 + (374 - width) / 2;
+ for k in range {
+ let i = indices[k];
+ shape(
+ b,
+ summary,
+ x,
+ 150 + row as i16 * 32,
+ 8,
+ 8,
+ CHART_COLORS[i],
+ 4,
+ )?;
+ let w = model::legend_width(names[i]);
+ label(
+ b,
+ summary,
+ names[i],
+ Rect::new(x + 14, 144 + row as i16 * 32, w + 4, 32),
+ 1,
+ SECONDARY,
+ 0,
+ false,
+ )?;
+ x += w + 32;
+ }
+ b.submit(lv)?;
+ }
+ } else {
+ note(
+ b,
+ lv,
+ s.root,
+ if inv.error == -95 {
+ "Update App Loader to use Storage."
+ } else {
+ "Usage unavailable. Refresh to try again."
+ },
+ )?;
+ }
+ if stale {
+ note(
+ b,
+ lv,
+ s.root,
+ "Refresh did not finish. Showing the previous reading.",
+ )?;
+ }
+ row(
+ b,
+ lv,
+ &mut s,
+ "Apps",
+ count_label(inv, Category::App(0)).as_str(),
+ 1,
+ false,
+ )?;
+ row(
+ b,
+ lv,
+ &mut s,
+ "Watch faces",
+ count_label(inv, Category::Face).as_str(),
+ 2,
+ false,
+ )?;
+ row(
+ b,
+ lv,
+ &mut s,
+ "Other files",
+ count_label(inv, Category::Other).as_str(),
+ 3,
+ false,
+ )?;
+ row(b, lv, &mut s, "System storage", "Firmware & data", 4, true)?;
+ row(
+ b,
+ lv,
+ &mut s,
+ "Usage details",
+ "Files & allocation",
+ 8,
+ false,
+ )?;
+ if inv.partial {
+ note(
+ b,
+ lv,
+ s.root,
+ "File list is incomplete. Some folders could not be read or exceed scan limits.",
+ )?;
+ }
+ row(
+ b,
+ lv,
+ &mut s,
+ if reading { "Cancel scan" } else { "Refresh" },
+ "",
+ REFRESH,
+ true,
+ )?;
+ }
+ Page::Apps => {
+ let mut found = false;
+ for i in 0..16 {
+ let total = inv.app_total(i);
+ let a = inv.apps[i as usize];
+ if a.valid || total > 0 {
+ found = true;
+ let mut name = Text::new();
+ if a.valid {
+ let _ = write!(name, "{}", a.name());
+ } else {
+ let _ = write!(name, "App slot {}", i + 1);
+ }
+ navigation(
+ b,
+ lv,
+ &mut s,
+ name.as_str(),
+ Text::bytes(total).as_str(),
+ 16 + i as u16,
+ if a.icon {
+ Icon::Installed(i)
+ } else {
+ Icon::App(name.as_str().chars().next().unwrap_or('A'))
+ },
+ )?;
+ }
+ }
+ if !found {
+ note(
+ b,
+ lv,
+ s.root,
+ if inv.ready {
+ "No app files found."
+ } else if inv.error < 0 {
+ "File scan unavailable. Refresh to try again."
+ } else {
+ "Reading app files..."
+ },
+ )?;
+ }
+ }
+ Page::Faces(offset) | Page::Other(offset) => {
+ let cat = if matches!(page, Page::Faces(_)) {
+ Category::Face
+ } else {
+ Category::Other
+ };
+ let mut found = false;
+ let mut ordinal = 0usize;
+ let mut more = false;
+ for (i, f) in inv.files[..inv.count].iter().enumerate() {
+ if f.category == cat {
+ let at = ordinal;
+ ordinal += 1;
+ if at < (offset as usize) * 12 {
+ continue;
+ }
+ if at >= (offset as usize + 1) * 12 {
+ more = true;
+ continue;
+ }
+ found = true;
+ row(
+ b,
+ lv,
+ &mut s,
+ f.name(),
+ Text::bytes(f.size).as_str(),
+ 32 + i as u16,
+ false,
+ )?;
+ }
+ }
+ if offset > 0 {
+ row(b, lv, &mut s, "Previous files", "", 201, true)?;
+ }
+ if more {
+ row(b, lv, &mut s, "More files", "", 200, true)?;
+ }
+ if !found {
+ let empty = block(b, s.root, 126)?;
+ icon(
+ b,
+ lv,
+ empty,
+ if matches!(page, Page::Faces(_)) {
+ Icon::Face
+ } else {
+ Icon::Folder
+ },
+ 187,
+ 44,
+ )?;
+ note(
+ b,
+ lv,
+ s.root,
+ if !inv.ready && inv.error < 0 {
+ "File scan unavailable. Refresh to try again."
+ } else if !inv.ready {
+ "Reading files..."
+ } else if inv.partial {
+ "No matching files found in the partial scan."
+ } else {
+ "No files found."
+ },
+ )?;
+ }
+ if inv.partial {
+ note(b, lv, s.root, "Partial file list. Refresh to try again.")?;
+ }
+ if matches!(page, Page::Faces(_)) {
+ note(
+ b,
+ lv,
+ s.root,
+ "Lists .wfc files by filename. Built-in faces are part of system resources.",
+ )?;
+ }
+ }
+ Page::App(slot) => {
+ let a = inv.apps[slot as usize];
+ if a.valid && a.name().len() > 16 {
+ note(b, lv, s.root, a.name())?;
+ }
+ value(b, lv, &mut s, "Files total", inv.app_total(slot))?;
+ for (i, f) in inv.files[..inv.count].iter().enumerate() {
+ if f.category == Category::App(slot) {
+ let name = if f.name().as_bytes()[2..].eq_ignore_ascii_case(b"pkg") {
+ "App package"
+ } else if f.name().as_bytes()[2..].eq_ignore_ascii_case(b"dat") {
+ "Saved data"
+ } else {
+ "Widget record"
+ };
+ row(
+ b,
+ lv,
+ &mut s,
+ name,
+ Text::bytes(f.size).as_str(),
+ 32 + i as u16,
+ false,
+ )?;
+ }
+ }
+ if a.valid {
+ let mut t = Text::new();
+ let _ = write!(t, "Version {}", a.version);
+ note(b, lv, s.root, t.as_str())?;
+ }
+ }
+ Page::File(i) => {
+ let f = &inv.files[i as usize];
+ note(b, lv, s.root, f.name())?;
+ value(b, lv, &mut s, "File size", f.size)?;
+ let mut exact = Text::new();
+ let _ = write!(exact, "{} bytes", f.size);
+ note(b, lv, s.root, exact.as_str())?;
+ note(b, lv, s.root, f.path())?;
+ note(
+ b,
+ lv,
+ s.root,
+ "Logical file bytes. Space on disk may be larger.",
+ )?;
+ }
+ Page::System => {
+ row(b, lv, &mut s, "NAND", "Resources & files", 5, true)?;
+ row(b, lv, &mut s, "System flash", "Firmware & boot", 6, true)?;
+ if let Some(f) = fs {
+ value(b, lv, &mut s, "App loader file", f.loader)?;
+ }
+ note(
+ b,
+ lv,
+ s.root,
+ "Reservations are capacities, not measured used space.",
+ )?;
+ }
+ Page::Nand | Page::Nor => {
+ let dev = if page == Page::Nand { 2 } else { 0 };
+ if model::reference_layout(parts) {
+ value(
+ b,
+ lv,
+ &mut s,
+ "Chip capacity",
+ if dev == 2 {
+ model::NAND_MAIN
+ } else {
+ model::NOR_MAIN
+ },
+ )?;
+ if dev == 2 {
+ value(b, lv, &mut s, "Logical NAND", model::NAND_LOGICAL)?;
+ value(b, lv, &mut s, "Flash management", model::FTL_MANAGEMENT)?;
+ note(b, lv, s.root, "Management space is not file storage.")?;
+ }
+ } else {
+ note(
+ b,
+ lv,
+ s.root,
+ "Hardware capacity is not verified for this layout.",
+ )?;
+ }
+ for (i, p) in parts.iter().enumerate().filter(|(_, p)| p.device == dev) {
+ row(
+ b,
+ lv,
+ &mut s,
+ model::purpose(p),
+ Text::bytes(p.allocated).as_str(),
+ 128 + i as u16,
+ false,
+ )?;
+ }
+ if dev == 2 && model::reference_layout(parts) {
+ value(b, lv, &mut s, "Unpartitioned tail", model::LOGICAL_TAIL)?;
+ note(
+ b,
+ lv,
+ s.root,
+ "Tail capacity is not available as file storage.",
+ )?;
+ }
+ }
+ Page::Partition(i) => {
+ let p = &parts[i as usize];
+ note(b, lv, s.root, model::purpose(p))?;
+ value(b, lv, &mut s, "Reserved capacity", p.allocated)?;
+ row(b, lv, &mut s, "Partition name", p.name(), 0, false)?;
+ let mut t = Text::new();
+ let _ = write!(t, "0x{:08X}", p.offset);
+ row(b, lv, &mut s, "Device offset", t.as_str(), 0, false)?;
+ note(
+ b,
+ lv,
+ s.root,
+ "Reserved capacity does not report how many bytes are in use.",
+ )?;
+ }
+ Page::Accounting => {
+ if let Some(f) = fs {
+ let used = f.total - f.free;
+ let summary = block(b, s.root, 142)?;
+ label(
+ b,
+ summary,
+ Text::bytes(used).as_str(),
+ Rect::new(40, 0, 338, 64),
+ 2,
+ stock::WHITE,
+ 2,
+ false,
+ )?;
+ label(
+ b,
+ summary,
+ "Breakdown of used space",
+ Rect::new(40, 70, 338, 34),
+ 1,
+ SECONDARY,
+ 2,
+ false,
+ )?;
+ b.submit(lv)?;
+ if let Some(values) = crate::inventory::breakdown(&f, inv) {
+ let colors = CHART_COLORS;
+ chart(b, summary, 40, 116, 338, &values)?;
+ b.submit(lv)?;
+ for (i, name) in ["Apps", "App loader", "Watch faces", "Other usage"]
+ .into_iter()
+ .enumerate()
+ {
+ if values[i] == 0 {
+ continue;
+ }
+ let item = block(b, s.root, 86)?;
+ shape(b, item, 40, 28, 10, 10, colors[i], 3)?;
+ label(
+ b,
+ item,
+ name,
+ Rect::new(68, 6, 310, 40),
+ 0,
+ stock::WHITE,
+ 0,
+ false,
+ )?;
+ label(
+ b,
+ item,
+ Text::bytes(values[i]).as_str(),
+ Rect::new(68, 50, 310, 32),
+ 1,
+ SECONDARY,
+ 0,
+ false,
+ )?;
+ b.submit(lv)?;
+ }
+ note(
+ b,
+ lv,
+ s.root,
+ "Other usage includes remaining files and unassigned allocation.",
+ )?;
+ } else {
+ note(
+ b,
+ lv,
+ s.root,
+ "A complete, consistent scan is needed for the breakdown.",
+ )?;
+ }
+ value(b, lv, &mut s, "Free space", f.free)?;
+ value(b, lv, &mut s, "File-data capacity", f.total)?;
+ note(
+ b,
+ lv,
+ s.root,
+ "Firmware and built-in resources are separate.",
+ )?;
+ } else {
+ note(b, lv, s.root, "No usage reading is available.")?;
+ }
+ }
+ }
+ if page != Page::Home {
+ row(b, lv, &mut s, "Back", "", BACK, true)?;
+ }
+ Ok(s)
+}
diff --git a/apps/storage/src/ui_tests.rs b/apps/storage/src/ui_tests.rs
new file mode 100644
index 0000000..ff27215
--- /dev/null
+++ b/apps/storage/src/ui_tests.rs
@@ -0,0 +1,182 @@
+use crate::{
+ inventory::{App, Category, File, Inventory},
+ ui::{self, Page},
+};
+use cmf_wp2_app::{Api, Event, Time, lv::*, stock};
+use std::cell::RefCell;
+use wp2_core::lvcmd::{self, Table};
+thread_local! {static STATE:RefCell<(Table,u8,usize)>=RefCell::new((Table::new(),0,0));}
+extern "C" fn submit(p: *const u8, n: usize) -> i32 {
+ let bytes = unsafe { std::slice::from_raw_parts(p, n) };
+ STATE.with(|s| {
+ let mut s = s.borrow_mut();
+ if let Err(e) = lvcmd::validate(bytes, &s.0, s.1) {
+ return e.code();
+ }
+ for rec in lvcmd::records(bytes) {
+ let r = rec.unwrap();
+ if let lvcmd::Rec::Font { slot, .. } = r {
+ s.1 |= 1 << slot;
+ }
+ lvcmd::apply(&mut s.0, &r);
+ let live = (1..=192).filter(|&i| s.0.class(i).is_some()).count();
+ s.2 = s.2.max(live);
+ }
+ 0
+ })
+}
+extern "C" fn rect(_: i16, _: i16, _: u16, _: u16, _: u16) {}
+extern "C" fn text(_: i16, _: i16, _: *const u8, _: usize, _: u16) {}
+extern "C" fn noop() {}
+extern "C" fn event(_: *mut Event, _: u32) -> bool {
+ false
+}
+extern "C" fn motor(_: u16, _: u16) -> i32 {
+ 0
+}
+extern "C" fn millis() -> u32 {
+ 0
+}
+extern "C" fn exit(_: i32) -> ! {
+ std::process::abort()
+}
+extern "C" fn bytes(_: *const u8, _: usize) -> i32 {
+ 0
+}
+extern "C" fn bytes_mut(_: *mut u8, _: usize) -> i32 {
+ 0
+}
+extern "C" fn time(_: *mut Time) -> i32 {
+ 0
+}
+extern "C" fn battery() -> i32 {
+ 0
+}
+extern "C" fn screen(_: bool) -> i32 {
+ 0
+}
+extern "C" fn flag(_: bool) {}
+fn api() -> Api {
+ Api {
+ abi: cmf_wp2_app::ABI,
+ abi_minor: cmf_wp2_app::ABI_MINOR,
+ width: 466,
+ height: 466,
+ fill_rect: rect,
+ draw_text: text,
+ present: noop,
+ next_event: event,
+ motor,
+ millis,
+ exit,
+ send_msg: bytes,
+ recv_msg: bytes_mut,
+ load_data: bytes_mut,
+ save_data: bytes,
+ get_time: time,
+ get_battery: battery,
+ screen_on: screen,
+ lv_submit: submit,
+ own_back: flag,
+ }
+}
+#[test]
+fn all_screens_and_nested_full_catalog_fit_loader_budgets() {
+ STATE.with(|s| *s.borrow_mut() = (Table::new(), 0, 0));
+ let api = api();
+ let lv = api.lv().unwrap();
+ let mut b = Batch::new().unwrap();
+ stock::font(&mut b).unwrap();
+ b.font(1, StockFont::F24M).unwrap();
+ b.font(2, StockFont::F48M).unwrap();
+ b.font(3, StockFont::F36M).unwrap();
+ b.submit(&lv).unwrap();
+ let mut inv = Inventory::new();
+ inv.ready = true;
+ inv.partial = true;
+ for slot in 0..16 {
+ let mut name = [0; 24];
+ name[..3].copy_from_slice(b"App");
+ inv.apps[slot] = App {
+ name,
+ version: 1,
+ valid: true,
+ icon: true,
+ };
+ }
+ for i in 0..96 {
+ let mut path = [0; 96];
+ let s = format!("/NAND:/test/{i}.wfc");
+ path[..s.len()].copy_from_slice(s.as_bytes());
+ inv.files[i] = File {
+ path,
+ size: 4096,
+ category: if i < 16 {
+ Category::App(i as u8)
+ } else {
+ Category::Face
+ },
+ };
+ }
+ inv.count = 96;
+ let fs = cmf_wp2_app::storage::Filesystem {
+ total: 10223616,
+ free: 8000000,
+ apps: 65536,
+ loader: 65536,
+ allocation_unit: 2048,
+ ..Default::default()
+ };
+ let mut parts = [cmf_wp2_app::storage::Partition {
+ allocated: 65536,
+ device: 2,
+ ..Default::default()
+ }; 30];
+ for (i, p) in parts.iter_mut().enumerate() {
+ p.offset = i as u32 * 65536;
+ p.name[..4].copy_from_slice(b"test");
+ }
+ let home = ui::render(&mut b, &lv, Page::Home, &parts, Some(fs), &inv, false, true).unwrap();
+ home.visible(&mut b, false).unwrap();
+ b.submit(&lv).unwrap();
+ for missing_icons in [false, true] {
+ for a in &mut inv.apps {
+ a.icon = !missing_icons;
+ }
+ for page in [
+ Page::Apps,
+ Page::Faces(0),
+ Page::Faces(8),
+ Page::Other(0),
+ Page::System,
+ Page::Nand,
+ Page::Nor,
+ Page::Accounting,
+ ] {
+ let view = ui::render(&mut b, &lv, page, &parts, Some(fs), &inv, false, false).unwrap();
+ view.visible(&mut b, false).unwrap();
+ b.submit(&lv).unwrap();
+ for child in [Page::App(15), Page::File(2), Page::Partition(0)] {
+ let detail =
+ ui::render(&mut b, &lv, child, &parts, Some(fs), &inv, false, false).unwrap();
+ b.del(detail.root).unwrap();
+ b.submit(&lv).unwrap();
+ }
+ b.del(view.root).unwrap();
+ b.submit(&lv).unwrap();
+ }
+ }
+ b.del(home.root).unwrap();
+ b.submit(&lv).unwrap();
+ for error in [-95, -5] {
+ let mut inv = Inventory::new();
+ inv.error = error;
+ let v = ui::render(&mut b, &lv, Page::Home, &[], None, &inv, false, false).unwrap();
+ b.del(v.root).unwrap();
+ b.submit(&lv).unwrap();
+ }
+ STATE.with(|s| {
+ assert!(s.borrow().2 <= 192);
+ println!("peak live objects: {}", s.borrow().2);
+ });
+}
diff --git a/apps/storage/store.md b/apps/storage/store.md
new file mode 100644
index 0000000..50e62d4
--- /dev/null
+++ b/apps/storage/store.md
@@ -0,0 +1,14 @@
+Storage shows the writable space available on the watch, with a segmented usage bar and sizes for installed
+apps, the App Loader, watch faces and other files. System storage lists firmware and resource reservations
+separately from free file space.
+
+Tap a category for details. The crown scrolls, the crown button goes back, and Refresh scans again. The app is
+read-only: it does not delete files, remove apps or change firmware. File sizes are logical lengths;
+filesystem allocation and metadata can make occupied space larger. Incomplete scans are labelled rather than
+presented as complete totals.
+
+## Requirements
+
+CMF Watch Pro 2 running patched firmware 1.0.0.73 and an App Loader providing
+storage-inspection service v1. On an older loader, the app displays an update message. No phone connection is
+needed. Watch 3 Pro support has not been established.
diff --git a/apps/storage/store.toml b/apps/storage/store.toml
new file mode 100644
index 0000000..f7b0fdc
--- /dev/null
+++ b/apps/storage/store.toml
@@ -0,0 +1,5 @@
+name = "Storage"
+summary = "View free space, installed app sizes, watch faces and the watch storage layout"
+version = "0.1.0"
+author = "Arnav Kumar"
+screenshots = ["shots/overview.png", "shots/usage.png", "shots/apps.png", "shots/apps-more.png", "shots/watchfaces.png", "shots/system.png"]