diff --git a/Cargo.lock b/Cargo.lock index d475810..4d68d8e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2921,7 +2921,7 @@ dependencies = [ [[package]] name = "usb-forge" -version = "0.2.0" +version = "0.3.0" dependencies = [ "ed25519-dalek", "eframe", diff --git a/Cargo.toml b/Cargo.toml index 358923c..154f5f5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ resolver = "3" [package] name = "usb-forge" -version = "0.2.0" +version = "0.3.0" edition = "2024" rust-version = "1.92" description = "Build a verified multi-boot USB thumb drive from official ISOs on Windows and Linux" diff --git a/assets/boot-theme/background.png b/assets/boot-theme/background.png new file mode 100644 index 0000000..7f45618 Binary files /dev/null and b/assets/boot-theme/background.png differ diff --git a/assets/boot-theme/make-theme.ps1 b/assets/boot-theme/make-theme.ps1 new file mode 100644 index 0000000..a04e550 --- /dev/null +++ b/assets/boot-theme/make-theme.ps1 @@ -0,0 +1,80 @@ +# Regenerates the USB Forge boot menu theme images in this folder (theme.txt is hand-written). +# Colours match src/theme.rs. Usage: powershell -ExecutionPolicy Bypass -File assets/boot-theme/make-theme.ps1 +Add-Type -AssemblyName System.Drawing +$ErrorActionPreference = 'Stop' +$here = Split-Path -Parent $MyInvocation.MyCommand.Path + +function C([string]$hex, [int]$a = 255) { + $v = [Convert]::ToInt32($hex.TrimStart('#'), 16) + [Drawing.Color]::FromArgb($a, ($v -shr 16) -band 255, ($v -shr 8) -band 255, $v -band 255) +} +$BG = C '0f1117'; $PANEL = C '151821'; $CARD_HOVER = C '222734'; $BORDER = C '2a303e' +$TEXT = C 'e6e8ee'; $MUTED = C '8b93a7'; $ACCENT = C 'ff7a45'; $DEEP = C '0b0d12'; $THUMB = C '4a5368' + +function Save([Drawing.Bitmap]$bmp, [string]$name) { + $bmp.Save((Join-Path $here $name), [Drawing.Imaging.ImageFormat]::Png) + $bmp.Dispose() +} + +function Solid([string]$name, [int]$w, [int]$h, [Drawing.Color]$color) { + $bmp = New-Object Drawing.Bitmap $w, $h, ([Drawing.Imaging.PixelFormat]::Format32bppArgb) + $g = [Drawing.Graphics]::FromImage($bmp) + $g.Clear($color) + $g.Dispose() + Save $bmp $name +} + +# A 9-slice box: 1px-wide border pieces (2x2 corners) around a stretched centre. +function Box([string]$prefix, [Drawing.Color]$edge, [Drawing.Color]$fill, [int]$t = 2) { + foreach ($p in 'nw', 'ne', 'sw', 'se') { Solid "${prefix}_$p.png" $t $t $edge } + foreach ($p in 'n', 's') { Solid "${prefix}_$p.png" 4 $t $edge } + foreach ($p in 'w', 'e') { Solid "${prefix}_$p.png" $t 4 $edge } + Solid "${prefix}_c.png" 4 4 $fill +} + +# ---- background: dark gradient, logo + wordmark in the top quarter ---------------------- +$W = 1024; $H = 768 +$bmp = New-Object Drawing.Bitmap $W, $H, ([Drawing.Imaging.PixelFormat]::Format24bppRgb) +$g = [Drawing.Graphics]::FromImage($bmp) +$g.SmoothingMode = 'AntiAlias' +$g.InterpolationMode = 'HighQualityBicubic' +$g.TextRenderingHint = 'AntiAliasGridFit' +$grad = New-Object Drawing.Drawing2D.LinearGradientBrush ([Drawing.PointF]::new(0, 0)), ([Drawing.PointF]::new(0, $H)), $PANEL, $BG +$g.FillRectangle($grad, 0, 0, $W, $H) + +# Soft warm glow behind the logo. +$glow = New-Object Drawing.Drawing2D.GraphicsPath +$glow.AddEllipse(312, -140, 400, 340) +$pgb = New-Object Drawing.Drawing2D.PathGradientBrush $glow +$pgb.CenterColor = (C 'ff7a45' 38) +$pgb.SurroundColors = [Drawing.Color[]]@((C 'ff7a45' 0)) +$g.FillPath($pgb, $glow) + +$icon = [Drawing.Image]::FromFile((Join-Path (Split-Path -Parent $here) 'icon.png')) +$title = 'USB Forge' +$font = New-Object Drawing.Font 'Segoe UI Semibold', 40, ([Drawing.FontStyle]::Regular), ([Drawing.GraphicsUnit]::Pixel) +$size = $g.MeasureString($title, $font) +$iconSize = 76; $gap = 14 +$x = [int](($W - ($iconSize + $gap + $size.Width)) / 2) +$g.DrawImage($icon, $x, 58, $iconSize, $iconSize) +$g.DrawString($title, $font, (New-Object Drawing.SolidBrush $TEXT), [float]($x + $iconSize + $gap), [float](96 - $size.Height / 2)) +$icon.Dispose() + +$sub = New-Object Drawing.Font 'Segoe UI', 16, ([Drawing.FontStyle]::Regular), ([Drawing.GraphicsUnit]::Pixel) +$fmt = New-Object Drawing.StringFormat +$fmt.Alignment = 'Center' +$g.DrawString('Choose an operating system or tool to start', $sub, (New-Object Drawing.SolidBrush $MUTED), [Drawing.RectangleF]::new(0, 152, $W, 24), $fmt) + +# Thin accent rule under the heading. +$g.FillRectangle((New-Object Drawing.SolidBrush $ACCENT), [int]($W / 2 - 28), 186, 56, 3) +$g.Dispose() +Save $bmp 'background.png' + +# ---- menu, selection, scrollbar, command-line box --------------------------------------- +Box 'menu' $BORDER $PANEL +Solid 'select_c.png' 4 4 $CARD_HOVER +Solid 'select_w.png' 4 4 $ACCENT +Solid 'slider_n.png' 10 2 $THUMB +Solid 'slider_c.png' 10 4 $THUMB +Solid 'slider_s.png' 10 2 $THUMB +Box 'terminal_box' $BORDER $DEEP diff --git a/assets/boot-theme/menu_c.png b/assets/boot-theme/menu_c.png new file mode 100644 index 0000000..187b100 Binary files /dev/null and b/assets/boot-theme/menu_c.png differ diff --git a/assets/boot-theme/menu_e.png b/assets/boot-theme/menu_e.png new file mode 100644 index 0000000..e0699c9 Binary files /dev/null and b/assets/boot-theme/menu_e.png differ diff --git a/assets/boot-theme/menu_n.png b/assets/boot-theme/menu_n.png new file mode 100644 index 0000000..0ddf756 Binary files /dev/null and b/assets/boot-theme/menu_n.png differ diff --git a/assets/boot-theme/menu_ne.png b/assets/boot-theme/menu_ne.png new file mode 100644 index 0000000..18330d0 Binary files /dev/null and b/assets/boot-theme/menu_ne.png differ diff --git a/assets/boot-theme/menu_nw.png b/assets/boot-theme/menu_nw.png new file mode 100644 index 0000000..18330d0 Binary files /dev/null and b/assets/boot-theme/menu_nw.png differ diff --git a/assets/boot-theme/menu_s.png b/assets/boot-theme/menu_s.png new file mode 100644 index 0000000..0ddf756 Binary files /dev/null and b/assets/boot-theme/menu_s.png differ diff --git a/assets/boot-theme/menu_se.png b/assets/boot-theme/menu_se.png new file mode 100644 index 0000000..18330d0 Binary files /dev/null and b/assets/boot-theme/menu_se.png differ diff --git a/assets/boot-theme/menu_sw.png b/assets/boot-theme/menu_sw.png new file mode 100644 index 0000000..18330d0 Binary files /dev/null and b/assets/boot-theme/menu_sw.png differ diff --git a/assets/boot-theme/menu_w.png b/assets/boot-theme/menu_w.png new file mode 100644 index 0000000..e0699c9 Binary files /dev/null and b/assets/boot-theme/menu_w.png differ diff --git a/assets/boot-theme/select_c.png b/assets/boot-theme/select_c.png new file mode 100644 index 0000000..f08a8bf Binary files /dev/null and b/assets/boot-theme/select_c.png differ diff --git a/assets/boot-theme/select_w.png b/assets/boot-theme/select_w.png new file mode 100644 index 0000000..2b94479 Binary files /dev/null and b/assets/boot-theme/select_w.png differ diff --git a/assets/boot-theme/slider_c.png b/assets/boot-theme/slider_c.png new file mode 100644 index 0000000..efa6b82 Binary files /dev/null and b/assets/boot-theme/slider_c.png differ diff --git a/assets/boot-theme/slider_n.png b/assets/boot-theme/slider_n.png new file mode 100644 index 0000000..4067284 Binary files /dev/null and b/assets/boot-theme/slider_n.png differ diff --git a/assets/boot-theme/slider_s.png b/assets/boot-theme/slider_s.png new file mode 100644 index 0000000..4067284 Binary files /dev/null and b/assets/boot-theme/slider_s.png differ diff --git a/assets/boot-theme/terminal_box_c.png b/assets/boot-theme/terminal_box_c.png new file mode 100644 index 0000000..362e29d Binary files /dev/null and b/assets/boot-theme/terminal_box_c.png differ diff --git a/assets/boot-theme/terminal_box_e.png b/assets/boot-theme/terminal_box_e.png new file mode 100644 index 0000000..e0699c9 Binary files /dev/null and b/assets/boot-theme/terminal_box_e.png differ diff --git a/assets/boot-theme/terminal_box_n.png b/assets/boot-theme/terminal_box_n.png new file mode 100644 index 0000000..0ddf756 Binary files /dev/null and b/assets/boot-theme/terminal_box_n.png differ diff --git a/assets/boot-theme/terminal_box_ne.png b/assets/boot-theme/terminal_box_ne.png new file mode 100644 index 0000000..18330d0 Binary files /dev/null and b/assets/boot-theme/terminal_box_ne.png differ diff --git a/assets/boot-theme/terminal_box_nw.png b/assets/boot-theme/terminal_box_nw.png new file mode 100644 index 0000000..18330d0 Binary files /dev/null and b/assets/boot-theme/terminal_box_nw.png differ diff --git a/assets/boot-theme/terminal_box_s.png b/assets/boot-theme/terminal_box_s.png new file mode 100644 index 0000000..0ddf756 Binary files /dev/null and b/assets/boot-theme/terminal_box_s.png differ diff --git a/assets/boot-theme/terminal_box_se.png b/assets/boot-theme/terminal_box_se.png new file mode 100644 index 0000000..18330d0 Binary files /dev/null and b/assets/boot-theme/terminal_box_se.png differ diff --git a/assets/boot-theme/terminal_box_sw.png b/assets/boot-theme/terminal_box_sw.png new file mode 100644 index 0000000..18330d0 Binary files /dev/null and b/assets/boot-theme/terminal_box_sw.png differ diff --git a/assets/boot-theme/terminal_box_w.png b/assets/boot-theme/terminal_box_w.png new file mode 100644 index 0000000..e0699c9 Binary files /dev/null and b/assets/boot-theme/terminal_box_w.png differ diff --git a/assets/boot-theme/theme.txt b/assets/boot-theme/theme.txt new file mode 100644 index 0000000..e069f02 --- /dev/null +++ b/assets/boot-theme/theme.txt @@ -0,0 +1,97 @@ +# USB Forge boot menu theme (GRUB gfxmenu). Colours match src/theme.rs. +# Images are generated by make-theme.ps1. Layout follows the boot loader's stock theme so its +# hotkey and boot-mode hints (the @VTOY_*@ labels) keep working. + +desktop-image: "background.png" +desktop-color: "#0f1117" +title-text: " " +title-color: "#e6e8ee" +message-color: "#e6e8ee" + +terminal-box: "terminal_box_*.png" + ++ boot_menu { + left = 15% + width = 70% + top = 30% + height = 52% + + menu_pixmap_style = "menu_*.png" + + item_color = "#e6e8ee" + item_height = 32 + item_spacing = 2 + item_padding = 6 + + selected_item_color = "#ff7a45" + selected_item_pixmap_style = "select_*.png" + + item_icon_space = 0 + + scrollbar = true + scrollbar_width = 10 + scrollbar_thumb = "slider_*.png" +} + ++ progress_bar { + id = "__timeout__" + text = "@TIMEOUT_NOTIFICATION_LONG@" + + left = 15% + width = 70% + top = 84% + height = 20 + + text_color = "#8b93a7" + fg_color = "#5a2e1c" + bg_color = "#151821" + border_color = "#2a303e" +} + ++ hbox{ + left = 30% + top = 95% + width = 10% + height = 25 + + label {text = "@VTOY_HOTKEY_TIP@" color = "#8b93a7" align = "left"} +} + ++ hbox{ + left = 30% + top = 95%-25 + width = 10% + height = 25 + + label {text = "@VTOY_MEM_DISK@" color = "#f5c451" align = "left"} +} + ++ hbox{ + left = 30% + top = 95%-50 + width = 10% + height = 25 + + label {text = "@VTOY_ISO_RAW@" color = "#f5c451" align = "left"} +} + ++ hbox{ + left = 30%+200 + top = 95%-50 + width = 10% + height = 25 + + label {text = "@VTOY_GRUB2_MODE@" color = "#f5c451" align = "left"} +} + ++ hbox{ + left = 30%+200 + top = 95%-25 + width = 10% + height = 25 + + label {text = "@VTOY_WIMBOOT_MODE@" color = "#f5c451" align = "left"} +} + ++ hbox{ + left = 90% + top = 55 + width = 10% + height = 25 + + label {text = "@VTOY_ISO_UEFI_DRV@" color = "#f5c451" align = "left"} +} diff --git a/src/app.rs b/src/app.rs index 1c7d27c..0b1db32 100644 --- a/src/app.rs +++ b/src/app.rs @@ -272,7 +272,7 @@ impl UsbForgeApp { } } if let Some(disk) = self.selected_disk() - && total > disk.size.saturating_sub(64 * 1024 * 1024) + && total > disk.size.saturating_sub(disks::RESERVED_BYTES) { problems.push(format!( "The selection needs {} but the drive holds {}.", @@ -530,31 +530,23 @@ impl UsbForgeApp { fn tool_row(&mut self, ui: &mut egui::Ui, tool: &catalog::ToolInfo) { let mut on = self.chosen.get(&tool.id).copied().unwrap_or(false); let mut channel = self.channel(tool.id); - let lookup_text = { + let max_file = self.fs.max_file(); + let (lookup_text, saved, too_big) = { let map = self.lookups.lock().ok(); match map.as_ref().and_then(|m| m.get(&(tool.id, channel))) { - Some(Lookup::Ready(r)) => Some(Ok(format!( - "{} · {}", - r.version, - r.size.map(human_size).unwrap_or_else(|| "size ?".into()) - ))), - Some(Lookup::Failed(e)) => Some(Err(e.clone())), - Some(Lookup::Loading) | None => None, + Some(Lookup::Ready(r)) => ( + Some(Ok(format!( + "{} · {}", + r.version, + r.size.map(human_size).unwrap_or_else(|| "size ?".into()) + ))), + cache_state(r), + r.size.zip(max_file).is_some_and(|(s, max)| s > max), + ), + Some(Lookup::Failed(e)) => (Some(Err(e.clone())), CacheState::Missing, false), + Some(Lookup::Loading) | None => (None, CacheState::Missing, false), } }; - let saved = { - let map = self.lookups.lock().ok(); - match map.as_ref().and_then(|m| m.get(&(tool.id, channel))) { - Some(Lookup::Ready(r)) => cache_state(r), - _ => CacheState::Missing, - } - }; - let too_big = matches!(&lookup_text, Some(Ok(_))) - && self.fs.max_file().is_some_and(|max| { - self.lookups.lock().ok().is_some_and(|m| { - matches!(m.get(&(tool.id, channel)), Some(Lookup::Ready(r)) if r.size.is_some_and(|s| s > max)) - }) - }); let (fill, stroke) = if on { (CARD_HOVER, ACCENT) diff --git a/src/boot_theme.rs b/src/boot_theme.rs new file mode 100644 index 0000000..c55221c --- /dev/null +++ b/src/boot_theme.rs @@ -0,0 +1,124 @@ +//! The USB Forge boot menu theme, written to the data partition after the ISOs. +//! +//! The boot loader reads `/ventoy/ventoy.json` from the data partition and supports a GRUB +//! gfxmenu theme through its theme plugin, so branding needs no change to the boot loader +//! itself (and nothing about Secure Boot). Images come from `assets/boot-theme/make-theme.ps1`. + +use std::path::Path; + +/// Folder on the data partition that holds the theme, relative to the drive root. +const THEME_DIR: &str = "ventoy/theme/usb-forge"; + +macro_rules! theme_files { + ($($name:literal),* $(,)?) => { + &[$(($name, include_bytes!(concat!("../assets/boot-theme/", $name)) as &[u8])),*] + }; +} + +const FILES: &[(&str, &[u8])] = theme_files![ + "theme.txt", + "background.png", + "menu_c.png", + "menu_n.png", + "menu_s.png", + "menu_e.png", + "menu_w.png", + "menu_ne.png", + "menu_nw.png", + "menu_se.png", + "menu_sw.png", + "select_c.png", + "select_w.png", + "slider_c.png", + "slider_n.png", + "slider_s.png", + "terminal_box_c.png", + "terminal_box_n.png", + "terminal_box_s.png", + "terminal_box_e.png", + "terminal_box_w.png", + "terminal_box_ne.png", + "terminal_box_nw.png", + "terminal_box_se.png", + "terminal_box_sw.png", +]; + +/// Background colour at the bottom of `background.png`. The boot loader always prints its own +/// name and version line; drawing it in this colour hides it. +const HIDDEN_TEXT_COLOR: &str = "#0f1117"; + +/// Plugin config: use the theme in graphical mode, with the boot loader's version line hidden. +fn plugin_config() -> String { + format!( + r##"{{ + "theme": {{ + "file": "/{THEME_DIR}/theme.txt", + "display_mode": "GUI", + "ventoy_left": "5%", + "ventoy_top": "95%", + "ventoy_color": "{HIDDEN_TEXT_COLOR}" + }} +}} +"## + ) +} + +/// Write the theme and the plugin config onto the drive mounted at `root`. +pub fn install(root: &Path) -> Result<(), String> { + let dir = root.join(THEME_DIR); + std::fs::create_dir_all(&dir).map_err(|e| format!("Cannot create {}: {e}", dir.display()))?; + for (name, bytes) in FILES { + let path = dir.join(name); + std::fs::write(&path, bytes) + .map_err(|e| format!("Cannot write {}: {e}", path.display()))?; + } + let config = root.join("ventoy").join("ventoy.json"); + std::fs::write(&config, plugin_config()) + .map_err(|e| format!("Cannot write {}: {e}", config.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn config_points_at_the_bundled_theme() { + let v: serde_json::Value = serde_json::from_str(&plugin_config()).expect("valid JSON"); + let file = v["theme"]["file"].as_str().unwrap(); + let name = file.strip_prefix(&format!("/{THEME_DIR}/")).unwrap(); + assert!(FILES.iter().any(|(n, _)| *n == name)); + assert_eq!(v["theme"]["ventoy_color"], HIDDEN_TEXT_COLOR); + assert!( + std::str::from_utf8(FILES[0].1) + .unwrap() + .contains(&format!("desktop-color: \"{HIDDEN_TEXT_COLOR}\"")), + "hidden text colour must match the theme background" + ); + } + + #[test] + fn every_image_the_theme_uses_is_bundled() { + let theme = std::str::from_utf8(FILES[0].1).unwrap(); + let bundled = |n: &str| FILES.iter().any(|(f, _)| *f == n); + for pattern in theme.split('"').filter(|s| s.ends_with(".png")) { + if let Some(prefix) = pattern.strip_suffix("*.png") { + assert!(bundled(&format!("{prefix}c.png")), "{pattern}"); + } else { + assert!(bundled(pattern), "{pattern}"); + } + } + for (name, bytes) in FILES.iter().filter(|(n, _)| n.ends_with(".png")) { + assert!(bytes.starts_with(b"\x89PNG"), "{name} is not a PNG"); + } + } + + #[test] + fn installs_into_a_drive_folder() { + let root = std::env::temp_dir().join(format!("usbf-theme-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + install(&root).unwrap(); + assert!(root.join("ventoy/ventoy.json").is_file()); + assert!(root.join(THEME_DIR).join("background.png").is_file()); + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/src/catalog.rs b/src/catalog.rs index 18f871b..4edd328 100644 --- a/src/catalog.rs +++ b/src/catalog.rs @@ -1,5 +1,5 @@ //! The software catalog. Every entry is resolved live from its official source, and every -//! download is inned to a SHA-256 published by that project. +//! download is pinned to a SHA-256 published by that project. use regex::Regex; @@ -403,7 +403,9 @@ fn rescuezilla() -> Result { )) } -fn sums_after_sha256_marker(text: &str, name_re: &str) -> Option<(String, String, String)> { +/// First SHA-256 line in a checksum listing whose file name matches `name_re`. Returns +/// (hash, file name, first capture group). Other hash types are skipped by their length. +fn sha256_line_matching(text: &str, name_re: &str) -> Option<(String, String, String)> { let re = Regex::new(name_re).expect("valid regex"); text.lines().find_map(|line| { let mut parts = line.split_whitespace(); @@ -422,9 +424,8 @@ fn sums_after_sha256_marker(text: &str, name_re: &str) -> Option<(String, String fn clonezilla() -> Result { let sums = get_text("https://clonezilla.org/downloads/stable/data/CHECKSUMS.TXT")?; - let (hash, name, v) = - sums_after_sha256_marker(&sums, r"^clonezilla-live-([\d.\-]+)-amd64\.iso$") - .ok_or("Clonezilla checksum not found.")?; + let (hash, name, v) = sha256_line_matching(&sums, r"^clonezilla-live-([\d.\-]+)-amd64\.iso$") + .ok_or("Clonezilla checksum not found.")?; let url = format!( "https://downloads.sourceforge.net/project/clonezilla/clonezilla_live_stable/{v}/{name}" ); @@ -433,7 +434,7 @@ fn clonezilla() -> Result { fn gparted() -> Result { let sums = get_text("https://gparted.org/gparted-live/stable/CHECKSUMS.TXT")?; - let (hash, name, v) = sums_after_sha256_marker(&sums, r"^gparted-live-([\d.\-]+)-amd64\.iso$") + let (hash, name, v) = sha256_line_matching(&sums, r"^gparted-live-([\d.\-]+)-amd64\.iso$") .ok_or("GParted checksum not found.")?; let url = format!("https://downloads.sourceforge.net/gparted/{name}"); Ok(Resolved::new(v, url, name, hash)) diff --git a/src/disks.rs b/src/disks.rs index bb23255..2132a28 100644 --- a/src/disks.rs +++ b/src/disks.rs @@ -21,6 +21,9 @@ pub struct Disk { pub mounts: Vec, } +/// Space kept free on the drive for the boot partition and filesystem overhead. +pub const RESERVED_BYTES: u64 = 64 * 1024 * 1024; + /// Anything larger than this is more likely an external hard drive than a thumb drive. pub const THUMB_DRIVE_MAX: u64 = 256 * 1024 * 1024 * 1024; diff --git a/src/job.rs b/src/job.rs index 3cc5bad..b154640 100644 --- a/src/job.rs +++ b/src/job.rs @@ -4,9 +4,10 @@ //! drive is touched, and the target disk is re-verified immediately before formatting. use std::path::Path; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::AtomicBool; use std::sync::{Arc, Mutex}; +use crate::boot_theme; use crate::catalog::{self, Channel, Resolved, ToolId}; use crate::disks::{self, Disk}; use crate::net; @@ -14,7 +15,6 @@ use crate::platform; use crate::sys::human_size; use crate::ventoy::{self, FileSystem}; -#[derive(Clone)] pub struct Plan { pub disk: Disk, pub tools: Vec<(ToolId, Channel)>, @@ -152,11 +152,7 @@ impl Ctx { } } fn check_cancel(&self) -> Result<(), String> { - if self.cancel.load(Ordering::Relaxed) { - Err("Cancelled.".into()) - } else { - Ok(()) - } + net::cancelled(&self.cancel) } } @@ -200,7 +196,7 @@ fn run(plan: &Plan, ctx: &Ctx) -> Result { } } let total: u64 = resolved.iter().filter_map(|(_, r)| r.size).sum(); - let usable = plan.disk.size.saturating_sub(64 * 1024 * 1024); + let usable = plan.disk.size.saturating_sub(disks::RESERVED_BYTES); if total > usable { return Err(format!( "The selected software needs {} but the drive only holds about {}.", @@ -257,7 +253,7 @@ fn run(plan: &Plan, ctx: &Ctx) -> Result { ventoy_rel.version, disk.display_id() )); - ctx.detail("Waiting for Windows to mount the new partition..."); + ctx.detail("Waiting for the new partition to mount..."); let root = platform::data_partition(&disk)?; ctx.log(format!("Data partition mounted at {}", root.display())); ctx.finish(step_format); @@ -268,6 +264,11 @@ fn run(plan: &Plan, ctx: &Ctx) -> Result { let name = catalog::info(*id).name; copy_to_usb(ctx, &cache, &root, name, r)?; } + // Cosmetic only: without it the drive still boots, just with the stock menu look. + match boot_theme::install(&root) { + Ok(()) => ctx.log("USB Forge boot menu theme installed"), + Err(e) => ctx.log(format!("WARNING: boot menu theme not installed: {e}")), + } ctx.finish(step_copy); ctx.log(format!("All done. {} is ready to boot.", root.display())); Ok(root.display().to_string()) diff --git a/src/main.rs b/src/main.rs index 8b1f4e2..f821dc3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,6 +12,7 @@ compile_error!("USB Forge supports Windows and Linux."); mod app; +mod boot_theme; mod catalog; mod disks; mod job; diff --git a/src/net.rs b/src/net.rs index 0dfdcf0..0919d7e 100644 --- a/src/net.rs +++ b/src/net.rs @@ -49,7 +49,8 @@ pub fn remote_size(url: &str) -> Option { pub type Progress<'a> = &'a mut dyn FnMut(u64, Option); -fn cancelled(cancel: &AtomicBool) -> Result<(), String> { +/// `Err("Cancelled.")` once the user has asked to stop. +pub fn cancelled(cancel: &AtomicBool) -> Result<(), String> { if cancel.load(Ordering::Relaxed) { Err("Cancelled.".into()) } else { diff --git a/src/platform/linux.rs b/src/platform/linux.rs index 8958888..f42dd71 100644 --- a/src/platform/linux.rs +++ b/src/platform/linux.rs @@ -149,9 +149,15 @@ fn is_removable_mount(m: &str) -> bool { } pub fn all_disks() -> Result, String> { - let v = lsblk(None)?; - let devices = v["blockdevices"].as_array().cloned().unwrap_or_default(); - Ok(devices + Ok(parse_disks(&lsblk(None)?)) +} + +/// Turn `lsblk -J` output into the disk list (whole disks only). +fn parse_disks(v: &Value) -> Vec { + v["blockdevices"] + .as_array() + .map(Vec::as_slice) + .unwrap_or_default() .iter() .filter(|d| text(&d["type"]) == "disk") .map(|d| { @@ -185,10 +191,10 @@ pub fn all_disks() -> Result, String> { mounts, } }) - .collect()) + .collect() } -/// Device paths of the disk's partitions, in order. +/// The disk's partitions, in order: (device path, label, mount points). fn partitions(disk: &str) -> Result)>, String> { let v = lsblk(Some(disk))?; let dev = &v["blockdevices"][0]; @@ -376,28 +382,12 @@ mod tests { {"name":"sdc","path":"/dev/sdc","size":2000000000000,"tran":"usb","type":"disk","model":"Backup","vendor":"WD","mountpoints":[null],"pttype":"gpt", "children":[{"name":"sdc1","path":"/dev/sdc1","type":"part","mountpoints":["[SWAP]"]}]} ]}"#; - let v: Value = serde_json::from_str(json).unwrap(); - let disks: Vec = v["blockdevices"] - .as_array() - .unwrap() - .iter() - .map(|d| { - let mut mounts = Vec::new(); - collect_mounts(d, &mut mounts); - Disk { - id: text(&d["path"]), - name: text(&d["model"]), - bus: text(&d["tran"]).to_uppercase(), - size: number(&d["size"]), - is_boot: mounts.iter().any(|m| m == "/boot/efi"), - is_system: mounts.iter().any(|m| !is_removable_mount(m)), - is_os_disk: mounts.iter().any(|m| m == "/"), - style: String::new(), - mounts, - } - }) - .collect(); + let disks = parse_disks(&serde_json::from_str(json).unwrap()); + assert_eq!(disks.len(), 3); + assert!(disks[0].is_boot && disks[0].is_os_disk); assert!(!disks[0].is_safe_target(), "internal NVMe must be hidden"); + assert_eq!(disks[1].name, "General UDisk"); + assert_eq!(disks[1].style, "MBR"); assert!( disks[1].is_safe_target(), "USB stick mounted under /media is a target"