From 80385cb6e68ccf43b2257faf35465f7ec898c2ad Mon Sep 17 00:00:00 2001 From: brainbudt <32467201+brainbudt@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:51:15 +0100 Subject: [PATCH 1/2] feat(i14-ui): upgrade terminal keyboard, add Docker Hub & system pages, and ship i14-web Upgrade the Rust on-device framebuffer UI and add an optional loopback-only web dashboard while keeping Cargo.lock unchanged (zero new dependencies): - Terminal keyboard & input: multitouch rollover, key previews, long-press digits/symbols, Alt & Ctrl-lock, expanded shortcut bar, spacebar trackpad, modified arrow keys in VT, cursor-capable TextField, volume-key actions, and safe SYN_DROPPED cancellation. - Terminal UX: 90-degree landscape rotation with inverse touch mapping, 4 PTY tabs, font zoom (S/M/L), clipboard copy/paste, and command snippets. - New GUI pages: OpenRC services/Unbound DNS/system monitor/logs, Docker Hub browser & remote/local container manager, local Alpine apk app store with VPN & torch controls, and read-only file browser/text viewer with current_cmd protection. - Web dashboard: optional fail-closed i14-web binary and OpenRC service bound to loopback with private 0600 token-file auth. - Core polish: 3x3 Home grid, scrollable Settings with HW-CAR info, Hidden Wi-Fi password toggle, explicit I14_ENABLE_TERMINAL=1 opt-in, and render-gated Bluetooth confirmation buttons. --- SECURITY.md | 9 + rootfs/overlay/etc/conf.d/i14-web | 9 + rootfs/overlay/etc/init.d/i14-web | 25 + rust/README.md | 8 +- rust/crates/i14-ui/src/app.rs | 1077 +++++++++-- rust/crates/i14-ui/src/apps.rs | 1416 ++++++++++++++ rust/crates/i14-ui/src/bin/i14-web.rs | 201 ++ rust/crates/i14-ui/src/canvas.rs | 124 +- rust/crates/i14-ui/src/docker.rs | 1963 ++++++++++++++++++++ rust/crates/i14-ui/src/files.rs | 793 ++++++++ rust/crates/i14-ui/src/input.rs | 525 ++++-- rust/crates/i14-ui/src/lib.rs | 6 + rust/crates/i14-ui/src/main.rs | 76 +- rust/crates/i14-ui/src/runner.rs | 135 +- rust/crates/i14-ui/src/services.rs | 1327 +++++++++++++ rust/crates/i14-ui/src/term.rs | 101 +- rust/crates/i14-ui/src/terminal_ui.rs | 645 +++++++ rust/crates/i14-ui/src/vt.rs | 20 +- rust/crates/i14-ui/src/web.rs | 1078 +++++++++++ rust/crates/i14-ui/src/widgets.rs | 624 ++++++- rust/crates/i14-ui/tests/app_parity.rs | 137 +- rust/crates/i14-ui/tests/vt_parity.rs | 7 +- rust/crates/i14-ui/tests/widgets_parity.rs | 62 +- rust/stage-rootfs.sh | 2 +- tests/test_i14_web_service.py | 48 + 25 files changed, 9930 insertions(+), 488 deletions(-) create mode 100644 rootfs/overlay/etc/conf.d/i14-web create mode 100755 rootfs/overlay/etc/init.d/i14-web create mode 100644 rust/crates/i14-ui/src/apps.rs create mode 100644 rust/crates/i14-ui/src/bin/i14-web.rs create mode 100644 rust/crates/i14-ui/src/docker.rs create mode 100644 rust/crates/i14-ui/src/files.rs create mode 100644 rust/crates/i14-ui/src/services.rs create mode 100644 rust/crates/i14-ui/src/terminal_ui.rs create mode 100644 rust/crates/i14-ui/src/web.rs create mode 100644 tests/test_i14_web_service.py diff --git a/SECURITY.md b/SECURITY.md index 9f28dc4..cc16a2d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -34,3 +34,12 @@ hardened general-purpose operating system distribution: hashes (`--rescue-password-hash-file`), Wi-Fi credentials, Bluetooth link keys (`bt-keys`), firmware dumps and NVRAM/NVDATA must never be committed to Git. + +The optional `i14-web` dashboard is disabled by default and serves plain HTTP +only on loopback (default `127.0.0.1:8080`). Supply a random bearer token +through `--token-file PATH`. The file must be a regular file owned by the +service user with owner-only permissions (for example, `0600`). +For remote access, forward the port with +`ssh -L 8080:127.0.0.1:8080 root@172.16.42.1` and open +`http://127.0.0.1:8080/` on the client. The explicit +`--allow-unauthenticated` option grants local clients access to service controls. diff --git a/rootfs/overlay/etc/conf.d/i14-web b/rootfs/overlay/etc/conf.d/i14-web new file mode 100644 index 0000000..f044e29 --- /dev/null +++ b/rootfs/overlay/etc/conf.d/i14-web @@ -0,0 +1,9 @@ +# The safest way to access the dashboard is to keep it on loopback and use SSH: +# ssh -L 8080:127.0.0.1:8080 root@172.16.42.1 +# Then open http://127.0.0.1:8080/ on the SSH client. +I14_WEB_BIND="127.0.0.1:8080" + +# Put a random token in this file on the phone and restrict it to the owner (0600). +I14_WEB_TOKEN_FILE="/mnt/data/media/0/i14-linux/web.token" +# Set to yes only for explicitly unauthenticated loopback access. +I14_WEB_ALLOW_UNAUTHENTICATED=no diff --git a/rootfs/overlay/etc/init.d/i14-web b/rootfs/overlay/etc/init.d/i14-web new file mode 100755 index 0000000..79638c0 --- /dev/null +++ b/rootfs/overlay/etc/init.d/i14-web @@ -0,0 +1,25 @@ +#!/sbin/openrc-run +description="I14 web dashboard" +command=/usr/libexec/i14-rs/i14-web +supervisor=supervise-daemon +respawn_delay=10 + +: "${I14_WEB_BIND:=127.0.0.1:8080}" +: "${I14_WEB_TOKEN_FILE:=/mnt/data/media/0/i14-linux/web.token}" +command_args='--bind "$I14_WEB_BIND"' +if [ "${I14_WEB_ALLOW_UNAUTHENTICATED:-no}" = yes ]; then + command_args="$command_args --allow-unauthenticated" +else + command_args="$command_args"' --token-file "$I14_WEB_TOKEN_FILE"' +fi + +depend() { + after i14-usbnet i14-wifi +} + +start_pre() { + [ "${I14_WEB_ALLOW_UNAUTHENTICATED:-no}" = yes ] && return 0 + [ -f "$I14_WEB_TOKEN_FILE" ] && [ -r "$I14_WEB_TOKEN_FILE" ] && [ -s "$I14_WEB_TOKEN_FILE" ] && return 0 + eerror "i14-web requires a readable, nonempty token file: $I14_WEB_TOKEN_FILE" + return 1 +} diff --git a/rust/README.md b/rust/README.md index 9fd622f..4710c41 100644 --- a/rust/README.md +++ b/rust/README.md @@ -9,7 +9,7 @@ image integration and device acceptance. | `i14-sys` | the only place with `unsafe`: framebuffer, evdev, pty, getrandom, uname | | `i14-probe` | read-only check of Rust's runtime and those interfaces on the phone | | `i14-config` | the shared settings file (`ui.json`, PIN) and the charge guard's status file | -| `i14-ui` | the interface (`i14-ui` binary) and the boot splash (`i14-splash` binary) | +| `i14-ui` | the touch interface (`i14-ui`), boot splash (`i14-splash`) and optional web dashboard (`i14-web`) | | `i14-power` | the charge guard (`i14-battery-guard`, service `i14-power`) | | `i14-cpufreq` | the screen-off CPU clock policy (`i14-cpufreq`) | | `i14-netwatch` | the Wi-Fi watchdog (`i14-netwatch`) | @@ -26,6 +26,12 @@ Rust uses `/usr/libexec/i14-rs/` and an `i14_impl` setting per migrated service. using the same package set: building one package alone can select different Cargo features, such as `serde_json`'s `float_roundtrip` from `i14-power`. +To use the optional dashboard, install the staged `i14-web` at +`/usr/libexec/i14-rs/i14-web`, provision the token described in +[`/etc/conf.d/i14-web`](../rootfs/overlay/etc/conf.d/i14-web), then run +`rc-service i14-web start`. Enable it at boot with `rc-update add i14-web default` +only if desired. + The pixel parity tests compare with the Python sources in `rootfs/overlay` and need `python3` and `I14_FONTS` set to a directory with the phone's Terminus fonts (`ter-118n`, `ter-120n`, `ter-124b`, `ter-132b` `.psf.gz` from `/usr/share/consolefonts`); diff --git a/rust/crates/i14-ui/src/app.rs b/rust/crates/i14-ui/src/app.rs index 7e2a83c..6375ea4 100644 --- a/rust/crates/i14-ui/src/app.rs +++ b/rust/crates/i14-ui/src/app.rs @@ -5,16 +5,25 @@ //! Pages do not call the app; they queue `Action`s that the app carries out //! once the page's method returns. -use std::io; +use crate::{ + apps::{AppsPage, LinuxApkApi, LinuxVpnApi, SysfsTorchApi}, + docker::{CliContainerApi, CurlDockerHubApi, DockerPage, CONFIG_PATH}, + files::FilesPage, + services::{LinuxSystemApi, SystemPage}, + terminal_ui::{ + map_volume_key, Clipboard, SnippetBar, TabManager, TermFonts, TermToolbar, ToolbarAction, + }, +}; +use std::{io, path::PathBuf}; use i14_config::{Config, CHARGE_LIMITS, TIMEOUTS}; use i14_sys::LocalTime; use crate::bt::state::{ACCEPT_RECT, REJECT_RECT}; use crate::bt::Bluetooth; -use crate::canvas::{Canvas, Rgb}; +use crate::canvas::{Canvas, Rgb, Rotation}; use crate::font::Font; -use crate::input::{Gesture, Key, KeyName}; +use crate::input::{Gesture, Key, KeyName, VolumeButton, KEY_VOLUMEDOWN, KEY_VOLUMEUP}; use crate::status::{address_of, palette, Battery}; use crate::term::Session; use crate::vt::{Cell, Color, BOLD, REVERSE}; @@ -194,6 +203,9 @@ pub trait Env { fn local_time(&self) -> LocalTime; fn battery(&self) -> Battery; fn battery_level(&self) -> String; + fn charge_status(&self) -> Option { + crate::status::Paths::default().status(self.monotonic()) + } fn addresses(&self) -> Vec<(String, String)>; fn free(&self, path: &str) -> String; fn uptime(&self) -> i64; @@ -202,24 +214,62 @@ pub trait Env { fn data_dir(&self) -> String; } -pub struct Fonts { +pub struct Fonts { pub big: Font, pub mid: Font, pub small: Font, - pub term: Font, + pub term: T, +} + +/// Page factories keep workers and device handles scoped to an open page. +pub struct AppBackends { + pub system: Box SystemPage>, + pub docker: Box DockerPage>, + pub apps: Box AppsPage>, + pub files_dir: PathBuf, +} + +impl Default for AppBackends { + fn default() -> Self { + Self { + system: Box::new(|w, h| SystemPage::new(w, h, Box::new(LinuxSystemApi))), + docker: Box::new(|w, h| { + DockerPage::new( + w, + h, + CONFIG_PATH, + Box::new(CurlDockerHubApi), + Box::new(CliContainerApi), + ) + }), + apps: Box::new(|w, h| { + AppsPage::new( + w, + h, + Box::new(LinuxApkApi), + Box::new(LinuxVpnApi), + Box::new(SysfsTorchApi::new()), + ) + }), + files_dir: DATA.into(), + } + } } /// Everything a page may use; the page stack itself lives in `App`. pub struct Ctx { pub width: i32, pub height: i32, - pub fonts: Fonts, + pub fonts: Fonts, pub cfg: Config, pub wifi: Box, pub bt: Bluetooth, pub screen: Box, pub env: Box, - pub session: Option, + pub tabs: TabManager, + pub rotation: Rotation, + pub terminal_enabled: bool, + pub backends: AppBackends, pub dirty: bool, pub last_activity: f64, actions: Vec, @@ -254,6 +304,10 @@ pub enum Spec { }, Hidden, Bluetooth, + System, + Docker, + Apps, + Files, Settings, PinSet, Lock { @@ -285,32 +339,6 @@ fn py_err(e: &io::Error) -> String { } } -/// The page base's touch: the keyboard first, then every button; an "up" that a -/// button took ends it. Returns the clicked button and a typed key, if any. -fn base_touch( - buttons: &mut [Button], - kb: Option<&mut Keyboard>, - ev: Gesture, - now: f64, -) -> (Option, Option) { - if let Some(kb) = kb { - let (handled, key) = kb.touch(ev, instant(now)); - if handled { - return (None, key); - } - } - for (i, b) in buttons.iter_mut().enumerate() { - let (handled, clicked) = b.touch(ev); - if clicked { - return (Some(i), None); - } - if handled && matches!(ev, Gesture::Up(..)) { - return (None, None); - } - } - (None, None) -} - /// Buttons first (any that takes the event ends it), as the list pages do. fn buttons_first(buttons: &mut [Button], ev: Gesture) -> (bool, Option) { for (i, b) in buttons.iter_mut().enumerate() { @@ -330,7 +358,7 @@ fn draw_buttons(buttons: &[Button], c: &mut Canvas, font: &Font) { /// Keyboard key-repeat timing runs on `Instant`; this maps the app's monotonic /// seconds onto one fixed origin so fake clocks in tests work too. -fn instant(secs: f64) -> std::time::Instant { +pub(crate) fn instant(secs: f64) -> std::time::Instant { use std::sync::OnceLock; static ORIGIN: OnceLock = OnceLock::new(); let origin = *ORIGIN.get_or_init(std::time::Instant::now); @@ -348,10 +376,14 @@ pub struct Home { cache_at: f64, } -const HOME_GRID: [(&str, Spec); 5] = [ +const HOME_GRID: [(&str, Spec); 9] = [ ("Terminal", Spec::Terminal), ("Wi-Fi", Spec::Wifi), ("Bluetooth", Spec::Bluetooth), + ("Systeem", Spec::System), + ("Docker", Spec::Docker), + ("Apps", Spec::Apps), + ("Bestanden", Spec::Files), ("Instellingen", Spec::Settings), ("Aan/uit", Spec::Power), ]; @@ -362,8 +394,8 @@ impl Home { .iter() .enumerate() .map(|(i, (label, _))| { - let (col, row) = ((i % 2) as i32, (i / 2) as i32); - Button::new(rect(30 + col * 340, 900 + row * 200, 320, 170), *label) + let (col, row) = ((i % 3) as i32, (i / 3) as i32); + Button::new(rect(20 + col * 230, 890 + row * 235, 220, 210), *label) }) .collect(); Self { @@ -480,35 +512,55 @@ impl Home { 1, None, ); - draw_buttons(&self.buttons, c, &f.mid); + for (button, (_, spec)) in self.buttons.iter().zip(&HOME_GRID) { + if cx.terminal_enabled || *spec != Spec::Terminal { + button.draw(c, &f.mid); + } + } } } pub struct TerminalPage { pub keyboard: Keyboard, pub kb_on: bool, - pub back: usize, pub drag: Option<(i32, usize, bool)>, - pub toggle: Button, - /// Python's TerminalPage has an empty `buttons` list; the toggle is separate. - no_buttons: Vec +

