From a869aa1235dfe14956becc94d2845224c66a0bba Mon Sep 17 00:00:00 2001 From: Paul Swenson <1937248+pdscomp@users.noreply.github.com> Date: Tue, 13 Oct 2026 09:38:28 -0400 Subject: [PATCH 1/3] Stream recovery task stdout live Commands run with piped stdout so task messages update as lines arrive (republished at most every 250ms) instead of dumping all output at completion. stderr drains on a helper thread so a chatty child can't deadlock the pipe. --- recovery/src/task_exec.rs | 115 +++++++++++++++++++++++++++++++------- 1 file changed, 96 insertions(+), 19 deletions(-) diff --git a/recovery/src/task_exec.rs b/recovery/src/task_exec.rs index 27a4290..1a10b18 100644 --- a/recovery/src/task_exec.rs +++ b/recovery/src/task_exec.rs @@ -1,4 +1,4 @@ -use std::{collections::HashMap, process::Command, thread}; +use std::{collections::HashMap, io::{BufRead, BufReader}, process::{Command, Stdio}, thread, time::{Duration, Instant}}; use slint::{ComponentHandle, ModelRc, SharedString, VecModel, Weak}; @@ -48,24 +48,87 @@ pub fn handle_command(command: &[String], ui_weak: &Weak) -> (i32, St (0, String::new()) } - _ => { - let output = Command::new(&command[0]) - .args(&command[1..]) - .output(); - - let output = match output { - Ok(output) => output, - Err(e) => { - return (-1, format!("Failed to execute command: {}", e)); - } - }; + _ => run_streaming(command, &mut |_| {}), + } +} + +// Spawn the command with piped stdout, invoking `sink` with each line as it +// arrives (so callers can render progress live) while still accumulating and +// returning the full output like Command::output() did. stderr is drained on +// a helper thread to keep a chatty child from deadlocking on a full pipe. +fn run_streaming(command: &[String], sink: &mut dyn FnMut(&str)) -> (i32, String) { + let child = Command::new(&command[0]) + .args(&command[1..]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn(); + + let mut child = match child { + Ok(child) => child, + Err(e) => { + return (-1, format!("Failed to execute command: {}", e)); + } + }; + + if let Some(stderr) = child.stderr.take() { + thread::spawn(move || { + let _ = std::io::copy(&mut BufReader::new(stderr), &mut std::io::sink()); + }); + } - return ( - output.status.code().unwrap_or(-1), - String::from_utf8_lossy(&output.stdout).to_string(), - ); + let mut output = String::new(); + if let Some(stdout) = child.stdout.take() { + let mut reader = BufReader::new(stdout); + let mut line = String::new(); + loop { + line.clear(); + match reader.read_line(&mut line) { + Ok(0) | Err(_) => break, + Ok(_) => { + output.push_str(&line); + sink(&line); + } + } } } + + match child.wait() { + Ok(status) => (status.code().unwrap_or(-1), output), + Err(e) => (-1, format!("Failed to wait on command: {}\n{}", e, output)), + } +} + +#[cfg(test)] +mod tests { + use super::run_streaming; + + #[test] + fn streams_lines_and_accumulates() { + let cmd: Vec = ["/bin/sh", "-c", "echo one; echo two; echo three"] + .iter().map(|s| s.to_string()).collect(); + let mut lines = 0; + let (code, out) = run_streaming(&cmd, &mut |_| lines += 1); + assert_eq!(code, 0); + assert_eq!(out, "one\ntwo\nthree\n"); + assert_eq!(lines, 3); + } + + #[test] + fn noisy_stderr_does_not_deadlock() { + let cmd: Vec = ["/bin/sh", "-c", "seq 1 2000 >&2; echo done"] + .iter().map(|s| s.to_string()).collect(); + let (code, out) = run_streaming(&cmd, &mut |_| {}); + assert_eq!(code, 0); + assert_eq!(out, "done\n"); + } + + #[test] + fn reports_spawn_failure() { + let cmd: Vec = ["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/nonexistent/binary"].iter().map(|s| s.to_string()).collect(); + let (code, out) = run_streaming(&cmd, &mut |_| {}); + assert_eq!(code, -1); + assert!(out.contains("Failed to execute command")); + } } pub fn register_action_button_click(ui: &AppWindow, scripts: &HashMap) { @@ -155,10 +218,24 @@ pub fn process_script_tasks(ui_weak: Weak, script: Script) { } publish_script_tasks(ui_weak.clone(), &tasks, hide_pending); - - let (exit_code, output) = handle_command(&read_only_task.command, &ui_weak); - if read_only_task.show_stdout { + // Stream stdout into the task's message as it arrives so long tasks + // show live progress; republish throttled, full text assigned at end. + let show_stdout = read_only_task.show_stdout; + let mut last_publish = None::; + let (exit_code, output) = if show_stdout { + run_streaming(&read_only_task.command, &mut |line| { + tasks.get_mut(i).unwrap().message.push_str(line); + if last_publish.map_or(true, |t| t.elapsed() >= Duration::from_millis(250)) { + publish_script_tasks(ui_weak.clone(), &tasks, hide_pending); + last_publish = Some(Instant::now()); + } + }) + } else { + handle_command(&read_only_task.command, &ui_weak) + }; + + if show_stdout { let task = tasks.get_mut(i).unwrap(); task.message = output; } From 01cc0621db2adb5ba7cd4deed99094919cc03f1f Mon Sep 17 00:00:00 2001 From: Paul Swenson <1937248+pdscomp@users.noreply.github.com> Date: Sat, 17 Oct 2026 18:59:27 -0400 Subject: [PATCH 2/3] Add disabled recovery options --- recovery/src/config/script.rs | 36 +++++++ recovery/src/main.rs | 24 +++-- recovery/src/menu_tests.rs | 171 ++++++++++++++++++++++++++++++++++ recovery/src/task_exec.rs | 4 + recovery/ui/main.slint | 42 +++++++-- 5 files changed, 258 insertions(+), 19 deletions(-) create mode 100644 recovery/src/menu_tests.rs diff --git a/recovery/src/config/script.rs b/recovery/src/config/script.rs index 831900a..9ade022 100644 --- a/recovery/src/config/script.rs +++ b/recovery/src/config/script.rs @@ -20,6 +20,10 @@ pub struct ScriptInner { pub tasks: Vec, pub hide_pending_tasks: Option, pub index: Option, + #[serde(default)] + pub disabled: bool, + #[serde(default)] + pub disabled_reason: String, } #[derive(Clone)] @@ -28,6 +32,8 @@ pub struct Script { pub completed_actions: Vec, pub tasks: Vec, pub hide_pending_tasks: bool, + pub disabled: bool, + pub disabled_reason: String, } impl Script { @@ -40,6 +46,36 @@ impl Script { } ]), tasks: inner.tasks, hide_pending_tasks: inner.hide_pending_tasks.unwrap_or(false), + disabled: inner.disabled, + disabled_reason: inner.disabled_reason, } } +} + +#[cfg(test)] +mod tests { + use super::{Script, ScriptInner}; + + #[test] + fn disabled_fields_default_to_enabled_and_preserve_reason() { + let legacy: ScriptInner = toml::from_str("tasks = []").unwrap(); + let legacy = Script::from_inner(legacy, "Legacy".into()); + assert!(!legacy.disabled); + assert!(legacy.disabled_reason.is_empty()); + assert_eq!(legacy.completed_actions[0].command, ["__back"]); + + let disabled: ScriptInner = toml::from_str( + "tasks = []\ndisabled = true\ndisabled_reason = 'Running OC-patched, root shell already present'", + ).unwrap(); + let disabled = Script::from_inner(disabled, "Disabled".into()); + assert!(disabled.disabled); + assert_eq!(disabled.disabled_reason, "Running OC-patched, root shell already present"); + + let enabled: ScriptInner = toml::from_str( + "tasks = []\ndisabled = false\ndisabled_reason = \"Arbitrary note: Å\\nsecond line\"", + ).unwrap(); + let enabled = Script::from_inner(enabled, "Enabled".into()); + assert!(!enabled.disabled); + assert_eq!(enabled.disabled_reason, "Arbitrary note: Å\nsecond line"); + } } \ No newline at end of file diff --git a/recovery/src/main.rs b/recovery/src/main.rs index bd98edb..cb1f88c 100644 --- a/recovery/src/main.rs +++ b/recovery/src/main.rs @@ -5,6 +5,8 @@ use crate::config::{DisplayConfig, DisplayInit, Script, ScriptInner}; mod config; mod task_exec; +#[cfg(test)] +mod menu_tests; slint::include_modules!(); @@ -48,6 +50,16 @@ fn to_shared_string_model(values: impl IntoIterator) -> ModelRc ModelRc { + ModelRc::new(VecModel::from( + scripts.iter().map(|script| MenuAction { + name: script.name.clone().into(), + disabled: script.disabled, + disabled_reason: script.disabled_reason.clone().into(), + }).collect::>(), + )) +} + fn register_action_submenu_enter( ui: &AppWindow, submenu_scripts: &HashMap>, @@ -66,9 +78,7 @@ fn register_action_submenu_enter( ui_weak .upgrade_in_event_loop(move |ui| { - ui.global::().set_actions(to_shared_string_model( - submenu_actions.into_iter().map(|action| action.name), - )); + ui.global::().set_actions(to_action_model(&submenu_actions)); ui.global::().set_submenus(to_shared_string_model(Vec::new())); ui.global::().set_show_back(true); ui.global::().set_window_title(SharedString::from(submenu_name)); @@ -96,9 +106,7 @@ fn register_action_exit_submenu( ui_weak .upgrade_in_event_loop(move |ui| { - ui.global::().set_actions(to_shared_string_model( - root_actions.into_iter().map(|action| action.name), - )); + ui.global::().set_actions(to_action_model(&root_actions)); ui.global::().set_submenus(to_shared_string_model(root_submenus)); ui.global::().set_show_back(false); ui.global::().set_window_title(SharedString::from(root_window_title)); @@ -146,9 +154,7 @@ fn main() { let ui = init_display(&config.display); - ui.global::().set_actions(to_shared_string_model( - root_actions.iter().map(|action| action.name.clone()), - )); + ui.global::().set_actions(to_action_model(&root_actions)); ui.global::().set_submenus(to_shared_string_model(root_submenus.clone())); ui.global::().set_show_back(false); ui.global::().set_window_title(SharedString::from(root_window_title.clone())); diff --git a/recovery/src/menu_tests.rs b/recovery/src/menu_tests.rs new file mode 100644 index 0000000..9bd2dc6 --- /dev/null +++ b/recovery/src/menu_tests.rs @@ -0,0 +1,171 @@ +use std::{ + cell::RefCell, + collections::HashMap, + rc::Rc, + sync::mpsc::{self, Sender}, +}; + +use slint::{ + ComponentHandle, LogicalPosition, Model, PhysicalSize, Rgb8Pixel, + platform::{ + EventLoopProxy, Platform, PointerEventButton, WindowAdapter, WindowEvent, + software_renderer::{MinimalSoftwareWindow, RepaintBufferType}, + }, +}; + +use crate::{AppWindow, State, config, task_exec, to_action_model, to_list}; + +type Event = Box; + +struct Offscreen { + window: Rc, + events: Sender, +} + +struct Proxy(Sender); + +impl Platform for Offscreen { + fn create_window_adapter(&self) -> Result, slint::PlatformError> { + Ok(self.window.clone()) + } + + fn new_event_loop_proxy(&self) -> Option> { + Some(Box::new(Proxy(self.events.clone()))) + } +} + +impl EventLoopProxy for Proxy { + fn quit_event_loop(&self) -> Result<(), slint::EventLoopError> { + Ok(()) + } + + fn invoke_from_event_loop(&self, event: Event) -> Result<(), slint::EventLoopError> { + self.0.send(event).unwrap(); + Ok(()) + } +} + +fn render(window: &MinimalSoftwareWindow, name: &str) { + let mut pixels = vec![Rgb8Pixel::default(); 480 * 272]; + window.window().request_redraw(); + assert!(window.draw_if_needed(|renderer| { renderer.render(&mut pixels, 480); })); + assert!(pixels.iter().any(|pixel| *pixel != Rgb8Pixel::default())); + if let Ok(dir) = std::env::var("ATOMSCREEN_MENU_SCREENSHOT_DIR") { + let mut ppm = b"P6\n480 272\n255\n".to_vec(); + for pixel in pixels { + ppm.extend_from_slice(&[pixel.r, pixel.g, pixel.b]); + } + std::fs::write(std::path::Path::new(&dir).join(format!("{name}.ppm")), ppm).unwrap(); + } +} + +// Sweep only the Run column: an enabled control must fire, disabled entries must not. +fn click_run_column(ui: &AppWindow) { + for y in (24..248).step_by(8) { + let position = LogicalPosition::new(420.0, y as f32); + ui.window().dispatch_event(WindowEvent::PointerPressed { + position, + button: PointerEventButton::Left, + }); + ui.window().dispatch_event(WindowEvent::PointerReleased { + position, + button: PointerEventButton::Left, + }); + } +} + +#[test] +fn root_and_submenu_keep_disabled_notes_and_block_clicks_and_execution() { + let config: config::Config = toml::from_str(r#" + [display.default] + width = 480 + height = 272 + + [scripts."Install Root Shell"] + index = 0 + disabled = true + disabled_reason = "Running OC-patched, root shell already present" + tasks = [{ name = "Must not run", command = [] }] + + [scripts."Root enabled control"] + index = 1 + tasks = [] + + [submenus.Utilities."Uninstall Root Shell"] + index = 0 + disabled = true + disabled_reason = "Running OC-patched, root shell already present" + tasks = [{ name = "Must not run", command = [] }] + + [submenus.Utilities."Submenu enabled control"] + index = 1 + tasks = [] + "#).unwrap(); + let root = to_list(config.scripts); + let submenus: HashMap<_, _> = config.submenus.unwrap().into_iter() + .map(|(name, scripts)| (name, to_list(scripts))).collect(); + let reason = "Running OC-patched, root shell already present"; + let window = MinimalSoftwareWindow::new(RepaintBufferType::NewBuffer); + let (sender, events) = mpsc::channel(); + slint::platform::set_platform(Box::new(Offscreen { + window: window.clone(), events: sender, + })).unwrap(); + let ui = AppWindow::new().unwrap(); + window.set_size(PhysicalSize::new(480, 272)); + let state = ui.global::(); + state.set_actions(to_action_model(&root)); + state.set_window_title("CC1 utilities".into()); + // The group menu uses the same ActionEntry but is not itself a runnable script. + state.set_submenus(crate::to_shared_string_model(["Utilities".into()])); + crate::register_action_submenu_enter(&ui, &submenus); + crate::register_action_exit_submenu(&ui, &root, &["Utilities".into()], "CC1 utilities"); + ui.show().unwrap(); + + let clicks = Rc::new(RefCell::new(Vec::new())); + let clicked = clicks.clone(); + state.on_action_start(move |name| clicked.borrow_mut().push(name.to_string())); + for (name, control, expected_back) in [ + ("root-disabled", "Root enabled control", false), + ("submenu-disabled", "Submenu enabled control", true), + ("root-restored", "Root enabled control", false), + ] { + let model = state.get_actions(); + let disabled = model.row_data(0).unwrap(); + assert!(disabled.disabled); + assert_eq!(disabled.disabled_reason.as_str(), reason); + assert!(!model.row_data(1).unwrap().disabled); + assert!(model.row_data(1).unwrap().disabled_reason.is_empty()); + assert_eq!(state.get_show_back(), expected_back); + render(&window, name); + // Hide group buttons while sweeping so navigation cannot change the view. + let groups = state.get_submenus(); + state.set_submenus(crate::to_shared_string_model(Vec::new())); + render(&window, "click-targets"); + clicks.borrow_mut().clear(); + click_run_column(&ui); + assert!(!clicks.borrow().is_empty(), "enabled control was not clickable"); + assert!(clicks.borrow().iter().all(|clicked| clicked == control)); + state.set_submenus(groups); + if expected_back { + state.invoke_action_exit_submenu(); + } else if name == "root-disabled" { + state.invoke_action_submenu_enter("Utilities".into()); + } + for event in events.try_iter() { event(); } + } + assert_eq!(state.get_window_title().as_str(), "CC1 utilities"); + assert_eq!(state.get_submenus().row_data(0).unwrap().as_str(), "Utilities"); + + let marker = std::env::temp_dir().join(format!("atomscreen-disabled-command-{}", std::process::id())); + assert!(!marker.exists()); + for mut script in [root[0].clone(), submenus["Utilities"][0].clone()] { + script.tasks[0].command = vec!["/usr/bin/touch".into(), marker.to_str().unwrap().into()]; + task_exec::process_script_tasks(ui.as_weak(), script); + assert!(!marker.exists(), "disabled script ran its command"); + assert_eq!(events.try_iter().count(), 0, "disabled script published UI state"); + assert!(state.get_active_action().is_empty()); + assert_eq!(state.get_active_action_state(), 0); + assert_eq!(state.get_active_action_tasks().row_count(), 0); + assert_eq!(state.get_active_action_buttons().row_count(), 0); + } +} diff --git a/recovery/src/task_exec.rs b/recovery/src/task_exec.rs index 1a10b18..9669ec9 100644 --- a/recovery/src/task_exec.rs +++ b/recovery/src/task_exec.rs @@ -203,6 +203,10 @@ pub fn publish_active_action_state(ui_weak: Weak, action_name: &str, } pub fn process_script_tasks(ui_weak: Weak, script: Script) { + if script.disabled { + return; + } + let mut tasks : Vec = script.tasks.into_iter().map(|x| ScriptTask::from_raw(x)).collect(); let hide_pending = script.hide_pending_tasks; publish_script_tasks(ui_weak.clone(), &tasks, hide_pending); diff --git a/recovery/ui/main.slint b/recovery/ui/main.slint index c540a39..739d9ef 100644 --- a/recovery/ui/main.slint +++ b/recovery/ui/main.slint @@ -8,8 +8,14 @@ export struct Task { message: string } +export struct MenuAction { + name: string, + disabled: bool, + disabled-reason: string, +} + export global State { - in-out property <[string]> actions; + in-out property <[MenuAction]> actions; in-out property <[string]> submenus; in-out property active-action; in-out property active-action-state; @@ -93,22 +99,32 @@ export component TaskEntry { export component ActionEntry { in property action; in property is-submenu; + in property disabled; + in property disabled-reason; HorizontalLayout { alignment: LayoutAlignment.stretch; spacing: StyleMetrics.layout-spacing; - Text { - horizontal-stretch: 0; - text: action; - vertical-alignment: center; - } - - Rectangle { + VerticalLayout { horizontal-stretch: 1; + alignment: LayoutAlignment.center; + + Text { + text: action; + opacity: disabled ? 0.5 : 1; + vertical-alignment: center; + } + + if disabled-reason != "": Text { + text: disabled-reason; + font-size: 12px; + wrap: word-wrap; + } } Button { + enabled: !disabled; icon: is-submenu ? @image-url("./assets/menu.svg") : @image-url("./assets/run.svg"); colorize-icon: true; text: is-submenu ? "Menu" : "Run"; @@ -240,7 +256,9 @@ export component ActionList { } for action in State.actions: ActionEntry { - action: action; + action: action.name; + disabled: action.disabled; + disabled-reason: action.disabled-reason; } } } @@ -306,7 +324,11 @@ component TestActionList { init => { State.window-title = "OpenCentauri recovery"; State.show-back = true; - State.actions = ["Install Patched Firmware (Online)", "Install Patched Firmware (Offline)", "Reboot"]; + State.actions = [ + { name: "Install Patched Firmware (Online)", disabled: false, disabled-reason: "" }, + { name: "Install Patched Firmware (Offline)", disabled: false, disabled-reason: "" }, + { name: "Reboot", disabled: false, disabled-reason: "" }, + ]; State.submenus = ["Advanced Options", "Settings"]; } From 88cbcac6b1d13b4fbb7e900f32494bdfbdba96f0 Mon Sep 17 00:00:00 2001 From: Paul Swenson <1937248+pdscomp@users.noreply.github.com> Date: Sun, 18 Oct 2026 18:56:22 -0400 Subject: [PATCH 3/3] Remove disabled recovery options and tests --- recovery/src/config/script.rs | 36 ------- recovery/src/main.rs | 24 ++--- recovery/src/menu_tests.rs | 171 ---------------------------------- recovery/src/task_exec.rs | 37 -------- recovery/ui/main.slint | 42 ++------- 5 files changed, 19 insertions(+), 291 deletions(-) delete mode 100644 recovery/src/menu_tests.rs diff --git a/recovery/src/config/script.rs b/recovery/src/config/script.rs index 9ade022..831900a 100644 --- a/recovery/src/config/script.rs +++ b/recovery/src/config/script.rs @@ -20,10 +20,6 @@ pub struct ScriptInner { pub tasks: Vec, pub hide_pending_tasks: Option, pub index: Option, - #[serde(default)] - pub disabled: bool, - #[serde(default)] - pub disabled_reason: String, } #[derive(Clone)] @@ -32,8 +28,6 @@ pub struct Script { pub completed_actions: Vec, pub tasks: Vec, pub hide_pending_tasks: bool, - pub disabled: bool, - pub disabled_reason: String, } impl Script { @@ -46,36 +40,6 @@ impl Script { } ]), tasks: inner.tasks, hide_pending_tasks: inner.hide_pending_tasks.unwrap_or(false), - disabled: inner.disabled, - disabled_reason: inner.disabled_reason, } } -} - -#[cfg(test)] -mod tests { - use super::{Script, ScriptInner}; - - #[test] - fn disabled_fields_default_to_enabled_and_preserve_reason() { - let legacy: ScriptInner = toml::from_str("tasks = []").unwrap(); - let legacy = Script::from_inner(legacy, "Legacy".into()); - assert!(!legacy.disabled); - assert!(legacy.disabled_reason.is_empty()); - assert_eq!(legacy.completed_actions[0].command, ["__back"]); - - let disabled: ScriptInner = toml::from_str( - "tasks = []\ndisabled = true\ndisabled_reason = 'Running OC-patched, root shell already present'", - ).unwrap(); - let disabled = Script::from_inner(disabled, "Disabled".into()); - assert!(disabled.disabled); - assert_eq!(disabled.disabled_reason, "Running OC-patched, root shell already present"); - - let enabled: ScriptInner = toml::from_str( - "tasks = []\ndisabled = false\ndisabled_reason = \"Arbitrary note: Å\\nsecond line\"", - ).unwrap(); - let enabled = Script::from_inner(enabled, "Enabled".into()); - assert!(!enabled.disabled); - assert_eq!(enabled.disabled_reason, "Arbitrary note: Å\nsecond line"); - } } \ No newline at end of file diff --git a/recovery/src/main.rs b/recovery/src/main.rs index cb1f88c..bd98edb 100644 --- a/recovery/src/main.rs +++ b/recovery/src/main.rs @@ -5,8 +5,6 @@ use crate::config::{DisplayConfig, DisplayInit, Script, ScriptInner}; mod config; mod task_exec; -#[cfg(test)] -mod menu_tests; slint::include_modules!(); @@ -50,16 +48,6 @@ fn to_shared_string_model(values: impl IntoIterator) -> ModelRc ModelRc { - ModelRc::new(VecModel::from( - scripts.iter().map(|script| MenuAction { - name: script.name.clone().into(), - disabled: script.disabled, - disabled_reason: script.disabled_reason.clone().into(), - }).collect::>(), - )) -} - fn register_action_submenu_enter( ui: &AppWindow, submenu_scripts: &HashMap>, @@ -78,7 +66,9 @@ fn register_action_submenu_enter( ui_weak .upgrade_in_event_loop(move |ui| { - ui.global::().set_actions(to_action_model(&submenu_actions)); + ui.global::().set_actions(to_shared_string_model( + submenu_actions.into_iter().map(|action| action.name), + )); ui.global::().set_submenus(to_shared_string_model(Vec::new())); ui.global::().set_show_back(true); ui.global::().set_window_title(SharedString::from(submenu_name)); @@ -106,7 +96,9 @@ fn register_action_exit_submenu( ui_weak .upgrade_in_event_loop(move |ui| { - ui.global::().set_actions(to_action_model(&root_actions)); + ui.global::().set_actions(to_shared_string_model( + root_actions.into_iter().map(|action| action.name), + )); ui.global::().set_submenus(to_shared_string_model(root_submenus)); ui.global::().set_show_back(false); ui.global::().set_window_title(SharedString::from(root_window_title)); @@ -154,7 +146,9 @@ fn main() { let ui = init_display(&config.display); - ui.global::().set_actions(to_action_model(&root_actions)); + ui.global::().set_actions(to_shared_string_model( + root_actions.iter().map(|action| action.name.clone()), + )); ui.global::().set_submenus(to_shared_string_model(root_submenus.clone())); ui.global::().set_show_back(false); ui.global::().set_window_title(SharedString::from(root_window_title.clone())); diff --git a/recovery/src/menu_tests.rs b/recovery/src/menu_tests.rs deleted file mode 100644 index 9bd2dc6..0000000 --- a/recovery/src/menu_tests.rs +++ /dev/null @@ -1,171 +0,0 @@ -use std::{ - cell::RefCell, - collections::HashMap, - rc::Rc, - sync::mpsc::{self, Sender}, -}; - -use slint::{ - ComponentHandle, LogicalPosition, Model, PhysicalSize, Rgb8Pixel, - platform::{ - EventLoopProxy, Platform, PointerEventButton, WindowAdapter, WindowEvent, - software_renderer::{MinimalSoftwareWindow, RepaintBufferType}, - }, -}; - -use crate::{AppWindow, State, config, task_exec, to_action_model, to_list}; - -type Event = Box; - -struct Offscreen { - window: Rc, - events: Sender, -} - -struct Proxy(Sender); - -impl Platform for Offscreen { - fn create_window_adapter(&self) -> Result, slint::PlatformError> { - Ok(self.window.clone()) - } - - fn new_event_loop_proxy(&self) -> Option> { - Some(Box::new(Proxy(self.events.clone()))) - } -} - -impl EventLoopProxy for Proxy { - fn quit_event_loop(&self) -> Result<(), slint::EventLoopError> { - Ok(()) - } - - fn invoke_from_event_loop(&self, event: Event) -> Result<(), slint::EventLoopError> { - self.0.send(event).unwrap(); - Ok(()) - } -} - -fn render(window: &MinimalSoftwareWindow, name: &str) { - let mut pixels = vec![Rgb8Pixel::default(); 480 * 272]; - window.window().request_redraw(); - assert!(window.draw_if_needed(|renderer| { renderer.render(&mut pixels, 480); })); - assert!(pixels.iter().any(|pixel| *pixel != Rgb8Pixel::default())); - if let Ok(dir) = std::env::var("ATOMSCREEN_MENU_SCREENSHOT_DIR") { - let mut ppm = b"P6\n480 272\n255\n".to_vec(); - for pixel in pixels { - ppm.extend_from_slice(&[pixel.r, pixel.g, pixel.b]); - } - std::fs::write(std::path::Path::new(&dir).join(format!("{name}.ppm")), ppm).unwrap(); - } -} - -// Sweep only the Run column: an enabled control must fire, disabled entries must not. -fn click_run_column(ui: &AppWindow) { - for y in (24..248).step_by(8) { - let position = LogicalPosition::new(420.0, y as f32); - ui.window().dispatch_event(WindowEvent::PointerPressed { - position, - button: PointerEventButton::Left, - }); - ui.window().dispatch_event(WindowEvent::PointerReleased { - position, - button: PointerEventButton::Left, - }); - } -} - -#[test] -fn root_and_submenu_keep_disabled_notes_and_block_clicks_and_execution() { - let config: config::Config = toml::from_str(r#" - [display.default] - width = 480 - height = 272 - - [scripts."Install Root Shell"] - index = 0 - disabled = true - disabled_reason = "Running OC-patched, root shell already present" - tasks = [{ name = "Must not run", command = [] }] - - [scripts."Root enabled control"] - index = 1 - tasks = [] - - [submenus.Utilities."Uninstall Root Shell"] - index = 0 - disabled = true - disabled_reason = "Running OC-patched, root shell already present" - tasks = [{ name = "Must not run", command = [] }] - - [submenus.Utilities."Submenu enabled control"] - index = 1 - tasks = [] - "#).unwrap(); - let root = to_list(config.scripts); - let submenus: HashMap<_, _> = config.submenus.unwrap().into_iter() - .map(|(name, scripts)| (name, to_list(scripts))).collect(); - let reason = "Running OC-patched, root shell already present"; - let window = MinimalSoftwareWindow::new(RepaintBufferType::NewBuffer); - let (sender, events) = mpsc::channel(); - slint::platform::set_platform(Box::new(Offscreen { - window: window.clone(), events: sender, - })).unwrap(); - let ui = AppWindow::new().unwrap(); - window.set_size(PhysicalSize::new(480, 272)); - let state = ui.global::(); - state.set_actions(to_action_model(&root)); - state.set_window_title("CC1 utilities".into()); - // The group menu uses the same ActionEntry but is not itself a runnable script. - state.set_submenus(crate::to_shared_string_model(["Utilities".into()])); - crate::register_action_submenu_enter(&ui, &submenus); - crate::register_action_exit_submenu(&ui, &root, &["Utilities".into()], "CC1 utilities"); - ui.show().unwrap(); - - let clicks = Rc::new(RefCell::new(Vec::new())); - let clicked = clicks.clone(); - state.on_action_start(move |name| clicked.borrow_mut().push(name.to_string())); - for (name, control, expected_back) in [ - ("root-disabled", "Root enabled control", false), - ("submenu-disabled", "Submenu enabled control", true), - ("root-restored", "Root enabled control", false), - ] { - let model = state.get_actions(); - let disabled = model.row_data(0).unwrap(); - assert!(disabled.disabled); - assert_eq!(disabled.disabled_reason.as_str(), reason); - assert!(!model.row_data(1).unwrap().disabled); - assert!(model.row_data(1).unwrap().disabled_reason.is_empty()); - assert_eq!(state.get_show_back(), expected_back); - render(&window, name); - // Hide group buttons while sweeping so navigation cannot change the view. - let groups = state.get_submenus(); - state.set_submenus(crate::to_shared_string_model(Vec::new())); - render(&window, "click-targets"); - clicks.borrow_mut().clear(); - click_run_column(&ui); - assert!(!clicks.borrow().is_empty(), "enabled control was not clickable"); - assert!(clicks.borrow().iter().all(|clicked| clicked == control)); - state.set_submenus(groups); - if expected_back { - state.invoke_action_exit_submenu(); - } else if name == "root-disabled" { - state.invoke_action_submenu_enter("Utilities".into()); - } - for event in events.try_iter() { event(); } - } - assert_eq!(state.get_window_title().as_str(), "CC1 utilities"); - assert_eq!(state.get_submenus().row_data(0).unwrap().as_str(), "Utilities"); - - let marker = std::env::temp_dir().join(format!("atomscreen-disabled-command-{}", std::process::id())); - assert!(!marker.exists()); - for mut script in [root[0].clone(), submenus["Utilities"][0].clone()] { - script.tasks[0].command = vec!["/usr/bin/touch".into(), marker.to_str().unwrap().into()]; - task_exec::process_script_tasks(ui.as_weak(), script); - assert!(!marker.exists(), "disabled script ran its command"); - assert_eq!(events.try_iter().count(), 0, "disabled script published UI state"); - assert!(state.get_active_action().is_empty()); - assert_eq!(state.get_active_action_state(), 0); - assert_eq!(state.get_active_action_tasks().row_count(), 0); - assert_eq!(state.get_active_action_buttons().row_count(), 0); - } -} diff --git a/recovery/src/task_exec.rs b/recovery/src/task_exec.rs index 9669ec9..ea3f715 100644 --- a/recovery/src/task_exec.rs +++ b/recovery/src/task_exec.rs @@ -98,39 +98,6 @@ fn run_streaming(command: &[String], sink: &mut dyn FnMut(&str)) -> (i32, String } } -#[cfg(test)] -mod tests { - use super::run_streaming; - - #[test] - fn streams_lines_and_accumulates() { - let cmd: Vec = ["/bin/sh", "-c", "echo one; echo two; echo three"] - .iter().map(|s| s.to_string()).collect(); - let mut lines = 0; - let (code, out) = run_streaming(&cmd, &mut |_| lines += 1); - assert_eq!(code, 0); - assert_eq!(out, "one\ntwo\nthree\n"); - assert_eq!(lines, 3); - } - - #[test] - fn noisy_stderr_does_not_deadlock() { - let cmd: Vec = ["/bin/sh", "-c", "seq 1 2000 >&2; echo done"] - .iter().map(|s| s.to_string()).collect(); - let (code, out) = run_streaming(&cmd, &mut |_| {}); - assert_eq!(code, 0); - assert_eq!(out, "done\n"); - } - - #[test] - fn reports_spawn_failure() { - let cmd: Vec = ["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/nonexistent/binary"].iter().map(|s| s.to_string()).collect(); - let (code, out) = run_streaming(&cmd, &mut |_| {}); - assert_eq!(code, -1); - assert!(out.contains("Failed to execute command")); - } -} - pub fn register_action_button_click(ui: &AppWindow, scripts: &HashMap) { let ui_weak = ui.as_weak(); let scripts = scripts.clone(); @@ -203,10 +170,6 @@ pub fn publish_active_action_state(ui_weak: Weak, action_name: &str, } pub fn process_script_tasks(ui_weak: Weak, script: Script) { - if script.disabled { - return; - } - let mut tasks : Vec = script.tasks.into_iter().map(|x| ScriptTask::from_raw(x)).collect(); let hide_pending = script.hide_pending_tasks; publish_script_tasks(ui_weak.clone(), &tasks, hide_pending); diff --git a/recovery/ui/main.slint b/recovery/ui/main.slint index 739d9ef..c540a39 100644 --- a/recovery/ui/main.slint +++ b/recovery/ui/main.slint @@ -8,14 +8,8 @@ export struct Task { message: string } -export struct MenuAction { - name: string, - disabled: bool, - disabled-reason: string, -} - export global State { - in-out property <[MenuAction]> actions; + in-out property <[string]> actions; in-out property <[string]> submenus; in-out property active-action; in-out property active-action-state; @@ -99,32 +93,22 @@ export component TaskEntry { export component ActionEntry { in property action; in property is-submenu; - in property disabled; - in property disabled-reason; HorizontalLayout { alignment: LayoutAlignment.stretch; spacing: StyleMetrics.layout-spacing; - VerticalLayout { - horizontal-stretch: 1; - alignment: LayoutAlignment.center; - - Text { - text: action; - opacity: disabled ? 0.5 : 1; - vertical-alignment: center; - } + Text { + horizontal-stretch: 0; + text: action; + vertical-alignment: center; + } - if disabled-reason != "": Text { - text: disabled-reason; - font-size: 12px; - wrap: word-wrap; - } + Rectangle { + horizontal-stretch: 1; } Button { - enabled: !disabled; icon: is-submenu ? @image-url("./assets/menu.svg") : @image-url("./assets/run.svg"); colorize-icon: true; text: is-submenu ? "Menu" : "Run"; @@ -256,9 +240,7 @@ export component ActionList { } for action in State.actions: ActionEntry { - action: action.name; - disabled: action.disabled; - disabled-reason: action.disabled-reason; + action: action; } } } @@ -324,11 +306,7 @@ component TestActionList { init => { State.window-title = "OpenCentauri recovery"; State.show-back = true; - State.actions = [ - { name: "Install Patched Firmware (Online)", disabled: false, disabled-reason: "" }, - { name: "Install Patched Firmware (Offline)", disabled: false, disabled-reason: "" }, - { name: "Reboot", disabled: false, disabled-reason: "" }, - ]; + State.actions = ["Install Patched Firmware (Online)", "Install Patched Firmware (Offline)", "Reboot"]; State.submenus = ["Advanced Options", "Settings"]; }