diff --git a/crates/alkane-gui/src/alkane_detect.rs b/crates/alkane-gui/src/alkane_detect.rs index 268f04c9..89df4083 100644 --- a/crates/alkane-gui/src/alkane_detect.rs +++ b/crates/alkane-gui/src/alkane_detect.rs @@ -175,6 +175,15 @@ pub fn install_supported(row: &MinerRow) -> bool { board_family(row).is_some_and(|board| crate::stock_ops::is_supported_board(&board)) } +/// Control boards that can boot from removable SD media, so the toolkit can +/// build an "Installation Media" card for them. Zynq-7010 is proven +/// (stock U-Boot card-detect side-load, confirmed on the bench S17 2026-11-17); +/// the Amlogic A113D is deliberately excluded -- it is eMMC-only with no SD slot +/// (USB recovery disabled), so it stays network-only. +pub fn media_supported(row: &MinerRow) -> bool { + matches!(board_family(row).as_deref(), Some("zynq-7010")) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/alkane-gui/src/main.rs b/crates/alkane-gui/src/main.rs index 092ffcf1..2bc553b4 100644 --- a/crates/alkane-gui/src/main.rs +++ b/crates/alkane-gui/src/main.rs @@ -16,6 +16,7 @@ mod fixtures; mod i18n; mod log_scan; mod logs; +mod media_ops; mod model; mod naming; mod pool_prefs; diff --git a/crates/alkane-gui/src/media_ops.rs b/crates/alkane-gui/src/media_ops.rs new file mode 100644 index 00000000..7744cfa0 --- /dev/null +++ b/crates/alkane-gui/src/media_ops.rs @@ -0,0 +1,306 @@ +// SPDX-License-Identifier: MIT +//! GUI-side orchestration for the "Installation Media" feature: enumerate +//! writable removable devices safely, and drive card creation + device write on +//! a background thread, streaming progress with the same [`StockMsg`] channel +//! the install/restore flows use. +//! +//! The card *image* is built with `alkane_flash::sd_media` (root-free); only the +//! final device write touches hardware, and the UI confirms the target first. + +use std::path::PathBuf; +use std::process::Command; +use std::sync::mpsc::channel; +use std::sync::Arc; + +use alkane_artifacts::afw::{verify_afw, VerifyOptions}; +use alkane_flash::sd_media; + +use crate::stock_ops::{StockHandle, StockMsg}; + +/// What kind of card to build. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum MediaKind { + /// Genuine vendor stock-recovery card (from a user-supplied vendor package). + StockRecovery, + /// Alkane that runs from the card each boot (nothing written to the board). + AlkaneSimpleBoot, + /// Alkane installer: boots, writes alkane to the board's storage, LED-signals. + AlkaneInstaller, +} + +impl MediaKind { + pub fn label(self) -> &'static str { + match self { + MediaKind::StockRecovery => "Stock recovery (restore the board to genuine stock)", + MediaKind::AlkaneSimpleBoot => { + "Alkane: run from SD card (nothing written to the board)" + } + MediaKind::AlkaneInstaller => { + "Alkane: installer (writes alkane to the board, then signals done)" + } + } + } +} + +/// A removable device that is a plausible SD/USB card target. Deliberately +/// conservative: only whole disks that are removable or hotplug, never a disk +/// that holds a mounted filesystem the host is using. +#[derive(Clone, Debug)] +pub struct RemovableDevice { + /// e.g. `/dev/sdc`. + pub path: String, + /// Human size, e.g. `14.6G`. + pub size: String, + /// Model string, e.g. `STORAGE DEVICE`. + pub model: String, + /// True if any partition of it is currently mounted (a caution flag the UI + /// surfaces; such a device is still selectable but clearly risky). + pub has_mounted_partition: bool, +} + +impl RemovableDevice { + pub fn describe(&self) -> String { + let mut s = format!("{} ({}", self.path, self.size.trim()); + if !self.model.trim().is_empty() { + s.push_str(", "); + s.push_str(self.model.trim()); + } + s.push(')'); + if self.has_mounted_partition { + s.push_str(" [mounted]"); + } + s + } +} + +/// Enumerate removable whole-disk devices via `lsblk -J`. Returns an empty list +/// if `lsblk` is unavailable or parsing fails (the UI then offers a manual +/// device entry). The root/system disk is never included (it is not removable). +pub fn list_removable_devices() -> Vec { + let out = match Command::new("lsblk") + .args([ + "-J", + "-b", + "-o", + "NAME,SIZE,RM,HOTPLUG,TYPE,MODEL,TRAN,MOUNTPOINT", + ]) + .output() + { + Ok(o) if o.status.success() => o.stdout, + _ => return Vec::new(), + }; + let json: serde_json::Value = match serde_json::from_slice(&out) { + Ok(v) => v, + Err(_) => return Vec::new(), + }; + let mut devices = Vec::new(); + let blockdevices = json + .get("blockdevices") + .and_then(|v| v.as_array()) + .cloned() + .unwrap_or_default(); + for dev in blockdevices { + let typ = dev.get("type").and_then(|v| v.as_str()).unwrap_or(""); + if typ != "disk" { + continue; + } + let rm = dev.get("rm").and_then(|v| v.as_bool()).unwrap_or(false); + let hotplug = dev + .get("hotplug") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let tran = dev.get("tran").and_then(|v| v.as_str()).unwrap_or(""); + // Removable, or a hotplug USB disk. Never an internal nvme/sata system + // disk (those are rm=false, hotplug=false). + let removable = rm || (hotplug && (tran == "usb" || tran == "mmc")); + if !removable { + continue; + } + let name = dev.get("name").and_then(|v| v.as_str()).unwrap_or(""); + if name.is_empty() { + continue; + } + let size_bytes = dev.get("size").and_then(|v| v.as_u64()).unwrap_or(0); + let model = dev + .get("model") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let mounted = dev + .get("children") + .and_then(|v| v.as_array()) + .map(|parts| { + parts.iter().any(|p| { + p.get("mountpoint") + .and_then(|m| m.as_str()) + .map(|m| !m.is_empty()) + .unwrap_or(false) + }) + }) + .unwrap_or(false) + || dev + .get("mountpoint") + .and_then(|m| m.as_str()) + .map(|m| !m.is_empty()) + .unwrap_or(false); + devices.push(RemovableDevice { + path: format!("/dev/{name}"), + size: human_size(size_bytes), + model, + has_mounted_partition: mounted, + }); + } + devices +} + +fn human_size(bytes: u64) -> String { + const UNITS: [&str; 5] = ["B", "K", "M", "G", "T"]; + let mut v = bytes as f64; + let mut u = 0; + while v >= 1024.0 && u < UNITS.len() - 1 { + v /= 1024.0; + u += 1; + } + format!("{v:.1}{}", UNITS[u]) +} + +/// A fully-specified media-creation request. +pub struct MediaRequest { + pub kind: MediaKind, + /// The source: an `.afw` file (alkane kinds) or a vendor stock package + /// (directory or `.zip`, stock kind). + pub source: PathBuf, + /// Target device, e.g. `/dev/sdc`. When `None`, only the image is built + /// (to `image_out`) and not written. + pub device: Option, + /// Where the intermediate card image is written. + pub image_out: PathBuf, + /// Allow an unsigned `.afw` (bench). + pub allow_unsigned: bool, +} + +/// Build the requested card image (and write it to the device if one is set) on +/// a background thread, streaming [`StockMsg`] exactly like `start_install`. +pub fn start_make_media(req: MediaRequest) -> StockHandle { + let (tx, rx) = channel(); + let cancel = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let cancel_worker = cancel.clone(); + let err_tx = tx.clone(); + + let spawned = std::thread::Builder::new() + .name("alkane-make-media".into()) + .spawn(move || { + let _ = tx.send(StockMsg::Started); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as u32) + .unwrap_or(0); + + let build = || -> Result<(), String> { + match req.kind { + MediaKind::StockRecovery => { + let _ = tx.send(StockMsg::Progress("preparing vendor package...".into())); + let dir = unpack_if_zip(&req.source).map_err(|e| e.to_string())?; + let _ = tx.send(StockMsg::Progress( + "assembling stock-recovery card...".into(), + )); + sd_media::build_stock_recovery_card(&dir, &req.image_out) + .map_err(|e| e.to_string())?; + } + MediaKind::AlkaneSimpleBoot | MediaKind::AlkaneInstaller => { + let _ = tx.send(StockMsg::Progress("verifying .afw...".into())); + let verified = verify_afw( + &req.source, + &VerifyOptions { + allow_unsigned: req.allow_unsigned, + expect_board: Some("zynq-7010".into()), + }, + ) + .map_err(|e| format!(".afw: {e}"))?; + if req.kind == MediaKind::AlkaneSimpleBoot { + let _ = tx + .send(StockMsg::Progress("assembling simple-boot card...".into())); + sd_media::build_zynq_simpleboot_card(&verified, &req.image_out, now) + .map_err(|e| e.to_string())?; + } else { + let _ = tx.send(StockMsg::Progress( + "assembling installer card (injecting install hook)...".into(), + )); + sd_media::build_zynq_installer_card(&verified, &req.image_out, now) + .map_err(|e| e.to_string())?; + } + } + } + if let Some(dev) = &req.device { + if cancel_worker.load(std::sync::atomic::Ordering::Relaxed) { + return Err("cancelled before device write".into()); + } + let _ = tx.send(StockMsg::Progress(format!( + "writing card to {} (do not remove)...", + dev.display() + ))); + sd_media::write_image_to_device(&req.image_out, dev) + .map_err(|e| e.to_string())?; + } + Ok(()) + }; + + let (ok, detail) = match build() { + Ok(()) => { + let where_ = req + .device + .as_ref() + .map(|d| format!("written to {}", d.display())) + .unwrap_or_else(|| format!("image at {}", req.image_out.display())); + (true, format!("card ready ({where_})")) + } + Err(e) => (false, format!("media build failed: {e}")), + }; + let ip = req + .device + .as_ref() + .map(|d| d.display().to_string()) + .unwrap_or_else(|| "card".into()); + let _ = tx.send(StockMsg::Result { ip, ok, detail }); + let _ = tx.send(StockMsg::Done); + }); + + if spawned.is_err() { + let _ = err_tx.send(StockMsg::Result { + ip: String::new(), + ok: false, + detail: "could not start the media worker thread".into(), + }); + let _ = err_tx.send(StockMsg::Done); + } + StockHandle::new(rx, cancel) +} + +/// If `src` is a `.zip`, unpack it to an ephemeral directory and return that; +/// a directory is returned as-is. +fn unpack_if_zip(src: &std::path::Path) -> std::io::Result { + if src.is_dir() { + return Ok(src.to_path_buf()); + } + if src + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("zip")) + { + let staged = std::env::temp_dir().join(format!("alkane-media-pkg-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&staged); + std::fs::create_dir_all(&staged)?; + let status = Command::new("unzip") + .args(["-o", "-q"]) + .arg(src) + .arg("-d") + .arg(&staged) + .status()?; + if !status.success() { + return Err(std::io::Error::other("unzip failed")); + } + return Ok(staged); + } + Err(std::io::Error::other( + "stock package must be a directory or a .zip", + )) +} diff --git a/crates/alkane-gui/src/stock_ops.rs b/crates/alkane-gui/src/stock_ops.rs index b09b685a..42edf2be 100644 --- a/crates/alkane-gui/src/stock_ops.rs +++ b/crates/alkane-gui/src/stock_ops.rs @@ -83,6 +83,12 @@ pub struct StockHandle { } impl StockHandle { + /// Construct a handle around a worker's receiver and cancel flag. Used by + /// other op modules (e.g. `media_ops`) that reuse this streaming channel. + pub fn new(rx: Receiver, cancel: Arc) -> StockHandle { + StockHandle { rx, cancel } + } + #[allow(dead_code)] pub fn stop(&self) { self.cancel.store(true, Ordering::Relaxed); diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index 2de48f3a..f643bc00 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -3,6 +3,7 @@ use crate::alkane_detect; use crate::credentials; +use crate::media_ops; use crate::model::*; use crate::restore; use crate::scan::{self, ScanMsg}; @@ -105,6 +106,15 @@ const ID_POOLS_CANCEL: i32 = 789; const ID_CTX_INSTALL_ALKANE: i32 = 770; const ID_CTX_UNINSTALL_ALKANE: i32 = 771; const ID_CTX_UPDATE_ALKANE: i32 = 772; +// "Installation Media..." context item (build a bootable SD card). +const ID_CTX_INSTALL_MEDIA: i32 = 773; +// Installation-Media dialog controls (free id block above the install dialog's). +const ID_MEDIA_OK: i32 = 1015; +const ID_MEDIA_CANCEL: i32 = 1016; +const ID_MEDIA_KIND_CHOICE: i32 = 1017; +const ID_MEDIA_DEVICE_CHOICE: i32 = 1019; +const ID_MEDIA_BROWSE: i32 = 1020; +const ID_MEDIA_RELOAD_DEVS: i32 = 1022; const ID_INSTALL_OK: i32 = 1006; const ID_INSTALL_CANCEL: i32 = 1007; const ID_INSTALL_RELEASE_CHOICE: i32 = 1008; @@ -1009,6 +1019,21 @@ pub struct App { // The release repo (owner/repo) the picker scans; defaults to // blueflare/alkane-os, editable + reloadable to any compatible repo. install_repo_input: Widget, + // Installation-Media dialog (sd_media / media_ops): build a bootable SD card + // for a card-bootable board (Zynq first). One background job, reusing + // `stock_op`. The widgets + the state captured when the dialog opens. + media_dialog: Widget, + media_kind_choice: Widget, + media_device_choice: Widget, + media_unsigned_check: Widget, + media_source_label: Widget, + // The browsed source: an .afw (alkane kinds) or a vendor package (stock). + media_source_path: Option, + // Removable devices behind the device choice, by item index (index 0 is the + // "build image only, do not write" option, so devices start at index 1). + media_devices: Vec, + // The board family the card targets (e.g. "zynq-7010"). + media_board: String, uninstall_dialog: Widget, uninstall_firmware_input: Widget, // Restore-to-stock source: the board's on-board stock backup (checkbox, @@ -1419,6 +1444,14 @@ pub fn build(frame: Widget) -> App { install_local_label: frame, install_plan_label: frame, install_repo_input: frame, + media_dialog: frame, + media_kind_choice: frame, + media_device_choice: frame, + media_unsigned_check: frame, + media_source_label: frame, + media_source_path: None, + media_devices: Vec::new(), + media_board: stock_ops::DEFAULT_BOARD.to_string(), uninstall_dialog: frame, uninstall_firmware_input: frame, uninstall_onboard_check: frame, @@ -2031,7 +2064,11 @@ impl App { let install = supported && none_alkane; let update = supported && all_alkane; let uninstall = all_alkane; - if install || update || uninstall { + // "Installation Media" applies to card-bootable boards (Zynq); it builds + // an SD card and does not need the board to be reachable now. + let media = + !selected.is_empty() && selected.iter().all(|r| alkane_detect::media_supported(r)); + if install || update || uninstall || media { menu.menu_append_separator(); } if install { @@ -2046,6 +2083,9 @@ impl App { "Uninstall alkane OS (restore to stock)...", ); } + if media { + menu.menu_append(ID_CTX_INSTALL_MEDIA, "Installation Media (SD card)..."); + } self.pending_popup = Some((t, menu)); } @@ -3026,6 +3066,204 @@ impl App { Some(dlg) } + /// Build the "Installation Media" dialog: choose a card kind, an image + /// source, and a target SD device, then build (and optionally write) a + /// bootable card for a card-bootable board (Zynq first). + fn build_install_media_dialog(&mut self) -> Option { + if self.flash_busy() { + wx_rs::set_status_text("busy -- try again once the current operation finishes"); + return None; + } + let board = self + .selected_rows() + .into_iter() + .find_map(crate::alkane_detect::board_family) + .unwrap_or_else(|| stock_ops::DEFAULT_BOARD.to_string()); + self.media_board = board.clone(); + self.media_source_path = None; + + let frame = Widget::main_frame(); + let dlg = Widget::dialog(frame, "Installation Media"); + let root = Widget::box_sizer(true); + root.add( + Widget::static_text( + dlg, + &format!( + "Build a bootable SD installation card for the {board} control board.\nInsert a card, choose what to build, then Create." + ), + ), + 0, + sf::BORDER_ALL, + 12, + ); + + // What to build. + root.add( + Widget::static_text(dlg, "What to build:"), + 0, + sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, + 12, + ); + let kind = Widget::choice(dlg, ID_MEDIA_KIND_CHOICE); + for k in [ + media_ops::MediaKind::StockRecovery, + media_ops::MediaKind::AlkaneSimpleBoot, + media_ops::MediaKind::AlkaneInstaller, + ] { + kind.choice_append(k.label()); + } + kind.choice_set_selection(2); // default: alkane installer + root.add(kind, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12); + self.media_kind_choice = kind; + + // Image source. + root.add( + Widget::static_text( + dlg, + "Image source -- an .afw for alkane, or a genuine vendor package (.zip or folder) for stock recovery:", + ), + 0, + sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, + 12, + ); + let browse_row = Widget::box_sizer(false); + browse_row.add( + Widget::button(dlg, "Browse...", ID_MEDIA_BROWSE), + 0, + sf::BORDER_RIGHT, + 6, + ); + let src_label = Widget::static_text(dlg, "(none selected)"); + browse_row.add(src_label, 1, sf::ALIGN_CENTRE_VERTICAL, 0); + self.media_source_label = src_label; + root.add_sizer( + browse_row, + 0, + sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, + 12, + ); + + let unsigned = Widget::check_box(dlg, "Allow unsigned .afw (bench only)"); + unsigned.set_checked(true); + root.add(unsigned, 0, sf::BORDER_ALL, 12); + self.media_unsigned_check = unsigned; + + // Target device. + root.add( + Widget::static_text(dlg, "Target SD card (writing ERASES the whole card):"), + 0, + sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, + 12, + ); + let dev_row = Widget::box_sizer(false); + let dev = Widget::choice(dlg, ID_MEDIA_DEVICE_CHOICE); + dev_row.add(dev, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_RIGHT, 6); + dev_row.add(Widget::button(dlg, "Rescan", ID_MEDIA_RELOAD_DEVS), 0, 0, 0); + self.media_device_choice = dev; + root.add_sizer( + dev_row, + 0, + sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, + 12, + ); + self.populate_media_devices(); + + root.add( + Widget::static_text( + dlg, + "The card is built as an image first, then written. Double-check the target card before Create.", + ), + 0, + sf::BORDER_ALL, + 12, + ); + + let btns = Widget::box_sizer(false); + btns.add_stretch(1); + btns.add( + Widget::button(dlg, "Create", ID_MEDIA_OK), + 0, + sf::BORDER_ALL, + 6, + ); + btns.add( + Widget::button(dlg, "Cancel", ID_MEDIA_CANCEL), + 0, + sf::BORDER_ALL, + 6, + ); + root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6); + root.set_sizer_on(dlg); + dlg.set_min_size(580, 480); + dlg.fit(dlg); + self.media_dialog = dlg; + Some(dlg) + } + + /// Fill the media device choice from a fresh removable-device scan. Index 0 + /// is "build an image file only" (no card write); real devices follow. + fn populate_media_devices(&mut self) { + self.media_devices = media_ops::list_removable_devices(); + let c = self.media_device_choice; + c.choice_clear(); + c.choice_append("Build an image file only (do not write a card)"); + for d in &self.media_devices { + c.choice_append(&d.describe()); + } + c.choice_set_selection(if self.media_devices.is_empty() { 0 } else { 1 }); + } + + /// Start building the requested card (and writing it, if a device is chosen) + /// on the shared background worker. Reuses `stock_op` and its drain. + fn apply_make_media_confirm(&mut self) { + if self.flash_busy() { + return; + } + let kind = match self.media_kind_choice.choice_get_selection() { + 0 => media_ops::MediaKind::StockRecovery, + 1 => media_ops::MediaKind::AlkaneSimpleBoot, + _ => media_ops::MediaKind::AlkaneInstaller, + }; + let source = match &self.media_source_path { + Some(p) => std::path::PathBuf::from(p), + None => { + wx_rs::set_status_text("pick an image source (.afw or a stock package) first"); + return; + } + }; + let dev_sel = self.media_device_choice.choice_get_selection(); + let device = if dev_sel <= 0 { + None + } else { + self.media_devices + .get((dev_sel - 1) as usize) + .map(|d| std::path::PathBuf::from(&d.path)) + }; + let allow_unsigned = self.media_unsigned_check.is_checked(); + let image_out = alkane_core::platform::config_path("media") + .join(format!("{}-card.img", self.media_board)); + if let Some(parent) = image_out.parent() { + let _ = std::fs::create_dir_all(parent); + } + + self.media_dialog.close(1); + let target = device + .as_ref() + .map(|d| d.display().to_string()) + .unwrap_or_else(|| "image file".into()); + wx_rs::set_status_text(&format!( + "building {} card -> {target}...", + self.media_board + )); + self.stock_op = Some(media_ops::start_make_media(media_ops::MediaRequest { + kind, + source, + device, + image_out, + allow_unsigned, + })); + } + /// Apply the install confirmation: validate the typed keyword, resolve the /// chosen release asset, and start the network-only from-stock install. fn apply_install_confirm(&mut self) { @@ -3544,6 +3782,7 @@ impl App { ID_CTX_INSTALL_ALKANE => return self.build_install_dialog(false), ID_CTX_UPDATE_ALKANE => return self.build_install_dialog(true), ID_CTX_UNINSTALL_ALKANE => return self.build_uninstall_dialog(), + ID_CTX_INSTALL_MEDIA => return self.build_install_media_dialog(), ID_CTX_POOLS => return self.build_pools_dialog(), ID_CTX_FLASH => { // A flash needs exclusive hardware access; don't even prompt if @@ -6335,6 +6574,24 @@ impl App { self.uninstall_ips.clear(); self.uninstall_dialog.close(0); } + ID_MEDIA_OK => self.apply_make_media_confirm(), + ID_MEDIA_CANCEL => self.media_dialog.close(0), + ID_MEDIA_RELOAD_DEVS => self.populate_media_devices(), + ID_MEDIA_BROWSE => { + if let Some(path) = Widget::file_dialog( + self.media_dialog, + "Choose an .afw (alkane) or a stock vendor package (.zip)", + ) { + let name = std::path::Path::new(&path) + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| path.clone()); + self.media_source_label + .set_label(&format!("Source: {name}")); + self.media_source_path = Some(path); + self.media_dialog.layout(); + } + } ID_POOLS_OK => self.apply_pools(), ID_POOLS_CANCEL => self.pools_dialog.close(0), // Pool-preset manager buttons (round 18 #8b).