+ +
+

Accu · HW-CAR

—

+

Netwerk

+

Opslag

+

Systeem

+

Services

+

Logs

+

Docker Hub

    +"##; + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::sync::Mutex; + + #[derive(Default)] + struct Fake { + actions: Mutex>, + } + impl WebBackend for Fake { + fn status_json(&self) -> Value { + json!({"battery":{"cap":"~78"}}) + } + fn services_json(&self) -> Value { + json!([{"name":"unbound","state":"started"}]) + } + fn service_action(&self, name: &str, action: &str) -> Result { + self.actions + .lock() + .unwrap() + .push(format!("{name}/{action}")); + Ok("done".into()) + } + fn logs_json(&self, lines: usize) -> Value { + json!([format!("limit {lines}")]) + } + fn docker_hub_search(&self, q: &str) -> Result { + Ok(json!({"query":q})) + } + } + + fn server(token: Option<&str>) -> WebServer { + WebServer::new( + "127.0.0.1:0".parse().unwrap(), + token.map(str::to_string), + token.is_none(), + ) + .unwrap() + } + + #[test] + fn log_reader_rejects_special_files_and_limits_the_tail() { + let dir = std::env::temp_dir().join(format!("i14-web-log-{}", std::process::id())); + fs::create_dir(&dir).unwrap(); + let log = dir.join("messages"); + let mut bytes = vec![b'a'; LOG_BYTES + 32]; + bytes[LOG_BYTES] = b'z'; + fs::write(&log, &bytes).unwrap(); + assert_eq!(log_tail(&log).unwrap(), bytes[32..]); + let link = dir.join("symlink"); + std::os::unix::fs::symlink(&log, &link).unwrap(); + assert!(log_tail(&link).is_err()); + assert!(log_tail(&dir).is_err()); + let fifo = dir.join("fifo"); + assert!(Command::new("mkfifo") + .arg(&fifo) + .status() + .unwrap() + .success()); + assert!(log_tail(&fifo).is_err()); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn log_fallback_deadline_bounds_silent_commands() { + let start = Instant::now(); + assert_eq!( + command_output("sleep", &["15"], 1, LOG_BYTES) + .unwrap_err() + .kind(), + io::ErrorKind::TimedOut + ); + assert!(start.elapsed() < Duration::from_secs(10)); + } + + #[test] + fn anonymous_mutations_require_same_origin_or_dashboard_header() { + let server = server(None); + let backend = Fake::default(); + for (headers, expected) in [ + ("Host: localhost", 403), + ("Host: localhost\r\nX-I14-Web: 0", 403), + ("Host: example.org\r\nX-I14-Web: 1", 403), + ("Host: localhost:8080\r\nOrigin: http://localhost:8081", 403), + ("Host: localhost:8080\r\nOrigin: http://localhost:8080", 200), + ("Host: [::1]:8080\r\nOrigin: http://[::1]:8080", 200), + ("Host: localhost\r\nx-i14-web: 1", 200), + ] { + let raw = format!("POST /api/services/unbound/restart HTTP/1.1\r\n{headers}\r\n\r\n"); + assert_eq!( + server + .handle_request(&parse_http_request(raw.as_bytes()).unwrap(), &backend) + .status, + expected, + "{headers}" + ); + } + assert_eq!(backend.actions.lock().unwrap().len(), 3); + } + + #[test] + fn rejects_malformed_http_and_ambiguous_framing() { + for head in [ + "GET / HTTP/1.0\r\nHost: ok", + "GET / HTTP/1.1\r\nHost: ok", + "GET https://host/ HTTP/1.1\r\nHost: ok", + "GET / HTTP/1.1", + "GET / HTTP/1.1\r\nHost:", + "GET / HTTP/1.1\r\nHost: a\r\nHoSt: b", + "POST / HTTP/1.1\r\nHost: localhost\r\nX-I14-Web: 1\r\nx-i14-web: 0", + "GET / HTTP/1.1\r\nHost : x", + "GET / HTTP/1.1\r\nHost: a\nX: y", + "GET / HTTP/1.1\r\nHost: a\r\n Authorization: x", + "GET / HTTP/1.1\r\nHost: a\r\nAuthorization: x\r\nAuthorization: y", + "POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: chunked", + "POST / HTTP/1.1\r\nHost: a\r\nContent-Length: +0", + "POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 0\r\nContent-Length: 0", + ] { + assert_eq!( + parse_http_request(format!("{head}\r\n\r\n").as_bytes()).err(), + Some(400), + "{head}" + ); + } + assert_eq!( + parse_http_request(b"GET / HTTP/1.1\r\nHost: a\r\n").err(), + Some(400) + ); + assert_eq!( + parse_http_request(b"POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 16385\r\n\r\n") + .err(), + Some(413) + ); + let prefix = "GET / HTTP/1.1\r\nHost: x\r\nX-Fill: "; + for (size, err) in [(HEADER_LIMIT, None), (HEADER_LIMIT + 1, Some(431))] { + let msg = format!("{prefix}{}\r\n\r\n", "a".repeat(size - prefix.len() - 4)); + assert_eq!(parse_http_request(msg.as_bytes()).err(), err); + } + } + + #[test] + fn authentication_policy_and_secret_comparison() { + for address in [ + "127.0.0.1:0", + "[::1]:0", + "0.0.0.0:0", + "[::]:0", + "192.0.2.1:0", + ] { + let addr: SocketAddr = address.parse().unwrap(); + assert!(WebServer::new(addr, None, false).is_err()); + assert_eq!( + WebServer::new(addr, None, true).is_ok(), + addr.ip().is_loopback() + ); + assert_eq!( + WebServer::new(addr, Some("test-only".into()), false).is_ok(), + addr.ip().is_loopback() + ); + for bad in ["", " x", "x\ny"] { + assert!(WebServer::new(addr, Some(bad.into()), false).is_err()); + } + } + let t = Token::new("test-only").unwrap(); + for s in [ + "", + "Test-only", + "test-onlY", + "test-onl", + "test-onlyx", + "test-only\0", + ] { + assert!(!t.matches(s)); + } + assert!(t.matches("test-only")); + } + + #[test] + fn rejects_unsafe_inputs_before_backend_calls() { + let backend = Fake::default(); + let server = server(None); + for target in [ + "/api/services/../restart", + "/api/services/-x/start", + "/api/services/a/b/start", + "/api/services/a%2Fb/start", + "/api/services/x/exec", + "/api/services/x/restart?y=1", + ] { + let raw = format!("POST {target} HTTP/1.1\r\nHost: localhost\r\nX-I14-Web: 1\r\n\r\n"); + assert_eq!( + server + .handle_request(&parse_http_request(raw.as_bytes()).unwrap(), &backend) + .status, + 400 + ); + } + for headers in [ + "Host: example.org", + "Host: localhost\r\nOrigin: http://other.test", + "Host: localhost\r\nOrigin: null", + "Host: localhost\r\nOrigin: https://localhost", + ] { + let raw = format!("POST /api/services/unbound/restart HTTP/1.1\r\n{headers}\r\n\r\n"); + assert_eq!( + server + .handle_request(&parse_http_request(raw.as_bytes()).unwrap(), &backend) + .status, + 403 + ); + } + assert!(backend.actions.lock().unwrap().is_empty()); + for path in [ + "/api/logs?lines=0", + "/api/logs?lines=201", + "/api/logs?n=2", + "/api/docker/search", + "/api/docker/search?q=%ff", + "/api/docker/search?q=%1", + "/api/docker/search?q=%zz", + "/api/docker/search?q=%00", + "/api/docker/search?q=a&q=b", + "/api/docker/search?q=%26", + "/api/docker/search?q=+", + ] { + let raw = format!("GET {path} HTTP/1.1\r\nHost: localhost\r\n\r\n"); + assert_eq!( + server + .handle_request(&parse_http_request(raw.as_bytes()).unwrap(), &backend) + .status, + 400, + "{path}" + ); + } + assert_eq!(parameter("q=a%2Fb+c", "q").unwrap(), "a/b c"); + assert_eq!(encode_query("a/b c"), "a%2Fb%20c"); + assert_eq!(parse_services("Runlevel: default\n unbound [ started ]\nDynamic Runlevel: hotplugged\n i14-ui [ stopped ]\n unbound [ started ]"),json!([{"name":"i14-ui","state":"stopped"},{"name":"unbound","state":"started"}])); + } + + fn request(addr: SocketAddr, raw: &str) -> (u16, String) { + let mut socket = TcpStream::connect(addr).unwrap(); + socket + .set_read_timeout(Some(Duration::from_secs(4))) + .unwrap(); + socket.write_all(raw.as_bytes()).unwrap(); + let mut msg = String::new(); + socket.read_to_string(&mut msg).unwrap(); + let (headers, body) = msg.split_once("\r\n\r\n").unwrap(); + for header in ["X-Content-Type-Options: nosniff","X-Frame-Options: DENY","Referrer-Policy: no-referrer","Content-Security-Policy: default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'"] { + assert!(headers.contains(header),"{headers}"); + } + assert!(headers.contains(&format!("Content-Length: {}\r\n", body.len()))); + ( + headers.split_whitespace().nth(1).unwrap().parse().unwrap(), + body.into(), + ) + } + + #[test] + fn loopback_serves_all_routes_and_stops_with_idle_client() { + let server = server(Some("test-only")); + let listener = server.bind().unwrap(); + let addr = listener.local_addr().unwrap(); + let backend = Fake::default(); + let stop = AtomicBool::new(false); + std::thread::scope(|scope| { + let worker = scope.spawn(|| server.serve(listener, &backend, &stop)); + // Always stop the server if an assertion unwinds. + struct Stop<'a>(&'a AtomicBool); + impl Drop for Stop<'_> { + fn drop(&mut self) { + self.0.store(true, Ordering::Release); + } + } + let guard = Stop(&stop); + let idle = TcpStream::connect(addr).unwrap(); + let get = |method, path, headers| { + request( + addr, + &format!("{method} {path} HTTP/1.1\r\nHost: {addr}\r\n{headers}\r\n"), + ) + }; + let (code, html) = get("GET", "/", ""); + assert_eq!(code, 200); + assert!(html.contains("sessionStorage")); + assert!(!html.contains("test-only")); + for header in [ + "", + "Authorization: Bearer invalid\r\n", + "Authorization: Basic test-only\r\n", + ] { + assert_eq!(get("GET", "/api/status", header).0, 401); + assert_eq!(get("POST", "/api/services/unbound/restart", header).0, 401); + } + for (method, path, expected) in [ + ("GET", "/api/health", json!({"ok":true})), + ("GET", "/api/status", backend.status_json()), + ("GET", "/api/services", backend.services_json()), + ( + "POST", + "/api/services/unbound/restart", + json!({"message":"done"}), + ), + ("GET", "/api/logs", json!(["limit 60"])), + ("GET", "/api/logs?lines=3", json!(["limit 3"])), + ( + "GET", + "/api/docker/search?q=alpine", + json!({"query":"alpine"}), + ), + ] { + let (code, body) = get(method, path, "Authorization: Bearer test-only\r\n"); + assert_eq!(code, 200, "{path}"); + assert_eq!(serde_json::from_str::(&body).unwrap(), expected); + } + assert_eq!(request(addr, "GET / HTTP/1.1\r\n\r\n").0, 400); + assert_eq!(*backend.actions.lock().unwrap(), ["unbound/restart"]); + drop(idle); + drop(guard); + worker.join().unwrap().unwrap(); + }); + } +} diff --git a/rust/crates/i14-ui/src/widgets.rs b/rust/crates/i14-ui/src/widgets.rs index f27db92..07b57b2 100644 --- a/rust/crates/i14-ui/src/widgets.rs +++ b/rust/crates/i14-ui/src/widgets.rs @@ -2,6 +2,7 @@ //! `i14ui/widgets.py`. Instead of calling callbacks, widgets return what //! happened (clicked, row tapped, key pressed) and the page acts on it. +use std::collections::BTreeSet; use std::time::{Duration, Instant}; use crate::canvas::{Canvas, Rgb}; @@ -279,6 +280,8 @@ pub struct TextField { pub maxlen: usize, pub value: String, pub show: bool, + // None follows the end, including when a caller supplies an initial value. + cursor: Option, } /// Python's `str.isprintable()` for one character, close enough for keyboard input. @@ -295,23 +298,66 @@ impl TextField { maxlen, value: String::new(), show: false, + cursor: None, } } + /// Insertion point in Unicode scalar values. + pub fn cursor(&self) -> usize { + self.cursor + .unwrap_or(usize::MAX) + .min(self.value.chars().count()) + } + pub fn key(&mut self, k: Key) -> bool { - match k.name { + let len = self.value.chars().count(); + let cur = self.cursor(); + let byte = |pos| { + self.value + .char_indices() + .nth(pos) + .map_or(self.value.len(), |(i, _)| i) + }; + let next = match k.name { + KeyName::Named("left") => cur.saturating_sub(1), + KeyName::Named("right") => (cur + 1).min(len), + KeyName::Named("home") => 0, + KeyName::Named("end") => len, KeyName::Named("backspace") => { - self.value.pop(); - true + let prev = cur.saturating_sub(1); + self.value.replace_range(byte(prev)..byte(cur), ""); + prev + } + KeyName::Named("delete") => { + self.value.replace_range(byte(cur)..byte(cur + 1), ""); + cur } - KeyName::Char(ch) - if !k.ctrl && printable(ch) && self.value.chars().count() < self.maxlen => - { - self.value.push(ch); - true + KeyName::Char(ch) if !k.ctrl && printable(ch) && len < self.maxlen => { + self.value.insert(byte(cur), ch); + cur + 1 } - _ => false, + _ => return false, + }; + self.cursor = (next < self.value.chars().count()).then_some(next); + true + } + + fn window(&self, font: &Font) -> (usize, usize) { + let n = (self.rect.w.saturating_sub(40).max(0) as usize) / font.w.max(1); + let end_start = self.value.chars().count().saturating_sub(n); + (self.cursor().saturating_sub(n / 2).min(end_start), n) + } + + pub fn tap(&mut self, x: i32, y: i32, font: &Font) -> bool { + if !self.rect.contains(x, y) { + return false; } + let (start, n) = self.window(font); + let dx = x.saturating_sub(self.rect.x).saturating_sub(16).max(0) as usize; + let col = (dx + font.w / 2) / font.w.max(1); + let pos = start + col.min(n); + self.cursor = (pos < self.value.chars().count()).then_some(pos); + true } pub fn draw(&self, c: &mut Canvas, font: &Font, small: &Font) -> i32 { @@ -320,29 +366,30 @@ impl TextField { let fy = y + small.h as i32 + 8; let fh = h - small.h as i32 - 8; c.fill(x, fy, w, fh, PANEL); - let len = self.value.chars().count(); - let text = if self.secret && !self.show { - "*".repeat(len) - } else { - self.value.clone() - }; - let n = floor_div(w - 40, font.w as i32).max(0) as usize; - // Python's text[-0:] is the whole text. - let shown: String = if len > n && n > 0 { - text.chars().skip(len - n).collect() - } else { - text - }; - c.text( - x + 16, - fy + floor_div(fh - font.h as i32, 2), - &(shown + "_"), - font, - FG, - PANEL, - 1, - None, - ) + let (start, n) = self.window(font); + let mut shown: String = self + .value + .chars() + .skip(start) + .take(n) + .map(|ch| if self.secret && !self.show { '*' } else { ch }) + .collect(); + let cy = fy + floor_div(fh - font.h as i32, 2); + let cursor = self.cursor(); + if cursor == self.value.chars().count() { + shown.push('_'); + } + let width = c.text(x + 16, cy, &shown, font, FG, PANEL, 1, None); + if cursor < self.value.chars().count() { + c.fill( + x + 16 + ((cursor - start) * font.w) as i32, + cy, + 2, + font.h as i32, + FG, + ); + } + width } } @@ -408,22 +455,46 @@ fn layout(name: Layout) -> Vec> { } } -fn terminal_row() -> Vec { - let k = |l: &'static str, o: &'static str, w: f64| (Some(l), Some(o), w); - vec![ - k("esc", "esc", 1.0), - k("tab", "tab", 1.0), - k("ctrl", "ctrl", 1.2), - k("←", "left", 1.0), - k("↓", "down", 1.0), - k("↑", "up", 1.0), - k("→", "right", 1.0), - k("|", "|", 0.9), - k("-", "-", 0.9), - k("/", "/", 1.0), +fn terminal_rows() -> [Vec; 2] { + let row = |keys: &[(&'static str, &'static str)]| { + keys.iter() + .map(|&(label, out)| (Some(label), Some(out), 1.0)) + .collect() + }; + [ + row(&[ + ("ESC", "esc"), + ("TAB", "tab"), + ("CTRL", "ctrl"), + ("ALT", "alt"), + ("←", "left"), + ("↓", "down"), + ("↑", "up"), + ("→", "right"), + ("|", "|"), + ("-", "-"), + ]), + row(&[ + ("HOME", "home"), + ("END", "end"), + ("PGUP", "pgup"), + ("PGDN", "pgdn"), + ("DEL", "delete"), + ("^C", "^C"), + ("^D", "^D"), + ("^L", "^L"), + ("/", "/"), + ("~", "~"), + ]), ] } +fn alternate(out: &str) -> Option<&'static str> { + let ch = single_char(out)?; + let i = "qwertyuiopasdfghjklzxcvbnm,.".find(ch)?; + "1234567890@#$_&-+()*\"':;!?<>".get(i..i + 1) +} + fn arrow_fallback(label: &str) -> Option<&'static str> { Some(match label { "←" => "<", @@ -434,8 +505,10 @@ fn arrow_fallback(label: &str) -> Option<&'static str> { }) } -const REPEAT: [&str; 5] = ["backspace", "left", "right", "up", "down"]; -const MODIFIERS: [&str; 5] = ["shift", "sym", "abc", "more", "ctrl"]; +const REPEAT: [&str; 6] = ["backspace", "left", "right", "up", "down", "delete"]; +const LONG_PRESS: Duration = Duration::from_millis(350); +const TRACKPAD_STEP: i32 = 32; +const MODIFIERS: [&str; 6] = ["shift", "sym", "abc", "more", "ctrl", "alt"]; const REPEAT_DELAY: Duration = Duration::from_millis(450); const REPEAT_EVERY: Duration = Duration::from_millis(80); @@ -468,6 +541,14 @@ pub struct Keyboard { /// 0 off, 1 next letter, 2 caps lock. pub shift: u8, pub ctrl: bool, + pub ctrl_lock: bool, + pub alt: bool, + // One pending key. A rollover commits its predecessor in press order. + owner: Option, + retired: BTreeSet, + alternate: Option<&'static str>, + track_x: i32, + dragged: bool, pub active: Option, pub repeat_at: Option, pub repeated: bool, @@ -485,6 +566,13 @@ impl Keyboard { layout: Layout::Letters, shift: 0, ctrl: false, + ctrl_lock: false, + alt: false, + owner: None, + retired: BTreeSet::new(), + alternate: None, + track_x: 0, + dragged: false, active: None, repeat_at: None, repeated: false, @@ -494,8 +582,18 @@ impl Keyboard { k } + fn row_heights(&self) -> (i32, i32) { + if self.bottom <= 800 { + // Leave 360 px for terminal text below the status bar and toolbar. + (40, 28) + } else { + (Self::ROW_H, Self::ROW_H / 2) + } + } + pub fn height(&self) -> i32 { - Self::ROW_H * if self.terminal_row { 5 } else { 4 } + let (typing, shortcut) = self.row_heights(); + 4 * typing + if self.terminal_row { 2 * shortcut } else { 0 } } pub fn top(&self) -> i32 { @@ -503,13 +601,17 @@ impl Keyboard { } fn build(&mut self) { - let mut rows = layout(self.layout); - if self.terminal_row { - rows.insert(0, terminal_row()); - } + let (row_height, shortcut_height) = self.row_heights(); + let extras = self + .terminal_row + .then(terminal_rows) + .into_iter() + .flatten() + .map(|row| (row, shortcut_height)); + let rows = extras.chain(layout(self.layout).into_iter().map(|row| (row, row_height))); self.keys.clear(); let mut y = self.top(); - for row in rows { + for (row, height) in rows { let units: f64 = row.iter().fold(0.0, |s, k| s + k.2); let unit = self.width as f64 / units; let mut x = 0.0f64; @@ -519,23 +621,46 @@ impl Keyboard { // Drawn with a small gap; the gap still belongs to the key. let (x0, x1) = (x as i32, (x + w) as i32); self.keys.push(KeyRect { - rect: rect(x0 + 3, y + 4, x1 - x0 - 6, Self::ROW_H - 8), + rect: rect(x0 + 3, y + 4, x1 - x0 - 6, height - 8), label, out, - hit: rect(x0, y, x1 - x0, Self::ROW_H), + hit: rect(x0, y, x1 - x0, height), }); } x += w; } - y += Self::ROW_H; + y += height; } } pub fn set_terminal_row(&mut self, on: bool) { + self.cancel(); + if !on { + self.ctrl = false; + self.ctrl_lock = false; + self.alt = false; + } self.terminal_row = on; self.build(); } + pub fn resize(&mut self, width: i32, bottom: i32) { + self.cancel(); + self.width = width.max(0); + self.bottom = bottom.max(0); + self.build(); + } + + pub fn cancel(&mut self) { + self.owner = None; + self.retired.clear(); + self.active = None; + self.repeat_at = None; + self.repeated = false; + self.alternate = None; + self.dragged = false; + } + pub fn key_at(&self, x: i32, y: i32) -> Option { self.keys.iter().find(|k| k.hit.contains(x, y)).copied() } @@ -547,7 +672,8 @@ impl Keyboard { .active .is_some_and(|a| a.out == k.out && a.rect == k.rect) || (k.out == "shift" && self.shift != 0) - || (k.out == "ctrl" && self.ctrl); + || (k.out == "ctrl" && self.ctrl) + || (k.out == "alt" && self.alt); let one = single_char(k.out); let modifier = MODIFIERS.contains(&k.out) || k.out == "backspace" || k.out == "enter"; let bg = if lit { @@ -565,63 +691,151 @@ impl Keyboard { } if k.out == "shift" && self.shift == 2 { text = "CAPS".into(); + } else if k.out == "ctrl" && self.ctrl_lock { + text = "LOCK".into(); } else if one.is_some_and(char::is_alphabetic) && self.shift != 0 { text = k.label.to_uppercase(); } c.fill(k.rect.x, k.rect.y, k.rect.w, k.rect.h, bg); center_text(c, k.rect, &text, font, FG, bg, 1); } + // Non-terminal keyboards are also used for passwords. + if let Some(k) = self + .active + .filter(|k| self.terminal_row && k.out != " " && single_char(k.out).is_some()) + { + let label = self.alternate.unwrap_or(k.out); + let text = if self.shift != 0 { + label.to_ascii_uppercase() + } else { + label.to_string() + }; + let w = k.rect.w.max(font.w as i32 + 10).min(c.w); + let h = (font.h as i32 + 14).min(c.h); + let x = (k.rect.x + (k.rect.w - w) / 2).clamp(0, c.w - w); + let y = (k.rect.y - h).clamp(0, c.h - h); + c.fill(x, y, w, h, ACCENT); + center_text(c, rect(x, y, w, h), &text, font, BG, ACCENT, 1); + } } - fn arm(&mut self, k: Option, now: Instant) { + fn arm(&mut self, k: Option, x: i32, now: Instant) { self.active = k; self.repeated = false; - self.repeat_at = k - .filter(|k| REPEAT.contains(&k.out)) - .map(|_| now + REPEAT_DELAY); + self.dragged = false; + self.track_x = x; + self.alternate = None; + self.repeat_at = k.and_then(|key| { + if REPEAT.contains(&key.out) { + now.checked_add(REPEAT_DELAY) + } else if self.layout == Layout::Letters && alternate(key.out).is_some() { + now.checked_add(LONG_PRESS) + } else { + None + } + }); + } + + fn finish(&mut self, now: Instant) -> Option { + let key = self.active?; + if self.repeated || self.dragged { + return None; + } + let out = if self.repeat_at.is_some_and(|at| at <= now) && self.layout == Layout::Letters { + alternate(key.out).unwrap_or(key.out) + } else { + key.out + }; + self.press(out) } - /// (handled, key typed). + /// Legacy single-contact API: at most one trackpad step per motion event. pub fn touch(&mut self, ev: Gesture, now: Instant) -> (bool, Option) { - match ev { + let (handled, keys) = self.contact(0, ev, now, 1); + (handled, keys.into_iter().next()) + } + + pub fn touch_slot(&mut self, slot: i32, ev: Gesture, now: Instant) -> (bool, Vec) { + self.contact(slot, ev, now, i32::MAX) + } + + fn contact( + &mut self, + slot: i32, + ev: Gesture, + now: Instant, + max_steps: i32, + ) -> (bool, Vec) { + let mut keys = Vec::new(); + let (x, y, released) = match ev { Gesture::Down(x, y) => { - if y < self.top() { - return (false, None); + self.retired.remove(&slot); + let mut key = self.key_at(x, y); + if key.is_none() { + return (y >= self.top() && y < self.bottom, keys); } - let k = self.key_at(x, y); - self.arm(k, now); - (true, None) + if let Some(prev) = self.owner.filter(|&prev| prev != slot) { + self.retired.insert(prev); + keys.extend(self.finish(now)); + // The previous thumb may have switched layouts. + key = self.key_at(x, y); + } + self.owner = Some(slot); + self.arm(key, x, now); + return (true, keys); } - Gesture::Move(_, y) if self.active.is_none() => (y >= self.top(), None), - Gesture::Move(x, y) => { - let k = self.key_at(x, y); - if k != self.active { - self.arm(k, now); + Gesture::Move(x, y) => (x, y, false), + Gesture::Up(x, y) => (x, y, true), + }; + if self.retired.contains(&slot) { + if released { + self.retired.remove(&slot); + } + return (true, keys); + } + if self.owner != Some(slot) { + return (y >= self.top() && y < self.bottom, keys); + } + if self.active.is_some_and(|key| key.out == " ") { + // Ignore off-screen deltas and keep the fractional step when reversing. + let x = x.clamp(0, self.width.max(0)); + let steps = ((x - self.track_x) / TRACKPAD_STEP).clamp(-max_steps, max_steps); + if steps != 0 { + self.dragged = true; + let out = if steps < 0 { "left" } else { "right" }; + self.track_x += steps * TRACKPAD_STEP; + for _ in 0..steps.unsigned_abs() { + keys.extend(self.press(out)); } - (true, None) } - Gesture::Up(_, y) => { - let k = self.active.take(); - let repeated = std::mem::replace(&mut self.repeated, false); - self.repeat_at = None; - let typed = match k { - Some(k) if !repeated => self.press(k.out), - _ => None, - }; - (k.is_some() || y >= self.top(), typed) + } else if !released && self.active.is_some() && self.alternate.is_none() { + let key = self.key_at(x, y); + if key != self.active { + self.arm(key, x, now); } } + if released { + keys.extend(self.finish(now)); + self.owner = None; + self.arm(None, x, now); + } + (true, keys) } - /// Key repeat while backspace or an arrow is held. + /// Commit a long-press alternate once, or repeat a held editing key. pub fn tick(&mut self, now: Instant) -> Option { let k = self.active?; - if self.repeat_at.is_some_and(|t| now >= t) { - self.repeat_at = Some(now + REPEAT_EVERY); - self.repeated = true; + if now < self.repeat_at? { + return None; + } + self.repeated = true; + if REPEAT.contains(&k.out) { + self.repeat_at = now.checked_add(REPEAT_EVERY); return self.press(k.out); } - None + self.repeat_at = None; + self.alternate = alternate(k.out); + self.press(self.alternate?) } fn press(&mut self, out: &'static str) -> Option { @@ -635,7 +849,28 @@ impl Keyboard { }; self.build(); } - "ctrl" => self.ctrl = !self.ctrl, + "ctrl" => { + (self.ctrl, self.ctrl_lock) = match (self.ctrl, self.ctrl_lock) { + (false, _) => (true, false), + (true, false) => (true, true), + (true, true) => (false, false), + }; + } + "alt" => self.alt = !self.alt, + "^C" | "^D" | "^L" => { + self.ctrl = self.ctrl_lock; + self.alt = false; + let ch = match out { + "^C" => 'c', + "^D" => 'd', + _ => 'l', + }; + return Some(Key { + name: KeyName::Char(ch), + ctrl: true, + alt: false, + }); + } _ => { let name = match single_char(out) { Some(ch) if ch.is_alphabetic() && self.shift != 0 => { @@ -647,11 +882,11 @@ impl Keyboard { Some(ch) => KeyName::Char(ch), None => KeyName::Named(out), }; - let ctrl = std::mem::replace(&mut self.ctrl, false); + let ctrl = std::mem::replace(&mut self.ctrl, self.ctrl_lock); return Some(Key { name, ctrl, - alt: false, + alt: std::mem::take(&mut self.alt), }); } } @@ -724,6 +959,213 @@ mod tests { assert_eq!(k.layout, Layout::Sym); } + fn point(k: &Keyboard, out: &str) -> (i32, i32) { + let r = k.keys.iter().find(|k| k.out == out).unwrap().hit; + (r.x + r.w / 2, r.y + r.h / 2) + } + + fn tap(k: &mut Keyboard, out: &str, now: Instant) -> Option { + let (x, y) = point(k, out); + k.touch(Gesture::Down(x, y), now); + k.touch(Gesture::Up(x, y), now).1 + } + + fn letter(ch: char) -> Key { + Key::plain(KeyName::Char(ch)) + } + fn named(name: &'static str) -> Key { + Key::plain(KeyName::Named(name)) + } + + #[test] + fn terminal_shortcuts_and_modifiers() { + let now = Instant::now(); + let mut k = Keyboard::new(720, 1600, true); + for name in [ + "esc", "tab", "home", "end", "pgup", "pgdn", "delete", "left", "down", "up", "right", + ] { + assert_eq!(tap(&mut k, name, now), Some(named(name))); + } + for (shortcut, ch) in [("^C", 'c'), ("^D", 'd'), ("^L", 'l')] { + tap(&mut k, "alt", now); + assert_eq!( + tap(&mut k, shortcut, now), + Some(Key { + ctrl: true, + ..letter(ch) + }) + ); + } + tap(&mut k, "ctrl", now); + tap(&mut k, "ctrl", now); + tap(&mut k, "alt", now); + assert!(k.ctrl_lock && k.alt); + assert_eq!( + tap(&mut k, "b", now), + Some(Key { + ctrl: true, + alt: true, + ..letter('b') + }) + ); + assert_eq!( + tap(&mut k, "x", now), + Some(Key { + ctrl: true, + ..letter('x') + }) + ); + tap(&mut k, "ctrl", now); + assert_eq!(tap(&mut k, "c", now), Some(letter('c'))); + } + + #[test] + fn rollover_commits_in_down_order_and_ignores_late_lifts() { + let mut k = Keyboard::new(720, 1600, true); + let now = Instant::now(); + let (x, y) = point(&k, "a"); + let (u, v) = point(&k, "s"); + for first_up in [0, 1] { + assert_eq!(k.touch_slot(0, Gesture::Down(x, y), now), (true, vec![])); + assert_eq!( + k.touch_slot(1, Gesture::Down(u, v), now), + (true, vec![letter('a')]) + ); + assert!(k.touch_slot(0, Gesture::Move(u, v), now).1.is_empty()); + let mut got = Vec::new(); + for slot in [first_up, 1 - first_up] { + got.extend(k.touch_slot(slot, Gesture::Up(u, v), now).1); + } + assert_eq!(got, [letter('s')]); + } + } + + #[test] + fn long_presses_emit_once_with_or_without_a_timer_tick() { + let mut k = Keyboard::new(720, 1600, true); + let now = Instant::now(); + for (key, alt) in [ + ("q", '1'), + ("p", '0'), + ("a", '@'), + ("l", ')'), + ("z", '*'), + ("m", '?'), + (",", '<'), + (".", '>'), + ] { + let (x, y) = point(&k, key); + k.touch(Gesture::Down(x, y), now); + assert_eq!(k.tick(now + LONG_PRESS - Duration::from_millis(1)), None); + assert_eq!(k.tick(now + LONG_PRESS), Some(letter(alt))); + assert_eq!(k.tick(now + REPEAT_DELAY), None); + assert_eq!(k.touch(Gesture::Up(x, y), now + REPEAT_DELAY).1, None); + k.touch(Gesture::Down(x, y), now); + assert_eq!( + k.touch(Gesture::Up(x, y), now + LONG_PRESS).1, + Some(letter(alt)) + ); + } + for key in ["left", "up", "right", "down", "delete", "backspace"] { + let (x, y) = point(&k, key); + k.touch(Gesture::Down(x, y), now); + assert_eq!(k.tick(now + REPEAT_DELAY), Some(named(key))); + assert_eq!(k.tick(now + REPEAT_DELAY + REPEAT_EVERY), Some(named(key))); + assert!(k + .touch(Gesture::Up(x, y), now + REPEAT_DELAY + REPEAT_EVERY) + .1 + .is_none()); + } + } + + #[test] + fn space_drag_keeps_remainder_and_consumes_lift() { + let mut k = Keyboard::new(720, 1600, true); + let now = Instant::now(); + let (x, y) = point(&k, " "); + k.touch_slot(4, Gesture::Down(x, y), now); + assert!(k + .touch_slot(4, Gesture::Move(x + TRACKPAD_STEP - 1, y), now) + .1 + .is_empty()); + assert_eq!( + k.touch_slot(4, Gesture::Move(x + 2 * TRACKPAD_STEP + 4, y), now) + .1, + [named("right"); 2] + ); + assert_eq!( + k.touch_slot(4, Gesture::Move(x, y), now).1, + [named("left"); 2] + ); + assert!(k.touch_slot(4, Gesture::Up(x, y), now).1.is_empty()); + assert_eq!(tap(&mut k, " ", now), Some(letter(' '))); + } + + #[test] + fn resize_rebuilds_hits_and_cancels_the_old_press() { + let mut k = Keyboard::new(720, 1600, true); + let now = Instant::now(); + let (x, y) = point(&k, "q"); + k.touch_slot(1, Gesture::Down(x, y), now); + k.resize(1600, 720); + assert_eq!(k.top(), 720 - k.height()); + assert!(k.key_at(x, y).is_none()); + assert!(k.touch_slot(1, Gesture::Up(x, y), now).1.is_empty()); + let (x, y) = point(&k, "p"); + assert!(x > 720 && y < 720); + assert_eq!(tap(&mut k, "p", now), Some(letter('p'))); + } + + #[test] + fn preview_pixels_follow_character_and_alternate() { + let font = Font::parse(&crate::font::tests::tiny()).unwrap(); + let mut c = Canvas::new(720, 600, None); + let mut k = Keyboard::new(720, 600, true); + let now = Instant::now(); + tap(&mut k, "shift", now); + let (x, y) = point(&k, "a"); + k.touch(Gesture::Down(x, y), now); + let r = k.active.unwrap().rect; + let py = r.y - (font.h as i32 + 14); + let last_glyph_pixel = r.x + (r.w - font.w as i32) / 2 + 7; + k.draw(&mut c, &font); + assert_eq!(c.pixel(r.x, py), ACCENT); + assert_eq!(c.pixel(last_glyph_pixel, py + 7), BG); // A: solid first row + assert_eq!(k.tick(now + LONG_PRESS), Some(letter('@'))); + k.draw(&mut c, &font); + assert_eq!(c.pixel(last_glyph_pixel, py + 7), ACCENT); // @ uses fallback glyph + k.touch(Gesture::Up(x, y), now + LONG_PRESS); + k.draw(&mut c, &font); + assert_ne!(c.pixel(r.x, py), ACCENT); + } + + #[test] + fn text_field_edits_unicode_at_the_visible_cursor() { + let font = Font::parse(&crate::font::tests::tiny()).unwrap(); + let mut f = TextField::new(rect(10, 0, 72, 100), "Password", true, 6); + f.value = "aé中💡yz".into(); + assert_eq!(f.cursor(), 6); + assert!(!f.key(letter('!'))); + // Four visible cells at the end: the second starts after 中. + assert!(f.tap(10 + 16 + 8, 50, &font)); + assert_eq!(f.cursor(), 3); + assert!(f.key(named("delete"))); + assert!(f.key(letter('€'))); + assert_eq!(f.value, "aé中€yz"); + f.key(named("left")); + f.key(named("backspace")); + assert_eq!((f.value.as_str(), f.cursor()), ("aé€yz", 2)); + f.key(named("home")); + f.key(named("backspace")); + f.key(named("right")); + f.key(letter('ñ')); + assert_eq!(f.value, "añé€yz"); + f.key(named("end")); + f.key(named("delete")); + assert_eq!(f.cursor(), 6); + assert!(!f.tap(0, 0, &font)); + } + #[test] fn keyboard_repeats_held_backspace() { let t0 = Instant::now(); diff --git a/rust/crates/i14-ui/tests/app_parity.rs b/rust/crates/i14-ui/tests/app_parity.rs index 3ab93ef..29b424e 100644 --- a/rust/crates/i14-ui/tests/app_parity.rs +++ b/rust/crates/i14-ui/tests/app_parity.rs @@ -1,14 +1,11 @@ //! Whole pages against `i14ui/app.py`: one scenario of taps, keys, back, lock //! and PIN entry runs in Python and in Rust with the same fakes (screen, Wi-Fi, //! a missing Bluetooth device, fixed time and battery), and every rendered frame -//! must be identical. Needs `python3` and I14_FONTS (the Terminus fonts). +//! is compared using the same PSF2 fonts. Set I14_FONTS to test with Terminus. //! The terminal page is left out: on macOS the Rust side has no pty. //! -//! Deliberate difference (docs/RUST-MIGRATION.md): the Bluetooth page. The Rust interface pairs -//! (visibility button, paired list, code dialog); the Python rollback stays scan-only. Frames -//! drawn while the Bluetooth page is open are therefore not compared byte for byte; instead -//! `bluetooth_page_is_the_only_deliberate_difference` checks that they do differ, that Python is -//! still scan-only, and that every other frame still matches. +//! Only the regions redesigned in Rust differ: the Home grid, Bluetooth pairing, +//! the Hidden password toggle and the scrollable storage and fuel-gauge section. use std::cell::RefCell; use std::io; @@ -457,6 +454,10 @@ fn page_name(p: &Page) -> &'static str { Page::Network(_) => "NetworkPage", Page::Hidden(_) => "HiddenPage", Page::Bluetooth(_) => "BluetoothPage", + Page::System(_) => "SystemPage", + Page::Docker(_) => "DockerPage", + Page::Apps(_) => "AppsPage", + Page::Files(_) => "FilesPage", Page::Settings(_) => "SettingsPage", Page::PinSet(_) => "PinSetPage", Page::Lock(_) => "LockPage", @@ -464,10 +465,15 @@ fn page_name(p: &Page) -> &'static str { } } -/// Frames, page names (for "page" ops) and the indices of frames drawn on the Bluetooth page. -fn run_rust(ops: &[Value], fonts: &str, cfg: &str) -> (Vec>, Vec, Vec) { +/// Redesigned scanline ranges per frame, with exclusive ends. +type ChangedRows = Vec<(usize, usize)>; +fn run_rust( + ops: &[Value], + fonts: &std::path::Path, + cfg: &str, +) -> (Vec>, Vec, Vec) { let frames = Rc::new(RefCell::new(Vec::new())); - let f = |n: &str| Font::open(format!("{fonts}/{n}")).unwrap(); + let f = |n: &str| Font::open(fonts.join(n)).unwrap(); let fonts = Fonts { big: f("ter-132b.psf.gz"), mid: f("ter-124b.psf.gz"), @@ -512,14 +518,39 @@ fn run_rust(ops: &[Value], fonts: &str, cfg: &str) -> (Vec>, Vec Box::new(FakeEnv), ); let mut pages = Vec::new(); - let mut bt_frames = Vec::new(); + let mut changed_rows = Vec::new(); for op in ops { match op[0].as_str().unwrap() { "render" => { - if matches!(app.stack.last(), Some(Page::Bluetooth(_))) { - bt_frames.push(frames.borrow().len()); + changed_rows.push(match app.page() { + Page::Home(_) => vec![(880, 1580)], + Page::Bluetooth(_) => vec![(80, 1600)], + Page::Hidden(p) => { + let y = p.buttons[0].rect.y as usize; + vec![(y, y + 100)] + } + Page::Settings(_) => vec![(810, 1040), (1360, 1600)], + _ => Vec::new(), + }); + app.render(); + if matches!(app.page(), Page::Home(_)) { + use i14_ui::widgets::{BG, PANEL}; + assert!(!app.cx.terminal_enabled); + for y in [900, 1135, 1370] { + for x in [30, 260, 490] { + let expected = if (x, y) == (30, 900) { BG } else { PANEL }; + assert_eq!(app.canvas.pixel(x, y), expected, "home tile at {x},{y}"); + } + for x in [245, 475] { + assert_eq!(app.canvas.pixel(x, y), BG); + } + } + for y in [1110, 1345] { + for x in [30, 260, 490] { + assert_eq!(app.canvas.pixel(x, y), BG); + } + } } - app.render() } "tap" => { let label = op[1].as_str().unwrap(); @@ -572,19 +603,44 @@ fn run_rust(ops: &[Value], fonts: &str, cfg: &str) -> (Vec>, Vec } } let out = frames.borrow().clone(); - (out, pages, bt_frames) + (out, pages, changed_rows) } #[test] fn pages_render_like_python() { - let Some(fonts) = std::env::var("I14_FONTS").ok() else { - eprintln!("skipped: set I14_FONTS to the Terminus font directory"); - return; - }; let tmp = std::env::temp_dir().join(format!("i14-app-parity-{}", std::process::id())); let _ = std::fs::remove_dir_all(&tmp); let out = tmp.join("frames"); std::fs::create_dir_all(&out).unwrap(); + // Exercise the complete scenario on hosts without Terminus, using distinct + // deterministic glyphs at each of the device's actual font dimensions. + let fonts = std::env::var_os("I14_FONTS") + .map(PathBuf::from) + .unwrap_or_else(|| { + let dir = tmp.join("fonts"); + std::fs::create_dir(&dir).unwrap(); + for (name, w, h) in [ + ("ter-120n", 10u32, 20u32), + ("ter-124b", 12, 24), + ("ter-132b", 16, 32), + ] { + let size = w.div_ceil(8) * h; + let mut gz = flate2::write::GzEncoder::new( + std::fs::File::create(dir.join(format!("{name}.psf.gz"))).unwrap(), + flate2::Compression::fast(), + ); + for value in [0x864ab572, 0, 32, 0, 256, size, h, w] { + gz.write_all(&value.to_le_bytes()).unwrap(); + } + for glyph in 0..=255u8 { + for row in 0..size { + gz.write_all(&[glyph.rotate_left(row % 8)]).unwrap(); + } + } + gz.finish().unwrap(); + } + dir + }); let ops = scenario(); let lib = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../rootfs/overlay/usr/lib"); let mut child = Command::new("python3") @@ -617,40 +673,23 @@ fn pages_render_like_python() { let mut lines: Vec = stdout.lines().map(str::to_string).collect(); let n: usize = lines.pop().unwrap().parse().unwrap(); - let (frames, pages, bt_frames) = - run_rust(&ops, &fonts, tmp.join("rs-ui.json").to_str().unwrap()); - eprintln!( - "{} frames, pages {:?}, Bluetooth frames {:?}", - n, lines, bt_frames - ); + let (frames, pages, changes) = run_rust(&ops, &fonts, tmp.join("rs-ui.json").to_str().unwrap()); assert_eq!(pages, lines, "page sequence"); assert_eq!(frames.len(), n, "frame count"); - // the deliberate difference: Bluetooth-page frames must differ (pairing UI vs scan-only) - assert_eq!( - bt_frames.len(), - 3, - "the scenario draws the Bluetooth page three times" - ); - for &i in &bt_frames { + for (i, (got, rows)) in frames.iter().zip(changes).enumerate() { let want = std::fs::read(out.join(format!("{i}.raw"))).unwrap(); - assert_ne!( - want, frames[i], - "Bluetooth frame {i} is identical: is the difference gone?" - ); - } - for (i, got) in frames.iter().enumerate() { - if bt_frames.contains(&i) { - continue; + assert_eq!(got.len(), 720 * 1600 * 4); + assert_eq!(got.len(), want.len()); + for (y, (actual, reference)) in got.chunks(720 * 4).zip(want.chunks(720 * 4)).enumerate() { + if !rows.iter().any(|&(start, end)| (start..end).contains(&y)) { + assert!( + actual == reference, + "unexpected difference on frame {i}, row {y}" + ); + } } - let want = std::fs::read(out.join(format!("{i}.raw"))).unwrap(); - if &want != got { - let first = want.iter().zip(got).position(|(a, b)| a != b).unwrap_or(0); - std::fs::write(tmp.join(format!("rust-{i}.raw")), got).unwrap(); - panic!( - "frame {i} differs from byte {first} (row {}); frames in {}", - first / (720 * 4), - tmp.display() - ); + if !rows.is_empty() { + assert!(want != *got, "missing Rust enhancement on frame {i}"); } } let _ = std::fs::remove_dir_all(&tmp); @@ -658,7 +697,7 @@ fn pages_render_like_python() { /// The Python rollback stays scan-only; the Rust page offers pairing. Runs without fonts. #[test] -fn bluetooth_page_is_the_only_deliberate_difference() { +fn python_bluetooth_rollback_remains_scan_only() { let py = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("../../../rootfs/overlay/usr/lib/i14ui/app.py"); let py = std::fs::read_to_string(py).unwrap(); diff --git a/rust/crates/i14-ui/tests/vt_parity.rs b/rust/crates/i14-ui/tests/vt_parity.rs index ff14a2e..c7a84f7 100644 --- a/rust/crates/i14-ui/tests/vt_parity.rs +++ b/rust/crates/i14-ui/tests/vt_parity.rs @@ -163,7 +163,12 @@ fn lines<'a>(ls: impl IntoIterator>) -> Value { const KEYS: &[(&str, bool, bool)] = &[ ("up", false, false), - ("home", false, true), + // Modified navigation uses xterm sequences in Rust; vt unit tests cover it. + ("down", false, false), + ("left", false, false), + ("right", false, false), + ("home", false, false), + ("end", false, false), ("c", true, false), ("[", true, true), (" ", true, false), diff --git a/rust/crates/i14-ui/tests/widgets_parity.rs b/rust/crates/i14-ui/tests/widgets_parity.rs index f3c4988..db338f0 100644 --- a/rust/crates/i14-ui/tests/widgets_parity.rs +++ b/rust/crates/i14-ui/tests/widgets_parity.rs @@ -1,13 +1,11 @@ -//! Widgets against `i14ui/widgets.py`: the on-screen keyboard layout always, +//! Widgets against `i14ui/widgets.py`: layouts outside the terminal extras, //! and drawn pixels when I14_FONTS points at the Terminus fonts. Needs `python3`. use std::path::PathBuf; use std::process::Command; -use std::time::Instant; use i14_ui::canvas::Canvas; use i14_ui::font::Font; -use i14_ui::input::Gesture; use i14_ui::widgets::*; use serde_json::{json, Value}; @@ -74,7 +72,58 @@ print(json.dumps(out)) ); } } - assert_eq!(json!(got), want); + for (i, got) in got.iter().enumerate() { + let want = want[i].as_array().unwrap(); + if (3..6).contains(&i) { + assert_eq!(got, want, "password layout"); + } else { + // The Python rollback has one row of 10 extras. Rust uses two rows + // of 10 in the same space. All typing rows still match exactly. + assert_eq!(&want[10..], &got[20..]); + assert!(want[..10].iter().all(|k| k[2] != "alt")); + let extras: Vec<_> = got[..20].iter().map(|k| k[2].as_str().unwrap()).collect(); + assert_eq!( + extras, + [ + "esc", "tab", "ctrl", "alt", "left", "down", "up", "right", "|", "-", "home", + "end", "pgup", "pgdn", "delete", "^C", "^D", "^L", "/", "~" + ] + ); + } + } +} + +#[test] +fn all_terminal_shortcuts_have_disjoint_hits_in_both_orientations() { + let extras = [ + "esc", "tab", "ctrl", "alt", "left", "down", "up", "right", "|", "-", "home", "end", + "pgup", "pgdn", "delete", "^C", "^D", "^L", "/", "~", + ]; + for (width, bottom, height) in [(720, 1600, 460), (1600, 720, 216)] { + let k = Keyboard::new(width, bottom, true); + assert_eq!(k.height(), height); + // The terminal toolbar takes 60 px, and the grid has 4 px of padding. + assert!(k.top() - i14_ui::app::BAR_H - 60 - 4 >= 360); + for (i, out) in extras.iter().enumerate() { + let key = k.keys[i]; + assert_eq!(key.out, *out); + let r = key.rect; + for x in [r.x, r.x + r.w / 2, r.x + r.w - 1] { + for y in [r.y, r.y + r.h / 2, r.y + r.h - 1] { + assert_eq!(k.key_at(x, y), Some(key)); + } + } + let h = key.hit; + for other in k.keys.iter().filter(|other| **other != key) { + let o = other.hit; + assert!( + h.x + h.w <= o.x || o.x + o.w <= h.x || h.y + h.h <= o.y || o.y + o.h <= h.y, + "{out} overlaps {}", + other.out + ); + } + } + } } #[test] @@ -114,7 +163,7 @@ empty.draw(c, mid, small) f = w.TextField((40, 700, 640, 120), "Wachtwoord", secret=True) f.value = "geheim-wachtwoord-dat-veel-te-lang-is-voor-het-veld" f.draw(c, mid, small) -k = w.Keyboard(720, 1600, lambda key: None, terminal_row=True) +k = w.Keyboard(720, 1600, lambda key: None, terminal_row=False) k.shift = 2 k.ctrl = True k.active = k.keys[14] @@ -158,12 +207,11 @@ sys.stdout.buffer.write(c.buf) let mut f = TextField::new(rect(40, 700, 640, 120), "Wachtwoord", true, 63); f.value = "geheim-wachtwoord-dat-veel-te-lang-is-voor-het-veld".into(); f.draw(&mut c, &mid, &small); - let mut k = Keyboard::new(720, 1600, true); + let mut k = Keyboard::new(720, 1600, false); k.shift = 2; k.ctrl = true; k.active = Some(k.keys[14]); k.draw(&mut c, &mid); - let _ = (Gesture::Down(0, 0), Instant::now()); assert_eq!(py.len(), c.buf.len()); let first = py.iter().zip(&c.buf).position(|(a, b)| a != b); assert_eq!( diff --git a/rust/stage-rootfs.sh b/rust/stage-rootfs.sh index e25a69b..644458a 100644 --- a/rust/stage-rootfs.sh +++ b/rust/stage-rootfs.sh @@ -4,7 +4,7 @@ set -eu cd "$(dirname "$0")" T=aarch64-unknown-linux-musl -BINS="i14-ui i14-splash i14-battery-guard i14-cpufreq i14-netwatch i14-reboot-bootloader" +BINS="i14-ui i14-splash i14-web i14-battery-guard i14-cpufreq i14-netwatch i14-reboot-bootloader" # The phone packages only (i14-tools is a host tool and links the Mac's zlib). mise exec -- cargo build --release --locked --target "$T" -p i14-ui -p i14-power -p i14-cpufreq -p i14-netwatch -p i14-util OUT=../rootfs/rust-bin diff --git a/tests/test_i14_web_service.py b/tests/test_i14_web_service.py new file mode 100644 index 0000000..3af2a0d --- /dev/null +++ b/tests/test_i14_web_service.py @@ -0,0 +1,48 @@ +"""Host checks for the optional OpenRC dashboard service.""" +import pathlib +import subprocess +import tempfile +import unittest + +ROOTFS = pathlib.Path(__file__).resolve().parents[1] / "rootfs" +ETC = ROOTFS / "overlay/etc" +SERVICE = ETC / "init.d/i14-web" +CONFIG = ETC / "conf.d/i14-web" + + +class WebService(unittest.TestCase): + def test_supervised_loopback_and_token_defaults(self): + self.assertEqual(SERVICE.stat().st_mode & 0o777, 0o755) + # OpenRC reads conf.d before the service, then evaluates command_args. + script = """ + . "$1" && . "$2" || exit 1 + eval "set -- $command_args" + printf '%s\n' "$supervisor" "$@" + """ + for config in ("/dev/null", CONFIG): + with self.subTest(config=config): + result = subprocess.run(["sh", "-c", script, "sh", config, SERVICE], + env={}, capture_output=True, text=True, check=True) + self.assertEqual(result.stdout.splitlines(), [ + "supervise-daemon", "--bind", "127.0.0.1:8080", + "--token-file", "/mnt/data/media/0/i14-linux/web.token", + ]) + + def test_start_requires_a_token_file(self): + with tempfile.TemporaryDirectory() as directory: + token = pathlib.Path(directory) / "web token" + for contents, expected in ((None, 1), ("", 1), ("test-token\n", 0)): + with self.subTest(contents=contents): + if contents is not None: + token.write_text(contents) + result = subprocess.run( + ["sh", "-c", 'eerror() { :; }; . "$1" && start_pre', "sh", SERVICE], + env={"I14_WEB_TOKEN_FILE": str(token)}, + ) + self.assertEqual(result.returncode, expected) + + def test_image_does_not_enable_web_at_boot(self): + builder = (ROOTFS / "build-alpine-rootfs.sh").read_text() + self.assertNotRegex(builder, r"for s in [^;]*\bi14-web\b[^;]*; do") + self.assertNotRegex(builder, r"(?m)^\s*(?:ln|rc-update)\s+[^\n]*\bi14-web\b") + self.assertFalse((ETC / "runlevels/default/i14-web").is_symlink()) From e3287f2336722d7f76712741da1ea2c9c5c2a570 Mon Sep 17 00:00:00 2001 From: brainbudt <32467201+brainbudt@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:58:41 +0100 Subject: [PATCH 2/2] feat(rootfs): add 512 MiB zram swap OpenRC service --- rootfs/build-alpine-rootfs.sh | 2 +- rootfs/overlay/etc/conf.d/i14-zram | 4 ++ rootfs/overlay/etc/init.d/i14-zram | 64 ++++++++++++++++++++++++++++++ tests/test_i14_zram_service.py | 36 +++++++++++++++++ 4 files changed, 105 insertions(+), 1 deletion(-) create mode 100644 rootfs/overlay/etc/conf.d/i14-zram create mode 100755 rootfs/overlay/etc/init.d/i14-zram create mode 100644 tests/test_i14_zram_service.py diff --git a/rootfs/build-alpine-rootfs.sh b/rootfs/build-alpine-rootfs.sh index 08736bb..8c099d6 100644 --- a/rootfs/build-alpine-rootfs.sh +++ b/rootfs/build-alpine-rootfs.sh @@ -85,7 +85,7 @@ chown -R 0:0 "$R/root" "$R/etc" "$R/usr/sbin" # Services. sysinit: /dev is already populated by /i14init (no devtmpfs on 3.18). for s in devfs dmesg mdev i14-splash; do ln -sf /etc/init.d/$s "$R/etc/runlevels/sysinit/$s"; done -for s in bootmisc hostname sysctl syslog seedrng i14-firewall; do +for s in bootmisc hostname sysctl syslog seedrng i14-zram i14-firewall; do [ -e "$R/etc/init.d/$s" ] && ln -sf /etc/init.d/$s "$R/etc/runlevels/boot/$s" done for s in networking sshd chronyd crond i14-power i14-cpufreq i14-usbnet i14-wifi i14-netwatch unbound i14-ui local; do diff --git a/rootfs/overlay/etc/conf.d/i14-zram b/rootfs/overlay/etc/conf.d/i14-zram new file mode 100644 index 0000000..ef0dfb6 --- /dev/null +++ b/rootfs/overlay/etc/conf.d/i14-zram @@ -0,0 +1,4 @@ +# Compressed in-RAM swap (/dev/zram0), avoiding eMMC flash wear. +I14_ZRAM_SIZE_MB="512" +I14_ZRAM_PRIORITY="100" +I14_ZRAM_STREAMS="4" diff --git a/rootfs/overlay/etc/init.d/i14-zram b/rootfs/overlay/etc/init.d/i14-zram new file mode 100755 index 0000000..d77e2dd --- /dev/null +++ b/rootfs/overlay/etc/init.d/i14-zram @@ -0,0 +1,64 @@ +#!/sbin/openrc-run +description="I14: compressed in-RAM swap (/dev/zram0)" + +: "${I14_ZRAM_SIZE_MB:=512}" +: "${I14_ZRAM_PRIORITY:=100}" +: "${I14_ZRAM_STREAMS:=4}" + +ZRAM_DEV="/dev/zram0" +ZRAM_SYS="/sys/block/zram0" + +depend() { + after mdev sysctl + before localmount +} + +start() { + ebegin "Starting I14 zram swap (${I14_ZRAM_SIZE_MB} MiB)" + case "$I14_ZRAM_SIZE_MB" in + ''|*[!0-9]*|0) + eend 1 "I14_ZRAM_SIZE_MB must be a positive integer" + return 1 + ;; + esac + if [ ! -b "$ZRAM_DEV" ] || [ ! -w "$ZRAM_SYS/disksize" ]; then + eend 1 "zram device $ZRAM_DEV is not available" + return 1 + fi + if grep -q "^${ZRAM_DEV}[[:space:]]" /proc/swaps 2>/dev/null; then + eend 0 + return 0 + fi + if [ -w "$ZRAM_SYS/reset" ]; then + echo 1 >"$ZRAM_SYS/reset" || { eend 1 "zram reset failed"; return 1; } + fi + if [ -w "$ZRAM_SYS/max_comp_streams" ]; then + echo "$I14_ZRAM_STREAMS" >"$ZRAM_SYS/max_comp_streams" 2>/dev/null || true + fi + bytes=$((I14_ZRAM_SIZE_MB * 1024 * 1024)) + echo "$bytes" >"$ZRAM_SYS/disksize" || { eend 1 "zram disksize failed"; return 1; } + mkswap "$ZRAM_DEV" >/dev/null || { + echo 1 >"$ZRAM_SYS/reset" 2>/dev/null || true + eend 1 "mkswap failed" + return 1 + } + if ! swapon -p "$I14_ZRAM_PRIORITY" "$ZRAM_DEV" 2>/dev/null; then + swapon "$ZRAM_DEV" || { + echo 1 >"$ZRAM_SYS/reset" 2>/dev/null || true + eend 1 "swapon failed" + return 1 + } + fi + eend 0 +} + +stop() { + ebegin "Stopping I14 zram swap" + if grep -q "^${ZRAM_DEV}[[:space:]]" /proc/swaps 2>/dev/null; then + swapoff "$ZRAM_DEV" || { eend 1 "swapoff failed"; return 1; } + fi + if [ -w "$ZRAM_SYS/reset" ]; then + echo 1 >"$ZRAM_SYS/reset" 2>/dev/null || true + fi + eend 0 +} diff --git a/tests/test_i14_zram_service.py b/tests/test_i14_zram_service.py new file mode 100644 index 0000000..2d61e30 --- /dev/null +++ b/tests/test_i14_zram_service.py @@ -0,0 +1,36 @@ +import stat +import subprocess +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +ROOTFS = ROOT / "rootfs" +ETC = ROOTFS / "overlay/etc" +INIT = ETC / "init.d/i14-zram" +CONF = ETC / "conf.d/i14-zram" + + +class I14ZramServiceTests(unittest.TestCase): + def test_init_script_is_executable_and_valid_sh(self): + mode = stat.S_IMODE(INIT.stat().st_mode) + self.assertTrue(mode & stat.S_IXUSR, f"expected executable init script, got {oct(mode)}") + res = subprocess.run(["sh", "-n", str(INIT)], capture_output=True, text=True) + self.assertEqual(res.returncode, 0, res.stderr) + + def test_defaults_to_512_mib_in_ram_zram(self): + conf = CONF.read_text() + script = INIT.read_text() + self.assertIn('I14_ZRAM_SIZE_MB="512"', conf) + self.assertIn('ZRAM_DEV="/dev/zram0"', script) + self.assertIn("mkswap", script) + self.assertIn("swapon", script) + self.assertIn("swapoff", script) + self.assertNotIn("/mnt/data", script) + + def test_registered_in_boot_runlevel_in_rootfs_builder(self): + builder = (ROOTFS / "build-alpine-rootfs.sh").read_text() + self.assertIn("i14-zram", builder) + + +if __name__ == "__main__": + unittest.main()