From 11f0a83e0638bb672aa5cca5ffde263333afff60 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 2 Jul 2026 21:16:33 +0000 Subject: [PATCH] Add native Windows app (WinUI 3 + C#/.NET) with CI, release packaging, and docs The Windows port of wInstaller lands in apps/windows/, mirroring the macOS app's architecture during the pre-Rust-core transition (ADR-0001 note): - WInstaller.Core (net8.0): typed state machine, marker-based ISO detection, operation planning with the full safety-gate set (removable-only, no boot/system disks, capacity, tool availability), executor pipeline with the identity re-check immediately before erase, redacted local logging, and a Simulate (dry-run) runner. 49 xunit tests run on Windows and Linux. - Bundled PowerShell helpers keep every system call argv-only: Get-Disk enumeration as JSON, Mount-DiskImage read-only ISO inspection, the Clear-Disk -> Initialize GPT -> Format FAT32 prepare step (the only elevated command, per ADR-0003, with safety gates re-checked inside the elevated context), DISM /Split-Image for oversized WIMs, and shell eject. - WInstaller.App: WinUI 3 assistant flow (welcome -> choose/verify ISO -> insert/analyze USB -> confirm erase -> create -> done) with Mica, Fluent styling, and SCREEN parity markers; all copy generated from shared/strings/copy.yaml into AppStrings.resx (ADR-0008). - CI: ci-windows.yml (core tests on windows+ubuntu, app publish smoke build), release-windows.yml (self-contained portable zip attached to releases), strings-sync job in parity.yml, and gen_strings_dotnet.py / make-ico.py. - Docs: README build/download/status/architecture updates, ROADMAP status, screen-inventory.yaml windows -> implemented, landing page Windows download. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_017AWcakD66cJ6RdiLTAB8x8 --- .github/workflows/ci-windows.yml | 50 ++ .github/workflows/parity.yml | 15 + .github/workflows/release-windows.yml | 53 ++ .gitignore | 6 + README.md | 61 ++- apps/windows/README.md | 79 +++ apps/windows/WInstaller.App/App.xaml | 12 + apps/windows/WInstaller.App/App.xaml.cs | 19 + apps/windows/WInstaller.App/AppStrings.cs | 27 + .../WInstaller.App/Assets/wInstaller.ico | Bin 0 -> 27758 bytes apps/windows/WInstaller.App/AssistantModel.cs | 318 ++++++++++++ apps/windows/WInstaller.App/MainWindow.xaml | 56 +++ .../windows/WInstaller.App/MainWindow.xaml.cs | 117 +++++ apps/windows/WInstaller.App/Steps.cs | 474 ++++++++++++++++++ .../WInstaller.App/Strings/AppStrings.resx | 191 +++++++ .../WInstaller.App/WInstaller.App.csproj | 32 ++ apps/windows/WInstaller.App/app.manifest | 28 ++ .../BootableUsbEngineTests.cs | 228 +++++++++ .../DiskEnumeratorTests.cs | 126 +++++ .../FakeCommandRunner.cs | 55 ++ .../InfrastructureTests.cs | 122 +++++ .../OperationExecutorTests.cs | 207 ++++++++ .../WInstaller.Core.Tests/TestFixtures.cs | 51 ++ .../WInstaller.Core.Tests.csproj | 20 + .../WInstaller.Core/BootableUsbEngine.cs | 275 ++++++++++ apps/windows/WInstaller.Core/CommandRunner.cs | 214 ++++++++ .../windows/WInstaller.Core/DiskEnumerator.cs | 167 ++++++ apps/windows/WInstaller.Core/IsoInspector.cs | 187 +++++++ apps/windows/WInstaller.Core/LocalLogger.cs | 126 +++++ apps/windows/WInstaller.Core/Models.cs | 213 ++++++++ .../WInstaller.Core/OperationExecutor.cs | 345 +++++++++++++ .../WInstaller.Core/Scripts/disk-info.ps1 | 47 ++ .../WInstaller.Core/Scripts/dismount-iso.ps1 | 17 + .../WInstaller.Core/Scripts/eject-disk.ps1 | 26 + .../WInstaller.Core/Scripts/list-disks.ps1 | 43 ++ .../WInstaller.Core/Scripts/mount-iso.ps1 | 38 ++ .../WInstaller.Core/Scripts/prepare-usb.ps1 | 68 +++ .../WInstaller.Core/Scripts/split-wim.ps1 | 41 ++ apps/windows/WInstaller.Core/Simulation.cs | 86 ++++ .../WInstaller.Core/WInstaller.Core.csproj | 22 + apps/windows/WInstaller.sln | 61 +++ docs/screen-inventory.yaml | 16 +- docs/site/index.html | 2 +- docs/specs/ROADMAP.md | 26 +- scripts/gen_strings_dotnet.py | 94 ++++ scripts/make-ico.py | 39 ++ 46 files changed, 4474 insertions(+), 26 deletions(-) create mode 100644 .github/workflows/ci-windows.yml create mode 100644 .github/workflows/release-windows.yml create mode 100644 apps/windows/README.md create mode 100644 apps/windows/WInstaller.App/App.xaml create mode 100644 apps/windows/WInstaller.App/App.xaml.cs create mode 100644 apps/windows/WInstaller.App/AppStrings.cs create mode 100644 apps/windows/WInstaller.App/Assets/wInstaller.ico create mode 100644 apps/windows/WInstaller.App/AssistantModel.cs create mode 100644 apps/windows/WInstaller.App/MainWindow.xaml create mode 100644 apps/windows/WInstaller.App/MainWindow.xaml.cs create mode 100644 apps/windows/WInstaller.App/Steps.cs create mode 100644 apps/windows/WInstaller.App/Strings/AppStrings.resx create mode 100644 apps/windows/WInstaller.App/WInstaller.App.csproj create mode 100644 apps/windows/WInstaller.App/app.manifest create mode 100644 apps/windows/WInstaller.Core.Tests/BootableUsbEngineTests.cs create mode 100644 apps/windows/WInstaller.Core.Tests/DiskEnumeratorTests.cs create mode 100644 apps/windows/WInstaller.Core.Tests/FakeCommandRunner.cs create mode 100644 apps/windows/WInstaller.Core.Tests/InfrastructureTests.cs create mode 100644 apps/windows/WInstaller.Core.Tests/OperationExecutorTests.cs create mode 100644 apps/windows/WInstaller.Core.Tests/TestFixtures.cs create mode 100644 apps/windows/WInstaller.Core.Tests/WInstaller.Core.Tests.csproj create mode 100644 apps/windows/WInstaller.Core/BootableUsbEngine.cs create mode 100644 apps/windows/WInstaller.Core/CommandRunner.cs create mode 100644 apps/windows/WInstaller.Core/DiskEnumerator.cs create mode 100644 apps/windows/WInstaller.Core/IsoInspector.cs create mode 100644 apps/windows/WInstaller.Core/LocalLogger.cs create mode 100644 apps/windows/WInstaller.Core/Models.cs create mode 100644 apps/windows/WInstaller.Core/OperationExecutor.cs create mode 100644 apps/windows/WInstaller.Core/Scripts/disk-info.ps1 create mode 100644 apps/windows/WInstaller.Core/Scripts/dismount-iso.ps1 create mode 100644 apps/windows/WInstaller.Core/Scripts/eject-disk.ps1 create mode 100644 apps/windows/WInstaller.Core/Scripts/list-disks.ps1 create mode 100644 apps/windows/WInstaller.Core/Scripts/mount-iso.ps1 create mode 100644 apps/windows/WInstaller.Core/Scripts/prepare-usb.ps1 create mode 100644 apps/windows/WInstaller.Core/Scripts/split-wim.ps1 create mode 100644 apps/windows/WInstaller.Core/Simulation.cs create mode 100644 apps/windows/WInstaller.Core/WInstaller.Core.csproj create mode 100644 apps/windows/WInstaller.sln create mode 100644 scripts/gen_strings_dotnet.py create mode 100644 scripts/make-ico.py diff --git a/.github/workflows/ci-windows.yml b/.github/workflows/ci-windows.yml new file mode 100644 index 0000000..8a2412b --- /dev/null +++ b/.github/workflows/ci-windows.yml @@ -0,0 +1,50 @@ +name: Windows + +on: + push: + branches: [main] + pull_request: + +jobs: + core-tests: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: "8.0.x" + + - name: Test core library + run: dotnet test apps/windows/WInstaller.Core.Tests/WInstaller.Core.Tests.csproj + + # The core targets plain net8.0 by design (see apps/windows/README.md), so + # the same tests also run on Linux — proving no accidental Windows-only APIs + # leak into the domain layer. + core-tests-linux: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: "8.0.x" + + - name: Test core library + run: dotnet test apps/windows/WInstaller.Core.Tests/WInstaller.Core.Tests.csproj + + app-build: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: "8.0.x" + + - name: Publish WinUI 3 app (unpackaged, self-contained) + run: > + dotnet publish apps/windows/WInstaller.App/WInstaller.App.csproj + -c Release -r win-x64 -p:Platform=x64 + -p:WindowsAppSDKSelfContained=true --self-contained true + -o ${{ runner.temp }}/publish diff --git a/.github/workflows/parity.yml b/.github/workflows/parity.yml index 3baf438..7cc9a8d 100644 --- a/.github/workflows/parity.yml +++ b/.github/workflows/parity.yml @@ -20,3 +20,18 @@ jobs: - name: Check screen parity run: python3 scripts/check_screen_parity.py + + strings-sync: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install dependencies + run: pip install pyyaml + + - name: Check generated strings are in sync with copy.yaml + run: python3 scripts/gen_strings_dotnet.py --check diff --git a/.github/workflows/release-windows.yml b/.github/workflows/release-windows.yml new file mode 100644 index 0000000..6dc7c47 --- /dev/null +++ b/.github/workflows/release-windows.yml @@ -0,0 +1,53 @@ +name: Release Windows app + +on: + release: + types: [published] + workflow_dispatch: + inputs: + tag: + description: "Existing release tag to attach the built app to" + required: true + +permissions: + contents: write + +jobs: + build-and-upload: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.release.tag_name || inputs.tag }} + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: "8.0.x" + + - name: Test core library + run: dotnet test apps/windows/WInstaller.Core.Tests/WInstaller.Core.Tests.csproj + + # Unpackaged self-contained publish: runs on a clean Windows 10/11 + # machine with no runtime or Windows App SDK install. The zip is + # unsigned until code signing is provisioned (ADR-0006 Phase 4 exit + # criterion); MSIX becomes the primary format once a certificate exists. + - name: Publish WinUI 3 app (portable, self-contained) + run: > + dotnet publish apps/windows/WInstaller.App/WInstaller.App.csproj + -c Release -r win-x64 -p:Platform=x64 + -p:WindowsAppSDKSelfContained=true --self-contained true + -o ${{ runner.temp }}/publish + + - name: Zip portable app + shell: pwsh + run: > + Compress-Archive -Path "${{ runner.temp }}/publish/*" + -DestinationPath "${{ runner.temp }}/wInstaller-Windows-x64.zip" + + - name: Upload asset to release + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + run: | + $tag = "${{ github.event.release.tag_name || inputs.tag }}" + gh release upload $tag "${{ runner.temp }}/wInstaller-Windows-x64.zip" --clobber -R "${{ github.repository }}" diff --git a/.gitignore b/.gitignore index 36a31c7..5ac0cac 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,9 @@ xcuserdata/ __pycache__/ *.pyc + +# .NET / WinUI (apps/windows) +bin/ +obj/ +publish/ +*.user diff --git a/README.md b/README.md index 619fcc8..9652fe3 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@

macOS CI + Windows CI Docs lint License: Noncommercial

@@ -22,16 +23,19 @@ before destructive actions, validates the result, and keeps everything local. **wInstaller is expanding from macOS-only to macOS, Windows, and Linux.** Each platform gets a fully native UI — SwiftUI, WinUI 3, and GTK4/libadwaita — built -on one shared Rust core engine. See [Architecture](#architecture) below and -[docs/adr/](docs/adr/) for the full reasoning. +on one shared core engine. The macOS and Windows apps have landed; Linux is +next. See [Architecture](#architecture) below and [docs/adr/](docs/adr/) for +the full reasoning. ## Download | macOS | Windows | Linux | |---|---|---| -| [Releases](https://github.com/pedrobritx/winstaller/releases) | *Coming soon (Phase 3)* | *Coming soon (Phase 2)* | +| [Releases](https://github.com/pedrobritx/winstaller/releases) | [Releases](https://github.com/pedrobritx/winstaller/releases) | *Coming soon (Phase 2)* | -Until signed release artifacts exist for a platform, build from source — see below. +Release artifacts are currently unsigned (Gatekeeper/SmartScreen will warn on +first launch); signing and notarization are tracked for 1.0. You can always +build from source instead — see below. ## Status @@ -48,11 +52,25 @@ The macOS app is feature-complete for the first-release happy path: - Liquid Glass SwiftUI interface (macOS 26) with native-material fallback - App icon and `.app` packaging script +The Windows app covers the same first-release happy path natively +(`apps/windows/`): + +- C# domain core mirroring the same state machine and safety gates + (`WInstaller.Core`, unit-tested on Windows *and* Linux in CI) +- Disk enumeration via PowerShell storage cmdlets with boot/system-disk + filtering at every layer +- Read-only ISO mount + inspection (`Mount-DiskImage -Access ReadOnly`) +- Real erase → GPT/FAT32 format → `robocopy` → validate → eject pipeline +- `DISM /Split-Image` for oversized `install.wim` files (no third-party tools) +- A single UAC prompt scoped to the destructive step only (ADR-0003) +- Local logging with user-profile redaction, Simulate (dry-run) mode +- WinUI 3 assistant UI with Mica, generated from the shared string table + > **Safety note:** Real disk operations format the selected removable drive. > Always verify the target and prefer the Simulate toggle first. Destructive > operations have not been run on hardware in CI — test on a spare USB. -Windows and Linux native apps are planned (see [ROADMAP.md](docs/specs/ROADMAP.md) and the +The Linux native app is planned next (see [ROADMAP.md](docs/specs/ROADMAP.md) and the phased delivery plan referenced from the ADRs). ## Building from source @@ -96,11 +114,28 @@ swift test \ **Requirements:** Swift 6.0+, macOS 15.0+, Xcode 16+ or Command Line Tools. -### Windows *(planned — Phase 3)* +### Windows + +Requires Windows 10 1809+ and the [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). -The Windows app (WinUI 3 + C#/.NET, `apps/windows/`) does not exist yet. Once it -lands, build instructions will appear here (`dotnet build` against -`WInstaller.sln`). +```powershell +git clone https://github.com/pedrobritx/winstaller.git +cd winstaller/apps/windows + +dotnet build WInstaller.sln # core + tests + WinUI 3 app +dotnet test WInstaller.Core.Tests # engine/parser/executor tests +dotnet run --project WInstaller.App # launch the assistant +``` + +To produce the portable release build (what CI attaches to releases): + +```powershell +dotnet publish WInstaller.App -c Release -r win-x64 -p:Platform=x64 ` + -p:WindowsAppSDKSelfContained=true --self-contained true -o publish +``` + +See [apps/windows/README.md](apps/windows/README.md) for how the app drives +PowerShell storage cmdlets, robocopy, and DISM, and for the elevation model. ### Linux *(planned — Phase 2)* @@ -135,7 +170,7 @@ or [VISION.md](docs/specs/VISION.md) for the complete set of interaction princip ## Architecture -wInstaller is three native UIs sharing one Rust core engine: +wInstaller is three native UIs sharing one core engine: - **macOS**: SwiftUI, calling into the core via a Swift wrapper package. - **Windows**: WinUI 3 + C#/.NET, calling into the core via P/Invoke. @@ -148,6 +183,12 @@ native, with no cross-platform UI framework. See [ARCHITECTURE.md](docs/specs/AR and every decision record under [docs/adr/](docs/adr/), starting with [docs/adr/0001-core-language-and-ffi.md](docs/adr/0001-core-language-and-ffi.md). +> **Transition note:** the shared Rust core (ADR-0001) has not landed yet. +> Today the macOS app implements the core in Swift (`Sources/WInstallerCore`) +> and the Windows app in C# (`apps/windows/WInstaller.Core`) — both against +> the same screen registry, shared copy source, and safety rules, so swapping +> in the Rust core later replaces internals, not behavior. + ## Documentation Map - [PRODUCT.md](docs/specs/PRODUCT.md): mission, users, success criteria, and non-goals. diff --git a/apps/windows/README.md b/apps/windows/README.md new file mode 100644 index 0000000..05f6b0a --- /dev/null +++ b/apps/windows/README.md @@ -0,0 +1,79 @@ +# wInstaller for Windows + +The native Windows app: **WinUI 3 + C#/.NET 8** (ADR-0004), sharing the +canonical screen flow, copy, and design tokens with the macOS and Linux apps +(ADR-0008). + +## Layout + +| Project | Purpose | +|---|---| +| `WInstaller.Core` | Domain logic: typed state machine, ISO detection, disk enumeration, safety gates, executor, local logging. Targets plain `net8.0` so tests run on any OS. | +| `WInstaller.Core/Scripts/*.ps1` | Bundled PowerShell helpers. Every system call is argv-only (`-File script.ps1 -Param value`) — never a shell-interpolated string. | +| `WInstaller.App` | The WinUI 3 assistant UI (unpackaged deployment). | +| `WInstaller.Core.Tests` | xunit tests for the engine, parsers, executor pipeline, and logger redaction. | + +> **Transition note (ADR-0001):** the long-term plan is one shared Rust core +> behind a C ABI. Until that lands, this app mirrors the macOS approach — the +> core domain logic is implemented natively (here in C#, `WInstaller.Core`) +> against the same screen registry, copy source, and safety rules, so the +> eventual swap to the Rust core replaces internals, not behavior. + +## How it talks to Windows + +- **Disk enumeration**: `Get-Disk`/`Get-Partition`/`Get-Volume` via + `list-disks.ps1`, parsed defensively as JSON. Boot/system disks are filtered + out and refused at every layer. +- **ISO inspection**: `Mount-DiskImage -Access ReadOnly`, directory scan, + dismount. The ISO is never modified. +- **Erase/format**: `prepare-usb.ps1` (Clear-Disk → Initialize-Disk GPT → + New-Partition → Format-Volume FAT32). This is the only elevated step — a + single UAC prompt scoped to the destructive operation (ADR-0003), *after* + the type-the-drive-name confirmation. The script re-checks the + boot/system/USB-bus gates inside the elevated context. +- **Copy**: `robocopy /E` (exit codes < 8 are success). +- **Oversized `install.wim`**: split into `.swm` parts with + `DISM /Split-Image` (ships with Windows — no third-party tool needed). +- **Eject**: Shell.Application `InvokeVerb('Eject')`. + +FAT32 note: Windows refuses to format FAT32 volumes larger than 32 GB, so on +bigger sticks wInstaller creates a 32 GB installer partition and leaves the +rest unallocated (the warning is surfaced in the plan review step). + +## Build and run + +Requires Windows 10 1809+ and the [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). + +```powershell +cd apps/windows +dotnet build WInstaller.sln # builds core + tests + WinUI app (x64) +dotnet test WInstaller.Core.Tests # engine/parser/executor tests +dotnet run --project WInstaller.App # launch the assistant +``` + +The core library and its tests also build and run on macOS/Linux +(`dotnet test WInstaller.Core.Tests`); only `WInstaller.App` needs Windows. + +## Package (portable zip) + +```powershell +dotnet publish WInstaller.App -c Release -r win-x64 -p:Platform=x64 ` + -p:WindowsAppSDKSelfContained=true --self-contained true -o publish +Compress-Archive publish\* wInstaller-Windows-x64.zip +``` + +This is what `.github/workflows/release-windows.yml` attaches to GitHub +releases. The artifact is currently **unsigned** — SmartScreen will warn on +first run until code signing is provisioned (tracked as the ADR-0006 Phase 4 +exit criterion; MSIX becomes the primary format once a certificate exists). + +## Strings + +User-facing copy is generated — do not edit `Strings/AppStrings.resx` by hand: + +```bash +# edit shared/strings/copy.yaml, then: +python3 scripts/gen_strings_dotnet.py +``` + +CI fails if the committed `.resx` drifts from `copy.yaml`. diff --git a/apps/windows/WInstaller.App/App.xaml b/apps/windows/WInstaller.App/App.xaml new file mode 100644 index 0000000..4d429cc --- /dev/null +++ b/apps/windows/WInstaller.App/App.xaml @@ -0,0 +1,12 @@ + + + + + + + + + diff --git a/apps/windows/WInstaller.App/App.xaml.cs b/apps/windows/WInstaller.App/App.xaml.cs new file mode 100644 index 0000000..c338425 --- /dev/null +++ b/apps/windows/WInstaller.App/App.xaml.cs @@ -0,0 +1,19 @@ +using Microsoft.UI.Xaml; + +namespace WInstaller.App; + +public partial class App : Application +{ + private Window? _window; + + public App() + { + InitializeComponent(); + } + + protected override void OnLaunched(LaunchActivatedEventArgs args) + { + _window = new MainWindow(); + _window.Activate(); + } +} diff --git a/apps/windows/WInstaller.App/AppStrings.cs b/apps/windows/WInstaller.App/AppStrings.cs new file mode 100644 index 0000000..3677d7b --- /dev/null +++ b/apps/windows/WInstaller.App/AppStrings.cs @@ -0,0 +1,27 @@ +using System.Resources; + +namespace WInstaller.App; + +/// +/// Reads the string table generated from shared/strings/copy.yaml +/// (scripts/gen_strings_dotnet.py). Do not hardcode user-facing copy — +/// add it to copy.yaml and regenerate (ADR-0008). +/// +internal static class AppStrings +{ + private static readonly ResourceManager Manager = + new("WInstaller.App.Strings.AppStrings", typeof(AppStrings).Assembly); + + public static string Get(string key) => Manager.GetString(key) ?? key; + + /// Fills copy.yaml-style placeholders like {drive_name}. + public static string Format(string key, params (string Name, string Value)[] replacements) + { + var text = Get(key); + foreach (var (name, value) in replacements) + { + text = text.Replace("{" + name + "}", value); + } + return text; + } +} diff --git a/apps/windows/WInstaller.App/Assets/wInstaller.ico b/apps/windows/WInstaller.App/Assets/wInstaller.ico new file mode 100644 index 0000000000000000000000000000000000000000..a7785f56a2681e3a989df22be5e01928e0fcfefb GIT binary patch literal 27758 zcmce-Wl$Vn@HV>3!eWaBm*5(lU_lp4a0~A45Zq;Pmq2h^T!TXhE&&3;-B~0AmmtBp z{QmEItL}$e@BMbCX3o@^(`S0R`>8%X^~?YOKmZB=7Z>nyrUtx10syoC001@h|LT_^ z0{}KJ*Pzh<)u+Y;0B}$N02u6l_4UXA0M1u06JECe=KmH40HWDm4prq3SQum&FPE|8 zWTn+#&Mz7OxM<*)mg?f!^hJD0PFh04d->}ax5^5X1dQmJR94Jw(|9e^^oa6Wb%^5; zsJPbdZc)MG4rt~PhrfD-sm|Ig8G@_&@eA%wxn>DH2YnI=lXBGYVnXhZ1T47>qZ6bq zl4d+e&ZTVGeb>KE*_|5YyL7I(tB6{PXAyb-4C-YXVfTM}H){`lUyiS}<$#R)VUvbg zrYL-KfomsNF8IO-Y?>4ZYx$e`!rzdd)=)K*hwa~ftYKCM_f52Q8Fdj7%(^qVHK=C$g#?& zfoF))dj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qR5{lXGlunTB1sl!ea0zF!$Br$D zlCh(nMp`1EyNj!@1h_g{+Gmdm9WWmd2YPn;JI^a9e3LuoCmeFRpekx0N6M zP)T;Mh*XNc6Y*!OoL}K#>+ijzmZDI%XCy-wqzM^BZw0x~@x80=q?vHGcN%i^Hdmf+ zzth}{_309^gEAP^_!Q^~mKQx=7DWdKD=+RGZZ74k*ZJ`J(w06PdU|tU;;)}+iUF2g zU;PW%{lQMyCq&J@!CCnyWG{Q^^vcu5cugnp=|Oa;d+0GB$Y#Xc^IBT@t-b;BPDDk6 ze&LHflUy6j6q*Dsipe;stO>ZXKu z3-X-3A&uk4sGuBRjy~RBc4kWQo=UD6jHP1osisaJ8)&zl6xYpyZgZjIM05+tbKM1{ zhl`a~l|1(WlJrtSC-)MZ}i)y3rbNJ$LdHNvh{rp}*=!!g( z=sSe_ay%_u%7m9Q!>KS*;wj9aNa>8v&@%iTkms<%pO933v?3E1&!d#U)2>7olF&&` z`)YN!+_Z1 zX9StjBqSoBR3~WiocP~!VN!<95Yn07D+Rr@Zo@vrdPllEtXdJbGw#)sa__C)c;Q`I zW~Y*FbP*-M%S*W_;Brz7UwGx9U34BsNYCO){3d$tkZ~ zq(tLo{fA+SvSd5|*Nju*_P2|D)7)BWRmR!p$`WVvM-xe>#MK1jonRqNKZxq%FLZGs zH^-Uvin3{xuJ%lt#eyza1xf~oWv;kKDK;6S6{Z8c7=p<9s$Znx&=x;C?`0wu9=x1J zlyhgC+Zs)Z2H`q4m-Y*`*Z8JN&Hs2(BE*6(xaEi>%*12I5YStGC2f&^KcNJ6HEt=k zS3(ILJ5wHQw*Mf)`J1(EtO`K +/// Coordinates the assistant flow: owns user intent, confirmation state, live +/// device data, and the running operation. Mirrors the macOS AssistantModel; +/// the flow ends at Done because the virtualization-handoff step is +/// not-applicable on Windows (docs/screen-inventory.yaml). +/// +public sealed class AssistantModel +{ + ///

Raised on every state transition the UI must re-render for. + public event Action? Changed; + + // Flow state + public AssistantStep Step { get; private set; } = AssistantStep.Welcome; + public InstallerIso? Iso { get; private set; } + public UsbDrive? SelectedDrive { get; private set; } + public OperationPlan? Plan { get; private set; } + public List Events { get; } = []; + public string ConfirmationText { get; private set; } = ""; + public string? ErrorMessage { get; private set; } + + // UI state + public bool IsInspectingIso { get; private set; } + public bool IsRefreshingDrives { get; private set; } + public bool IsRunning { get; private set; } + public bool SimulateMode { get; private set; } + + // Device data + public IReadOnlyList Drives { get; private set; } = []; + public string CommandLog { get; private set; } = ""; + + private readonly BootableUsbEngine _engine = new(); + private readonly ICommandRunner _liveRunner = new ProcessCommandRunner(); + private readonly LocalLogger _logger = new(); + private CancellationTokenSource? _executionCancellation; + + public bool CanContinue => Step switch + { + AssistantStep.Welcome => true, + AssistantStep.ChooseIso => Iso is not null && !IsInspectingIso, + AssistantStep.VerifyIso => Iso?.Confidence >= DetectionConfidence.Medium, + AssistantStep.InsertUsb => SelectedDrive is not null, + AssistantStep.AnalyzeUsb => Plan is not null, + AssistantStep.ConfirmErase => ConfirmationText == SelectedDrive?.DisplayName, + AssistantStep.CreateUsb => !IsRunning, + AssistantStep.Done => true, + _ => false, + }; + + public bool CanGoBack => Step > AssistantStep.Welcome && Step < AssistantStep.CreateUsb; + + // MARK: Navigation + + public void ContinueFlow() + { + ErrorMessage = null; + switch (Step) + { + case AssistantStep.Welcome: + Step = AssistantStep.ChooseIso; + break; + case AssistantStep.ChooseIso: + Step = AssistantStep.VerifyIso; + break; + case AssistantStep.VerifyIso: + Step = AssistantStep.InsertUsb; + _ = RefreshDrivesAsync(); + break; + case AssistantStep.InsertUsb: + CreatePlan(); + if (Plan is not null) + { + Step = AssistantStep.AnalyzeUsb; + } + break; + case AssistantStep.AnalyzeUsb: + Step = AssistantStep.ConfirmErase; + break; + case AssistantStep.ConfirmErase: + _ = ConfirmAndCreateAsync(); + break; + case AssistantStep.CreateUsb: + Step = AssistantStep.Done; + break; + case AssistantStep.Done: + Reset(); + break; + } + RaiseChanged(); + } + + public void GoBack() + { + if (!CanGoBack) + { + return; + } + ErrorMessage = null; + Step = (AssistantStep)((int)Step - 1); + RaiseChanged(); + } + + // MARK: ISO + + public async Task ImportIsoAsync(string path) + { + if (!path.EndsWith(".iso", StringComparison.OrdinalIgnoreCase)) + { + ErrorMessage = "Choose a file with the .iso extension."; + RaiseChanged(); + return; + } + + IsInspectingIso = true; + ErrorMessage = null; + RaiseChanged(); + try + { + var inspector = new IsoInspector(_liveRunner, _engine); + Iso = await inspector.InspectAsync(path); + } + catch (IsoInspectionException exception) + { + ErrorMessage = exception.UserMessage; + } + catch (BootableUsbException exception) + { + ErrorMessage = exception.UserMessage; + } + catch (Exception exception) + { + ErrorMessage = exception.Message; + } + IsInspectingIso = false; + RaiseChanged(); + } + + // MARK: USB + + public async Task RefreshDrivesAsync() + { + IsRefreshingDrives = true; + RaiseChanged(); + try + { + var enumerator = new DiskEnumerator(_liveRunner); + Drives = await enumerator.RemovableDrivesAsync(); + } + catch (Exception) + { + Drives = []; + } + if (SelectedDrive is not null && Drives.All(drive => drive.DiskNumber != SelectedDrive.DiskNumber)) + { + SelectedDrive = null; + } + IsRefreshingDrives = false; + RaiseChanged(); + } + + public void SelectDrive(UsbDrive? drive) + { + SelectedDrive = drive; + RaiseChanged(); + } + + private void CreatePlan() + { + if (Iso is null || SelectedDrive is null) + { + return; + } + try + { + Plan = _engine.MakePlan(Iso, SelectedDrive); + SeedEvents(Plan); + } + catch (BootableUsbException exception) + { + ErrorMessage = exception.UserMessage; + } + } + + // MARK: Confirmation input (does not raise Changed: the text box owns focus) + + public void SetConfirmationText(string text) => ConfirmationText = text; + + public void SetSimulateMode(bool enabled) => SimulateMode = enabled; + + // MARK: Execution + + private async Task ConfirmAndCreateAsync() + { + if (Plan is null || SelectedDrive is null) + { + return; + } + try + { + _engine.ConfirmErase(SelectedDrive, ConfirmationText); + } + catch (BootableUsbException exception) + { + ErrorMessage = exception.UserMessage; + RaiseChanged(); + return; + } + + Step = AssistantStep.CreateUsb; + IsRunning = true; + ErrorMessage = null; + SeedEvents(Plan); + RaiseChanged(); + + var executor = SimulateMode + ? Simulation.Executor(Plan, _logger) + : new OperationExecutor(_liveRunner, logger: _logger); + + _executionCancellation = new CancellationTokenSource(); + try + { + await foreach (var engineEvent in executor.Run(Plan, _executionCancellation.Token)) + { + Apply(engineEvent); + } + IsRunning = false; + CommandLog = _logger.ExportText(); + Step = AssistantStep.Done; + } + catch (ExecutionException exception) + { + IsRunning = false; + ErrorMessage = exception.UserMessage; + CommandLog = _logger.ExportText(); + } + catch (Exception exception) + { + IsRunning = false; + ErrorMessage = exception.Message; + } + RaiseChanged(); + } + + public void CancelExecution() + { + _executionCancellation?.Cancel(); + _executionCancellation = null; + } + + private void Apply(EngineEvent engineEvent) + { + var index = Events.FindIndex(existing => existing.Id == engineEvent.Id); + if (index >= 0) + { + Events[index] = engineEvent; + } + else + { + Events.Add(engineEvent); + } + RaiseChanged(); + } + + private void SeedEvents(OperationPlan plan) + { + Events.Clear(); + var seeds = new List<(string Id, string Title)> + { + ("mount-iso", "Mount ISO read-only"), + ("verify-usb", "Re-check USB identity"), + ("prepare-usb", "Erase and format USB drive"), + ("copy-files", "Copy installer files"), + }; + if (plan.Strategy.RequiresWimSplit) + { + seeds.Add(("split-wim", "Split oversized Windows image")); + } + seeds.Add(("validate", "Validate boot files")); + seeds.Add(("eject", "Eject USB safely")); + + Events.AddRange(seeds.Select(seed => + new EngineEvent(seed.Id, EngineState.Idle, seed.Title, "Waiting…", ChecklistStatus.Waiting))); + } + + // MARK: Reset + + private void Reset() + { + CancelExecution(); + _engine.Reset(); + Step = AssistantStep.Welcome; + Iso = null; + SelectedDrive = null; + Plan = null; + Events.Clear(); + ConfirmationText = ""; + ErrorMessage = null; + CommandLog = ""; + IsRunning = false; + } + + private void RaiseChanged() => Changed?.Invoke(); +} diff --git a/apps/windows/WInstaller.App/MainWindow.xaml b/apps/windows/WInstaller.App/MainWindow.xaml new file mode 100644 index 0000000..615bd9c --- /dev/null +++ b/apps/windows/WInstaller.App/MainWindow.xaml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/windows/WInstaller.App/MainWindow.xaml.cs b/apps/windows/WInstaller.App/MainWindow.xaml.cs new file mode 100644 index 0000000..623745e --- /dev/null +++ b/apps/windows/WInstaller.App/MainWindow.xaml.cs @@ -0,0 +1,117 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using Windows.Storage.Pickers; + +namespace WInstaller.App; + +public sealed partial class MainWindow : Window +{ + private static readonly (AssistantStep Step, string Title, string Glyph)[] SidebarSteps = + [ + (AssistantStep.Welcome, "Welcome", "\uE80F"), + (AssistantStep.ChooseIso, "Choose ISO", "\uE8A5"), + (AssistantStep.VerifyIso, "Verify ISO", "\uE73E"), + (AssistantStep.InsertUsb, "Insert USB", "\uE88E"), + (AssistantStep.AnalyzeUsb, "Analyze USB", "\uE9D9"), + (AssistantStep.ConfirmErase, "Confirm Erase", "\uE7BA"), + (AssistantStep.CreateUsb, "Create USB", "\uE895"), + (AssistantStep.Done, "Done", "\uE930"), + ]; + + internal AssistantModel Model { get; } = new(); + + public MainWindow() + { + InitializeComponent(); + Title = "wInstaller"; + SystemBackdrop = new MicaBackdrop(); + Model.Changed += Render; + Render(); + } + + private void Render() + { + RenderSidebar(); + StepContent.Content = Steps.Build(Model, this); + BackButton.IsEnabled = Model.CanGoBack; + BackButton.Visibility = Model.CanGoBack ? Visibility.Visible : Visibility.Collapsed; + ContinueButton.Content = ContinueLabel(); + ContinueButton.IsEnabled = Model.CanContinue; + ErrorText.Text = Model.ErrorMessage ?? ""; + } + + /// Called by the confirm-erase text box without a full re-render. + internal void RefreshContinueButton() => ContinueButton.IsEnabled = Model.CanContinue; + + private string ContinueLabel() => Model.Step switch + { + AssistantStep.ConfirmErase => AppStrings.Get("confirm-erase.action_confirm"), + AssistantStep.Done => "Start Over", + _ => "Continue", + }; + + private void RenderSidebar() + { + SidebarPanel.Children.Clear(); + foreach (var (step, title, glyph) in SidebarSteps) + { + var isCurrent = Model.Step == step; + var isReached = Model.Step >= step; + + var row = new Grid + { + Padding = new Thickness(10, 8, 10, 8), + CornerRadius = new CornerRadius(6), + }; + if (isCurrent) + { + row.Background = (Brush)Application.Current.Resources["AccentFillColorDefaultBrush"]; + } + row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + + var icon = new FontIcon { Glyph = glyph, FontSize = 14, Margin = new Thickness(0, 0, 10, 0) }; + var label = new TextBlock { Text = title, VerticalAlignment = VerticalAlignment.Center }; + Grid.SetColumn(label, 1); + + if (isCurrent) + { + icon.Foreground = (Brush)Application.Current.Resources["TextOnAccentFillColorPrimaryBrush"]; + label.Foreground = (Brush)Application.Current.Resources["TextOnAccentFillColorPrimaryBrush"]; + } + else if (!isReached) + { + icon.Foreground = (Brush)Application.Current.Resources["TextFillColorTertiaryBrush"]; + label.Foreground = (Brush)Application.Current.Resources["TextFillColorTertiaryBrush"]; + } + + row.Children.Add(icon); + row.Children.Add(label); + SidebarPanel.Children.Add(row); + } + } + + private void OnContinue(object sender, RoutedEventArgs args) => Model.ContinueFlow(); + + private void OnBack(object sender, RoutedEventArgs args) => Model.GoBack(); + + internal async Task PickIsoAsync() + { + var picker = new FileOpenPicker + { + SuggestedStartLocation = PickerLocationId.Downloads, + }; + picker.FileTypeFilter.Add(".iso"); + + // Unpackaged apps must associate the picker with a window handle. + var handle = WinRT.Interop.WindowNative.GetWindowHandle(this); + WinRT.Interop.InitializeWithWindow.Initialize(picker, handle); + + var file = await picker.PickSingleFileAsync(); + if (file is not null) + { + await Model.ImportIsoAsync(file.Path); + } + } +} diff --git a/apps/windows/WInstaller.App/Steps.cs b/apps/windows/WInstaller.App/Steps.cs new file mode 100644 index 0000000..9abc7fd --- /dev/null +++ b/apps/windows/WInstaller.App/Steps.cs @@ -0,0 +1,474 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using WInstaller.Core; + +namespace WInstaller.App; + +/// +/// Builds the content view for each assistant step. All user-facing copy comes +/// from the shared string table (AppStrings / copy.yaml); the step set matches +/// docs/screen-inventory.yaml. The `SCREEN:` markers below are read by +/// scripts/check_screen_parity.py. +/// +internal static class Steps +{ + public static UIElement Build(AssistantModel model, MainWindow window) => model.Step switch + { + AssistantStep.Welcome => Welcome(), + AssistantStep.ChooseIso => ChooseIso(model, window), + AssistantStep.VerifyIso => VerifyIso(model), + AssistantStep.InsertUsb => InsertUsb(model), + AssistantStep.AnalyzeUsb => AnalyzeUsb(model), + AssistantStep.ConfirmErase => ConfirmErase(model, window), + AssistantStep.CreateUsb => CreateUsb(model), + AssistantStep.Done => Done(model), + _ => new TextBlock { Text = "" }, + }; + + // SCREEN: welcome + private static UIElement Welcome() + { + var panel = Page("welcome.title", "welcome.subtitle"); + var card = Card(); + card.Children.Add(InfoRow("\uE8A5", AppStrings.Get("welcome.info_iso_title"), AppStrings.Get("welcome.info_iso_body"))); + card.Children.Add(InfoRow("\uE88E", AppStrings.Get("welcome.info_usb_title"), AppStrings.Get("welcome.info_usb_body"))); + card.Children.Add(InfoRow("\uE72E", AppStrings.Get("welcome.info_confirmation_title"), AppStrings.Get("welcome.info_confirmation_body"))); + card.Children.Add(InfoRow("\uE946", AppStrings.Get("welcome.info_local_title"), AppStrings.Get("welcome.info_local_body"))); + panel.Children.Add(Boxed(card)); + return panel; + } + + // SCREEN: choose-iso + private static UIElement ChooseIso(AssistantModel model, MainWindow window) + { + var panel = Page("choose-iso.title", "choose-iso.subtitle"); + + var chooseButton = new Button + { + Content = AppStrings.Get("choose-iso.action_choose"), + IsEnabled = !model.IsInspectingIso, + }; + chooseButton.Click += async (_, _) => await window.PickIsoAsync(); + panel.Children.Add(chooseButton); + + if (model.IsInspectingIso) + { + var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10 }; + row.Children.Add(new ProgressRing { IsActive = true, Width = 20, Height = 20 }); + row.Children.Add(Body(AppStrings.Get("choose-iso.status_mounting"))); + panel.Children.Add(row); + } + else if (model.Iso is { } iso) + { + var card = Card(); + card.Children.Add(FieldRow("File", iso.DisplayName)); + card.Children.Add(FieldRow("Size", ByteFormat.Bytes(iso.Size))); + panel.Children.Add(Boxed(card)); + } + + return panel; + } + + // SCREEN: verify-iso + private static UIElement VerifyIso(AssistantModel model) + { + var panel = Page("verify-iso.title", "verify-iso.subtitle"); + if (model.Iso is not { } iso) + { + return panel; + } + + var card = Card(); + card.Children.Add(FieldRow(AppStrings.Get("verify-iso.field_os"), iso.DetectedOs.DisplayName)); + card.Children.Add(FieldRow(AppStrings.Get("verify-iso.field_confidence"), iso.Confidence.ToString())); + card.Children.Add(FieldRow("File", iso.DisplayName)); + card.Children.Add(FieldRow("Size", ByteFormat.Bytes(iso.Size))); + if (!string.IsNullOrEmpty(iso.VolumeLabel)) + { + card.Children.Add(FieldRow("Volume label", iso.VolumeLabel!)); + } + card.Children.Add(FieldRow(AppStrings.Get("verify-iso.field_boot_files"), iso.BootFiles.Count.ToString())); + if (iso.WindowsImageInfo is { } imageInfo) + { + card.Children.Add(FieldRow( + AppStrings.Get("verify-iso.field_wim_status"), + AppStrings.Get(imageInfo.RequiresSplit ? "verify-iso.wim_split_required" : "verify-iso.wim_no_split"))); + } + panel.Children.Add(Boxed(card)); + return panel; + } + + // SCREEN: insert-usb + private static UIElement InsertUsb(AssistantModel model) + { + var panel = Page("insert-usb.title", "insert-usb.subtitle"); + + var refreshButton = new Button + { + Content = AppStrings.Get("insert-usb.action_refresh"), + IsEnabled = !model.IsRefreshingDrives, + }; + refreshButton.Click += async (_, _) => await model.RefreshDrivesAsync(); + panel.Children.Add(refreshButton); + + if (model.IsRefreshingDrives) + { + var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10 }; + row.Children.Add(new ProgressRing { IsActive = true, Width = 20, Height = 20 }); + row.Children.Add(Body(AppStrings.Get("insert-usb.status_looking"))); + panel.Children.Add(row); + } + else if (model.Drives.Count == 0) + { + var empty = Card(); + empty.Children.Add(Heading(AppStrings.Get("insert-usb.empty_title"))); + empty.Children.Add(Body(AppStrings.Get("insert-usb.empty_message"))); + panel.Children.Add(Boxed(empty)); + } + else + { + var list = new ListView { SelectionMode = ListViewSelectionMode.Single }; + foreach (var drive in model.Drives) + { + var row = new StackPanel { Spacing = 2, Padding = new Thickness(4, 8, 4, 8) }; + row.Children.Add(new TextBlock { Text = drive.DisplayName }); + row.Children.Add(Caption($"{drive.Identifier} · {ByteFormat.Bytes(drive.Size)} · {drive.ConnectionType} · {drive.FileSystem}")); + var item = new ListViewItem + { + Content = row, + Tag = drive, + IsSelected = model.SelectedDrive?.DiskNumber == drive.DiskNumber, + }; + list.Items.Add(item); + } + list.SelectionChanged += (_, _) => + model.SelectDrive((list.SelectedItem as ListViewItem)?.Tag as UsbDrive); + panel.Children.Add(list); + } + + return panel; + } + + // SCREEN: analyze-usb + private static UIElement AnalyzeUsb(AssistantModel model) + { + var panel = Page("analyze-usb.title", "analyze-usb.subtitle"); + if (model.Plan is not { } plan) + { + return panel; + } + + var strategyCard = Card(); + strategyCard.Children.Add(FieldRow("Partition scheme", plan.Strategy.TargetPartitionScheme)); + strategyCard.Children.Add(FieldRow("File system", plan.Strategy.TargetFileSystem)); + strategyCard.Children.Add(FieldRow("Data to copy", ByteFormat.Bytes(plan.EstimatedBytesToCopy))); + panel.Children.Add(Boxed(strategyCard)); + + foreach (var warning in plan.Strategy.Warnings) + { + var infoBar = new InfoBar + { + Severity = InfoBarSeverity.Warning, + Message = warning, + IsOpen = true, + IsClosable = false, + }; + panel.Children.Add(infoBar); + } + + var stepsCard = Card(); + foreach (var step in plan.Steps) + { + var row = new StackPanel { Spacing = 2 }; + var titleRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 }; + titleRow.Children.Add(new TextBlock { Text = step.Title }); + if (step.Command?.IsDestructive == true) + { + titleRow.Children.Add(new TextBlock + { + Text = "DESTRUCTIVE", + FontSize = 11, + Foreground = (Brush)Application.Current.Resources["SystemFillColorCriticalBrush"], + VerticalAlignment = VerticalAlignment.Center, + }); + } + row.Children.Add(titleRow); + row.Children.Add(Caption(step.Detail)); + stepsCard.Children.Add(row); + } + panel.Children.Add(Boxed(stepsCard)); + + return panel; + } + + // SCREEN: confirm-erase + private static UIElement ConfirmErase(AssistantModel model, MainWindow window) + { + var panel = Page("confirm-erase.title", "confirm-erase.subtitle"); + if (model.SelectedDrive is not { } drive) + { + return panel; + } + + panel.Children.Add(new InfoBar + { + Severity = InfoBarSeverity.Error, + Message = AppStrings.Format("confirm-erase.warning", ("drive_name", drive.DisplayName)), + IsOpen = true, + IsClosable = false, + }); + + panel.Children.Add(Body(AppStrings.Format( + "confirm-erase.detail_format", + ("identifier", drive.Identifier), + ("capacity", ByteFormat.Bytes(drive.Size)), + ("volumes", drive.Volumes.Count > 0 ? string.Join(", ", drive.Volumes) : "—")))); + + var confirmationBox = new TextBox + { + PlaceholderText = AppStrings.Format("confirm-erase.field_placeholder", ("drive_name", drive.DisplayName)), + Text = model.ConfirmationText, + }; + confirmationBox.TextChanged += (_, _) => + { + model.SetConfirmationText(confirmationBox.Text); + window.RefreshContinueButton(); + }; + panel.Children.Add(confirmationBox); + + var simulateCard = Card(); + var simulateRow = new Grid(); + simulateRow.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + simulateRow.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + var simulateText = new StackPanel { Spacing = 2 }; + simulateText.Children.Add(Heading(AppStrings.Get("confirm-erase.simulate_title"))); + simulateText.Children.Add(Caption(AppStrings.Get("confirm-erase.simulate_body"))); + var simulateSwitch = new ToggleSwitch { IsOn = model.SimulateMode, OnContent = null, OffContent = null }; + simulateSwitch.Toggled += (_, _) => model.SetSimulateMode(simulateSwitch.IsOn); + Grid.SetColumn(simulateSwitch, 1); + simulateRow.Children.Add(simulateText); + simulateRow.Children.Add(simulateSwitch); + simulateCard.Children.Add(simulateRow); + panel.Children.Add(Boxed(simulateCard)); + + return panel; + } + + // SCREEN: create-usb + private static UIElement CreateUsb(AssistantModel model) + { + var titleKey = model.SimulateMode ? "create-usb.title_simulate" : "create-usb.title_real"; + var subtitleKey = model.SimulateMode ? "create-usb.subtitle_simulate" : "create-usb.subtitle_real"; + var panel = new StackPanel { Spacing = 16, MaxWidth = 640, HorizontalAlignment = HorizontalAlignment.Left }; + panel.Children.Add(Title(AppStrings.Get(titleKey))); + panel.Children.Add(Body(AppStrings.Get(subtitleKey))); + + var checklist = Card(); + foreach (var engineEvent in model.Events) + { + checklist.Children.Add(ChecklistRow(engineEvent)); + } + panel.Children.Add(Boxed(checklist)); + + if (model.IsRunning) + { + var cancelButton = new Button { Content = AppStrings.Get("create-usb.action_cancel") }; + cancelButton.Click += (_, _) => model.CancelExecution(); + panel.Children.Add(cancelButton); + } + + return panel; + } + + // SCREEN: done + private static UIElement Done(AssistantModel model) + { + var titleKey = model.SimulateMode ? "done.title_simulate" : "done.title_real"; + var subtitleKey = model.SimulateMode ? "done.subtitle_simulate" : "done.subtitle_real"; + var panel = new StackPanel { Spacing = 16, MaxWidth = 640, HorizontalAlignment = HorizontalAlignment.Left }; + + var headline = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10 }; + headline.Children.Add(new FontIcon + { + Glyph = "\uE930", + FontSize = 28, + Foreground = (Brush)Application.Current.Resources["SystemFillColorSuccessBrush"], + }); + headline.Children.Add(Title(AppStrings.Get(titleKey))); + panel.Children.Add(headline); + panel.Children.Add(Body(AppStrings.Get(subtitleKey))); + + if (model.Plan is { } plan) + { + var card = Card(); + card.Children.Add(FieldRow("Installer", plan.Iso.DetectedOs.DisplayName)); + card.Children.Add(FieldRow("USB drive", $"{plan.Drive.DisplayName} ({plan.Drive.Identifier})")); + foreach (var check in plan.ValidationChecks) + { + var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 }; + row.Children.Add(new FontIcon + { + Glyph = "\uE73E", + FontSize = 12, + Foreground = (Brush)Application.Current.Resources["SystemFillColorSuccessBrush"], + }); + row.Children.Add(Body(check)); + card.Children.Add(row); + } + panel.Children.Add(Boxed(card)); + } + + if (!string.IsNullOrEmpty(model.CommandLog)) + { + panel.Children.Add(Heading("Command log (redacted)")); + var log = new TextBlock + { + Text = model.CommandLog, + FontFamily = new FontFamily("Consolas"), + FontSize = 12, + TextWrapping = TextWrapping.Wrap, + }; + var scroller = new ScrollViewer { Content = log, MaxHeight = 180 }; + panel.Children.Add(Boxed(Wrap(scroller))); + } + + return panel; + } + + // MARK: Shared building blocks + + private static StackPanel Page(string titleKey, string subtitleKey) + { + var panel = new StackPanel { Spacing = 16, MaxWidth = 640, HorizontalAlignment = HorizontalAlignment.Left }; + panel.Children.Add(Title(AppStrings.Get(titleKey))); + panel.Children.Add(Body(AppStrings.Get(subtitleKey))); + return panel; + } + + private static TextBlock Title(string text) => new() + { + Text = text, + FontSize = 26, + FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, + TextWrapping = TextWrapping.Wrap, + }; + + private static TextBlock Heading(string text) => new() + { + Text = text, + FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, + TextWrapping = TextWrapping.Wrap, + }; + + private static TextBlock Body(string text) => new() + { + Text = text, + TextWrapping = TextWrapping.Wrap, + Foreground = (Brush)Application.Current.Resources["TextFillColorSecondaryBrush"], + }; + + private static TextBlock Caption(string text) => new() + { + Text = text, + FontSize = 12, + TextWrapping = TextWrapping.Wrap, + Foreground = (Brush)Application.Current.Resources["TextFillColorTertiaryBrush"], + }; + + private static StackPanel Card() => new() { Spacing = 12 }; + + private static StackPanel Wrap(UIElement child) + { + var panel = Card(); + panel.Children.Add(child); + return panel; + } + + private static Border Boxed(UIElement content) => new() + { + Child = content, + Background = (Brush)Application.Current.Resources["CardBackgroundFillColorDefaultBrush"], + BorderBrush = (Brush)Application.Current.Resources["CardStrokeColorDefaultBrush"], + BorderThickness = new Thickness(1), + CornerRadius = new CornerRadius(8), + Padding = new Thickness(16), + }; + + private static Grid InfoRow(string glyph, string title, string body) + { + var row = new Grid(); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + + var icon = new FontIcon { Glyph = glyph, FontSize = 16, Margin = new Thickness(0, 2, 12, 0) }; + var text = new StackPanel { Spacing = 2 }; + text.Children.Add(Heading(title)); + text.Children.Add(Caption(body)); + Grid.SetColumn(text, 1); + + row.Children.Add(icon); + row.Children.Add(text); + return row; + } + + private static Grid FieldRow(string label, string value) + { + var row = new Grid(); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(160) }); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + + var caption = Caption(label); + var content = new TextBlock { Text = value, TextWrapping = TextWrapping.Wrap }; + Grid.SetColumn(content, 1); + + row.Children.Add(caption); + row.Children.Add(content); + return row; + } + + private static Grid ChecklistRow(EngineEvent engineEvent) + { + var row = new Grid(); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + + UIElement statusIcon; + if (engineEvent.Status == ChecklistStatus.Running) + { + statusIcon = new ProgressRing + { + IsActive = true, + Width = 16, + Height = 16, + Margin = new Thickness(0, 2, 12, 0), + }; + } + else + { + var (glyph, brushKey) = engineEvent.Status switch + { + ChecklistStatus.Complete => ("\uE73E", "SystemFillColorSuccessBrush"), + ChecklistStatus.Warning => ("\uE7BA", "SystemFillColorCautionBrush"), + ChecklistStatus.Failed => ("\uE711", "SystemFillColorCriticalBrush"), + _ => ("\uE823", "TextFillColorTertiaryBrush"), + }; + statusIcon = new FontIcon + { + Glyph = glyph, + FontSize = 14, + Margin = new Thickness(0, 2, 12, 0), + Foreground = (Brush)Application.Current.Resources[brushKey], + }; + } + + var text = new StackPanel { Spacing = 2 }; + text.Children.Add(new TextBlock { Text = engineEvent.Title }); + text.Children.Add(Caption(engineEvent.Detail)); + Grid.SetColumn(text, 1); + + row.Children.Add(statusIcon); + row.Children.Add(text); + return row; + } +} diff --git a/apps/windows/WInstaller.App/Strings/AppStrings.resx b/apps/windows/WInstaller.App/Strings/AppStrings.resx new file mode 100644 index 0000000..8dbc3e9 --- /dev/null +++ b/apps/windows/WInstaller.App/Strings/AppStrings.resx @@ -0,0 +1,191 @@ + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + wInstaller should feel like something a first-party disk utility would be if it actually explained itself. No telemetry, no uploads, no vague "optimizing" language — just a local assistant that tells you what it found, what it's about to do, and why. + + + A calm, native assistant for building bootable Windows and Linux USB installers — on macOS, Windows, and Linux. + + + wInstaller plans every command as arguments and marks destructive steps explicitly. + + + Review the operation plan + + + Choose ISO + + + Mounting and analyzing… + + + Select installation media. The importer rejects non-ISO files, then wInstaller mounts it read-only to analyze. + + + Choose an ISO file + + + Cancel + + + Erase and Create Bootable USB + + + Identifier: {identifier} · Capacity: {capacity} · Volumes: {volumes} + + + Type {drive_name} + + + Run the full sequence without erasing anything. + + + Simulate (dry-run) + + + Type the exact USB drive name to unlock the destructive operation. + + + Confirm erase + + + All data on {drive_name} will be erased. + + + Cancel + + + wInstaller is preparing the drive, copying files, and validating boot media. + + + Dry-run mode: wInstaller runs the full checklist without executing any destructive command. + + + Creating bootable USB + + + Simulating USB creation + + + The installer USB was created, validated, and safely ejected. + + + The simulated checklist completed. Turn off Simulate to create real media. + + + Bootable USB is ready + + + Dry run completed + + + Refresh + + + Plug in a USB drive, then choose Refresh. Internal disks are never shown. + + + Connect a removable USB drive + + + Looking for removable drives… + + + Internal disks are hidden and refused by the planning engine. + + + Select a removable USB drive + + + Open + + + Virtualization app detected + + + Windows may require a valid license. + + + You can still use the USB you created. Install a virtualization app to continue in a VM. + + + No supported virtualization app is installed + + + wInstaller does not create or start virtual machines without explicit user intent. + + + Use with a virtualization app + + + Boot files + + + Confidence + + + Operating system + + + WIM status + + + wInstaller explains what it detected before a USB drive is selected. + + + Verify the installer + + + No split required + + + Split required + + + Erase is blocked until the drive name is typed. + + + Confirmation + + + Choose Windows or Linux installation media. + + + ISO file + + + Every operation runs on this machine. No uploads. + + + Local only + + + Use removable media with enough capacity. + + + USB drive + + + wInstaller guides ISO selection, USB verification, erase confirmation, copy planning, validation, and virtualization handoff. + + + Create a bootable installer USB + + diff --git a/apps/windows/WInstaller.App/WInstaller.App.csproj b/apps/windows/WInstaller.App/WInstaller.App.csproj new file mode 100644 index 0000000..1e278a0 --- /dev/null +++ b/apps/windows/WInstaller.App/WInstaller.App.csproj @@ -0,0 +1,32 @@ + + + + WinExe + net8.0-windows10.0.19041.0 + 10.0.17763.0 + 10.0.17763.0 + WInstaller.App + wInstaller + app.manifest + Assets\wInstaller.ico + x64;ARM64 + win-x64;win-arm64 + true + true + + None + enable + enable + + + + + + + + + + + + diff --git a/apps/windows/WInstaller.App/app.manifest b/apps/windows/WInstaller.App/app.manifest new file mode 100644 index 0000000..05b20be --- /dev/null +++ b/apps/windows/WInstaller.App/app.manifest @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + PerMonitorV2 + true + + + diff --git a/apps/windows/WInstaller.Core.Tests/BootableUsbEngineTests.cs b/apps/windows/WInstaller.Core.Tests/BootableUsbEngineTests.cs new file mode 100644 index 0000000..fd653b4 --- /dev/null +++ b/apps/windows/WInstaller.Core.Tests/BootableUsbEngineTests.cs @@ -0,0 +1,228 @@ +using Xunit; + +namespace WInstaller.Core.Tests; + +public class BootableUsbEngineTests +{ + [Fact] + public void AnalyzeIso_DetectsWindowsWithHighConfidence() + { + var engine = new BootableUsbEngine(); + var iso = TestFixtures.WindowsIso(engine); + + Assert.Equal(OperatingSystemKind.Windows, iso.DetectedOs.Kind); + Assert.Equal(DetectionConfidence.High, iso.Confidence); + Assert.NotNull(iso.WindowsImageInfo); + Assert.Equal(3_800_000_000, iso.WindowsImageInfo!.InstallWimSize); + Assert.Contains("sources/boot.wim", iso.BootFiles); + Assert.Equal(EngineState.WaitingForUsb, engine.State); + } + + [Fact] + public void AnalyzeIso_NormalizesBackslashesAndCase() + { + var engine = new BootableUsbEngine(); + var iso = engine.AnalyzeIso( + path: @"C:\isos\win.iso", + size: 5_000_000_000, + volumeLabel: null, + directoryEntries: [@"SETUP.EXE", @"sources\BOOT.WIM", @"sources\install.wim", @"efi\boot\bootx64.efi"], + fileSizes: new Dictionary()); + + Assert.Equal(OperatingSystemKind.Windows, iso.DetectedOs.Kind); + Assert.Equal(DetectionConfidence.High, iso.Confidence); + } + + [Fact] + public void AnalyzeIso_ThreeMarkersIsMediumConfidence() + { + var engine = new BootableUsbEngine(); + var iso = engine.AnalyzeIso( + path: @"C:\isos\win.iso", + size: 5_000_000_000, + volumeLabel: null, + directoryEntries: ["setup.exe", "sources/boot.wim", "sources/install.esd"], + fileSizes: new Dictionary()); + + Assert.Equal(DetectionConfidence.Medium, iso.Confidence); + Assert.True(iso.WindowsImageInfo!.HasInstallEsd); + } + + [Fact] + public void AnalyzeIso_DetectsLinuxFromMarkers() + { + var engine = new BootableUsbEngine(); + var iso = engine.AnalyzeIso( + path: "/isos/ubuntu.iso", + size: 4_000_000_000, + volumeLabel: "Ubuntu 24.04 LTS amd64", + directoryEntries: ["casper/vmlinuz", ".disk/info", "efi/boot/bootx64.efi", "boot/grub/grub.cfg"], + fileSizes: new Dictionary()); + + Assert.Equal(OperatingSystemKind.Linux, iso.DetectedOs.Kind); + Assert.Equal("Ubuntu 24.04 LTS amd64", iso.DetectedOs.Detail); + Assert.Equal(DetectionConfidence.Medium, iso.Confidence); + } + + [Fact] + public void AnalyzeIso_UnknownMediaThrows() + { + var engine = new BootableUsbEngine(); + var exception = Assert.Throws(() => engine.AnalyzeIso( + path: @"C:\isos\data.iso", + size: 1_000_000, + volumeLabel: "DATA", + directoryEntries: ["readme.txt", "photos/cat.jpg"], + fileSizes: new Dictionary())); + + Assert.Equal(UsbErrorKind.UnsupportedIso, exception.Kind); + Assert.Equal(EngineState.Failed, engine.State); + } + + [Theory] + [InlineData(4_294_967_294, false)] + [InlineData(4_294_967_295, false)] + [InlineData(4_294_967_296, true)] + public void WindowsImageInfo_SplitsOnlyAboveFat32Limit(long wimSize, bool expected) + { + var info = new WindowsImageInfo(wimSize, HasInstallEsd: false); + Assert.Equal(expected, info.RequiresSplit); + } + + [Fact] + public void MakePlan_RefusesNonRemovableDrive() + { + var engine = new BootableUsbEngine(); + var iso = TestFixtures.WindowsIso(engine); + var fixedDisk = TestFixtures.RemovableDrive() with { IsRemovable = false }; + + var exception = Assert.Throws(() => engine.MakePlan(iso, fixedDisk)); + Assert.Equal(UsbErrorKind.DiskNotRemovable, exception.Kind); + Assert.Equal(EngineState.Failed, engine.State); + } + + [Fact] + public void MakePlan_RefusesSystemDisk() + { + var engine = new BootableUsbEngine(); + var iso = TestFixtures.WindowsIso(engine); + var systemDisk = TestFixtures.SystemDrive() with { IsRemovable = true }; + + var exception = Assert.Throws(() => engine.MakePlan(iso, systemDisk)); + Assert.Equal(UsbErrorKind.DiskIsSystem, exception.Kind); + } + + [Fact] + public void MakePlan_RefusesUndersizedDrive() + { + var engine = new BootableUsbEngine(); + var iso = TestFixtures.WindowsIso(engine); + var tinyDrive = TestFixtures.RemovableDrive(size: 1_000_000_000); + + var exception = Assert.Throws(() => engine.MakePlan(iso, tinyDrive)); + Assert.Equal(UsbErrorKind.InsufficientCapacity, exception.Kind); + } + + [Fact] + public void MakePlan_ReportsMissingTools() + { + var engine = new BootableUsbEngine(); + var iso = TestFixtures.WindowsIso(engine); + + var exception = Assert.Throws(() => + engine.MakePlan(iso, TestFixtures.RemovableDrive(), new ToolAvailability(Robocopy: false))); + Assert.Equal(UsbErrorKind.MissingTool, exception.Kind); + Assert.Contains("robocopy", exception.UserMessage); + } + + [Fact] + public void MakePlan_RequiresDismOnlyWhenSplitting() + { + var engine = new BootableUsbEngine(); + var smallWim = TestFixtures.WindowsIso(engine); + var noDism = new ToolAvailability(Dism: false); + + // No split required: DISM absence is fine. + var plan = engine.MakePlan(smallWim, TestFixtures.RemovableDrive(), noDism); + Assert.False(plan.Strategy.RequiresWimSplit); + + var engine2 = new BootableUsbEngine(); + var bigWim = TestFixtures.WindowsIso(engine2, installWimSize: 5_100_000_000); + var exception = Assert.Throws(() => + engine2.MakePlan(bigWim, TestFixtures.RemovableDrive(), noDism)); + Assert.Equal(UsbErrorKind.MissingTool, exception.Kind); + } + + [Fact] + public void MakePlan_MarksExactlyOneDestructiveElevatedStep() + { + var engine = new BootableUsbEngine(); + var plan = engine.MakePlan(TestFixtures.WindowsIso(engine), TestFixtures.RemovableDrive()); + + var destructive = Assert.Single(plan.DestructiveSteps); + Assert.Equal("prepare-usb", destructive.Id); + Assert.True(destructive.Command!.RequiresElevation); + Assert.True(plan.RequiresAuthorization); + Assert.Equal(EngineState.AwaitingEraseConfirmation, engine.State); + } + + [Fact] + public void MakePlan_AddsSplitStepAndWarningsForOversizedWim() + { + var engine = new BootableUsbEngine(); + var iso = TestFixtures.WindowsIso(engine, installWimSize: 5_100_000_000); + var plan = engine.MakePlan(iso, TestFixtures.RemovableDrive()); + + Assert.True(plan.Strategy.RequiresWimSplit); + Assert.Contains(plan.Steps, step => step.Id == "split-wim"); + Assert.Contains(plan.Strategy.Warnings, warning => warning.Contains("split")); + // 64 GB stick: warn that the FAT32 partition is capped at 32 GB. + Assert.Contains(plan.Strategy.Warnings, warning => warning.Contains("32 GB")); + Assert.Contains(@"sources\install.swm", plan.ValidationChecks); + } + + [Fact] + public void ConfirmErase_RejectsMismatchedName() + { + var engine = new BootableUsbEngine(); + var drive = TestFixtures.RemovableDrive(); + _ = engine.MakePlan(TestFixtures.WindowsIso(engine), drive); + + var exception = Assert.Throws(() => engine.ConfirmErase(drive, "wrong name")); + Assert.Equal(UsbErrorKind.ConfirmationMismatch, exception.Kind); + } + + [Fact] + public void ConfirmErase_RequiresPlanningFirst() + { + var engine = new BootableUsbEngine(); + var exception = Assert.Throws(() => + engine.ConfirmErase(TestFixtures.RemovableDrive(), "Kingston DataTraveler 3.0")); + Assert.Equal(UsbErrorKind.InvalidState, exception.Kind); + } + + [Fact] + public void ConfirmErase_ExactNameUnlocksExecution() + { + var engine = new BootableUsbEngine(); + var drive = TestFixtures.RemovableDrive(); + _ = engine.MakePlan(TestFixtures.WindowsIso(engine), drive); + + engine.ConfirmErase(drive, "Kingston DataTraveler 3.0"); + Assert.Equal(EngineState.PreparingDrive, engine.State); + } + + [Fact] + public void DryRunEvents_IncludeWimRowOnlyWhenSplitting() + { + var engine = new BootableUsbEngine(); + var plan = engine.MakePlan(TestFixtures.WindowsIso(engine), TestFixtures.RemovableDrive()); + Assert.DoesNotContain(engine.DryRunEvents(plan), e => e.Id == "wim"); + + var engine2 = new BootableUsbEngine(); + var bigPlan = engine2.MakePlan( + TestFixtures.WindowsIso(engine2, installWimSize: 5_100_000_000), + TestFixtures.RemovableDrive()); + Assert.Contains(engine2.DryRunEvents(bigPlan), e => e.Id == "wim"); + } +} diff --git a/apps/windows/WInstaller.Core.Tests/DiskEnumeratorTests.cs b/apps/windows/WInstaller.Core.Tests/DiskEnumeratorTests.cs new file mode 100644 index 0000000..cb5efd0 --- /dev/null +++ b/apps/windows/WInstaller.Core.Tests/DiskEnumeratorTests.cs @@ -0,0 +1,126 @@ +using Xunit; + +namespace WInstaller.Core.Tests; + +public class DiskEnumeratorTests +{ + private const string ListFixture = """ + [ + { + "Number": 0, + "FriendlyName": "Samsung SSD 980 PRO 1TB", + "Size": 1000204886016, + "BusType": "NVMe", + "IsBoot": true, + "IsSystem": true, + "IsRemovableMedia": false, + "PartitionStyle": "GPT", + "Volumes": [ + { "DriveLetter": "C", "FileSystemLabel": "Windows", "FileSystem": "NTFS" } + ] + }, + { + "Number": 3, + "FriendlyName": "Kingston DataTraveler 3.0", + "Size": 61530439680, + "BusType": "USB", + "IsBoot": false, + "IsSystem": false, + "IsRemovableMedia": true, + "PartitionStyle": "MBR", + "Volumes": [ + { "DriveLetter": "E", "FileSystemLabel": "UNTITLED", "FileSystem": "exFAT" } + ] + } + ] + """; + + [Fact] + public void ParseDiskList_MapsBothDisks() + { + var disks = DiskEnumerator.ParseDiskList(ListFixture); + + Assert.Equal(2, disks.Count); + + var system = disks[0]; + Assert.True(system.IsSystemDisk); + Assert.False(system.IsRemovable); + Assert.Equal("GPT", system.PartitionScheme); + Assert.Equal("NTFS", system.FileSystem); + Assert.Equal(["Windows"], system.Volumes); + + var usb = disks[1]; + Assert.Equal(3, usb.DiskNumber); + Assert.Equal("Disk 3", usb.Identifier); + Assert.True(usb.IsRemovable); + Assert.False(usb.IsSystemDisk); + Assert.Equal(61_530_439_680, usb.Size); + Assert.Equal("Kingston DataTraveler 3.0", usb.DisplayName); + } + + [Fact] + public void ParseDiskList_AcceptsSingleObject() + { + // ConvertTo-Json collapses single-element arrays to a bare object. + const string fixture = """ + { "Number": 2, "FriendlyName": "SanDisk Ultra", "Size": 32000000000, "BusType": "USB", + "IsBoot": false, "IsSystem": false, "IsRemovableMedia": true, "PartitionStyle": "RAW", "Volumes": [] } + """; + var disks = DiskEnumerator.ParseDiskList(fixture); + + var disk = Assert.Single(disks); + Assert.Equal("SanDisk Ultra", disk.DisplayName); + Assert.Equal("Unformatted", disk.PartitionScheme); + Assert.Equal("Unformatted", disk.FileSystem); + } + + [Fact] + public void ParseDriveInfo_FallsBackToDriveLetterWhenUnlabeled() + { + const string fixture = """ + { "Number": 4, "FriendlyName": "Generic Flash Disk", "Size": 8000000000, "BusType": "USB", + "IsBoot": false, "IsSystem": false, "IsRemovableMedia": true, "PartitionStyle": "MBR", + "Volumes": [ { "DriveLetter": "F", "FileSystemLabel": "", "FileSystem": "FAT32" } ] } + """; + var drive = DiskEnumerator.ParseDriveInfo(fixture); + + Assert.Equal(["F:"], drive.Volumes); + Assert.Equal("FAT32", drive.FileSystem); + } + + [Fact] + public async Task RemovableDrives_FiltersOutSystemDisks() + { + var runner = new FakeCommandRunner(); + runner.RespondToScript("list-disks.ps1", ListFixture); + var enumerator = new DiskEnumerator(runner); + + var drives = await enumerator.RemovableDrivesAsync(); + + var drive = Assert.Single(drives); + Assert.Equal(3, drive.DiskNumber); + } + + [Fact] + public async Task RemovableDrives_EmptyOnCommandFailure() + { + var runner = new FakeCommandRunner(); + runner.RespondToScript("list-disks.ps1", "", exitCode: 1); + var enumerator = new DiskEnumerator(runner); + + var drives = await enumerator.RemovableDrivesAsync(); + + Assert.Empty(drives); + } + + [Theory] + [InlineData("GPT", "GPT")] + [InlineData("MBR", "MBR")] + [InlineData("RAW", "Unformatted")] + [InlineData(null, "Unknown")] + [InlineData("Weird", "Weird")] + public void PartitionScheme_Mapping(string? style, string expected) + { + Assert.Equal(expected, DiskEnumerator.PartitionScheme(style)); + } +} diff --git a/apps/windows/WInstaller.Core.Tests/FakeCommandRunner.cs b/apps/windows/WInstaller.Core.Tests/FakeCommandRunner.cs new file mode 100644 index 0000000..a453edc --- /dev/null +++ b/apps/windows/WInstaller.Core.Tests/FakeCommandRunner.cs @@ -0,0 +1,55 @@ +namespace WInstaller.Core.Tests; + +/// +/// Records every command the pipeline asks for and answers from scripted +/// responses, so executor tests never touch a real process or disk. +/// +internal sealed class FakeCommandRunner : ICommandRunner +{ + public sealed record Response(string StandardOutput = "", string StandardError = "", int ExitCode = 0); + + private readonly Dictionary _scriptResponses = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _executableResponses = new(StringComparer.OrdinalIgnoreCase); + + public List Commands { get; } = []; + + public void RespondToScript(string scriptName, string standardOutput, int exitCode = 0, string standardError = "") => + _scriptResponses[scriptName] = new Response(standardOutput, standardError, exitCode); + + public void RespondToExecutable(string executableName, string standardOutput, int exitCode = 0, string standardError = "") => + _executableResponses[executableName] = new Response(standardOutput, standardError, exitCode); + + public Task RunAsync(PlannedCommand command, CommandTimeout timeout, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + Commands.Add(command); + + var script = command.Arguments + .Select(Path.GetFileName) + .FirstOrDefault(name => name?.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase) == true); + + Response response; + if (script is not null && _scriptResponses.TryGetValue(script, out var scripted)) + { + response = scripted; + } + else if (_executableResponses.TryGetValue(Path.GetFileName(command.Executable), out var byExecutable)) + { + response = byExecutable; + } + else + { + response = new Response(); + } + + var now = DateTimeOffset.Now; + return Task.FromResult(new CommandResult( + command.Executable, + command.Arguments, + response.StandardOutput, + response.StandardError, + response.ExitCode, + now, + now)); + } +} diff --git a/apps/windows/WInstaller.Core.Tests/InfrastructureTests.cs b/apps/windows/WInstaller.Core.Tests/InfrastructureTests.cs new file mode 100644 index 0000000..879d3ed --- /dev/null +++ b/apps/windows/WInstaller.Core.Tests/InfrastructureTests.cs @@ -0,0 +1,122 @@ +using Xunit; + +namespace WInstaller.Core.Tests; + +public class IsoInspectorParsingTests +{ + [Fact] + public void ParseMount_ReadsDriveLetterAndLabel() + { + var mount = IsoInspector.ParseMount("""{"DriveLetter":"F","VolumeLabel":"CCCOMA_X64FRE"}"""); + Assert.Equal("F", mount.DriveLetter); + Assert.Equal("CCCOMA_X64FRE", mount.VolumeLabel); + } + + [Fact] + public void ParseMount_TreatsMissingLetterAsNull() + { + var mount = IsoInspector.ParseMount("""{"DriveLetter":"","VolumeLabel":""}"""); + Assert.Null(mount.DriveLetter); + } + + [Fact] + public void Scan_NormalizesSeparatorsAndRecordsLowercasedSizes() + { + var root = Path.Combine(Path.GetTempPath(), $"winstaller-scan-{Guid.NewGuid():N}"); + try + { + Directory.CreateDirectory(Path.Combine(root, "Sources")); + Directory.CreateDirectory(Path.Combine(root, ".disk")); + File.WriteAllText(Path.Combine(root, "Sources", "Install.wim"), "wim-bytes"); + File.WriteAllText(Path.Combine(root, ".disk", "info"), "Ubuntu"); + + var scan = IsoInspector.Scan(root); + + Assert.Contains("Sources/Install.wim", scan.Entries); + Assert.Contains(".disk/info", scan.Entries); + Assert.True(scan.FileSizes.ContainsKey("sources/install.wim")); + Assert.Equal(9, scan.FileSizes["sources/install.wim"]); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Fact] + public void Scan_MissingRootYieldsEmptyResult() + { + var scan = IsoInspector.Scan(Path.Combine(Path.GetTempPath(), "definitely-not-a-mount-point")); + Assert.Empty(scan.Entries); + Assert.Empty(scan.FileSizes); + } +} + +public class LocalLoggerTests +{ + [Fact] + public void Redact_HidesWindowsUserPaths() + { + var redacted = LocalLogger.Redact(@"copy C:\Users\pedro\Downloads\win11.iso to E:\"); + Assert.DoesNotContain("pedro", redacted); + Assert.Contains(@"C:\Users\\Downloads\win11.iso", redacted); + } + + [Fact] + public void Redact_HandlesForwardSlashesAndCase() + { + var redacted = LocalLogger.Redact("c:/users/Pedro Brito/file.iso"); + Assert.DoesNotContain("Pedro", redacted); + } + + [Fact] + public void Format_IncludesOperationExitCodeAndIndentedDetail() + { + var entry = new LogEntry( + OperationId: "prepare-usb", + Tool: "powershell.exe", + Arguments: ["-File", "prepare-usb.ps1"], + ExitCode: 0, + UserMessage: "Erase and format USB drive", + TechnicalDetail: "line one\nline two"); + + var formatted = LocalLogger.Format(entry); + + Assert.Contains("prepare-usb powershell.exe", formatted); + Assert.Contains("exit=0", formatted); + Assert.Contains("— Erase and format USB drive", formatted); + Assert.Contains("\n line two", formatted); + } + + [Fact] + public void Record_PersistsToTheLogFile() + { + var directory = Path.Combine(Path.GetTempPath(), $"winstaller-log-{Guid.NewGuid():N}"); + try + { + var logger = new LocalLogger(directory); + logger.Record(new LogEntry("mount-iso", "powershell.exe", [], 0, "Mount ISO read-only")); + + var logFile = Path.Combine(directory, "winstaller.log"); + Assert.True(File.Exists(logFile)); + Assert.Contains("Mount ISO read-only", File.ReadAllText(logFile)); + Assert.Single(logger.AllEntries); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } +} + +public class ByteFormatTests +{ + [Theory] + [InlineData(999, "999 bytes")] + [InlineData(64_000_000_000, "64 GB")] + [InlineData(6_500_000_000, "6.5 GB")] + public void Bytes_UsesDecimalUnits(long value, string expected) + { + Assert.Equal(expected, ByteFormat.Bytes(value)); + } +} diff --git a/apps/windows/WInstaller.Core.Tests/OperationExecutorTests.cs b/apps/windows/WInstaller.Core.Tests/OperationExecutorTests.cs new file mode 100644 index 0000000..0d0555d --- /dev/null +++ b/apps/windows/WInstaller.Core.Tests/OperationExecutorTests.cs @@ -0,0 +1,207 @@ +using Xunit; + +namespace WInstaller.Core.Tests; + +public class OperationExecutorTests +{ + private static (OperationPlan Plan, FakeCommandRunner Runner) HappyPathSetup(long installWimSize = 3_800_000_000) + { + var engine = new BootableUsbEngine(); + var iso = TestFixtures.WindowsIso(engine, installWimSize); + var drive = TestFixtures.RemovableDrive(); + var plan = engine.MakePlan(iso, drive); + engine.ConfirmErase(drive, drive.DisplayName); + + var runner = new FakeCommandRunner(); + runner.RespondToScript("mount-iso.ps1", """{"DriveLetter":"F","VolumeLabel":"CCCOMA_X64FRE"}"""); + runner.RespondToScript("disk-info.ps1", DiskInfoJson(drive)); + runner.RespondToScript("prepare-usb.ps1", """{"DriveLetter":"E","VolumeLabel":"WINSTALLER"}"""); + runner.RespondToExecutable("robocopy.exe", "", exitCode: 1); // 1 = files copied successfully + return (plan, runner); + } + + private static string DiskInfoJson(UsbDrive drive, long? sizeOverride = null, bool isSystem = false) => $$""" + { "Number": {{drive.DiskNumber}}, "FriendlyName": "{{drive.MediaName}}", "Size": {{sizeOverride ?? drive.Size}}, + "BusType": "USB", "IsBoot": {{(isSystem ? "true" : "false")}}, "IsSystem": {{(isSystem ? "true" : "false")}}, + "IsRemovableMedia": true, "PartitionStyle": "MBR", "Volumes": [] } + """; + + private static async Task<(List Events, Exception? Error)> Collect(OperationExecutor executor, OperationPlan plan) + { + var events = new List(); + try + { + await foreach (var engineEvent in executor.Run(plan)) + { + events.Add(engineEvent); + } + return (events, null); + } + catch (Exception exception) + { + return (events, exception); + } + } + + [Fact] + public async Task HappyPath_RunsFullChecklistInOrder() + { + var (plan, runner) = HappyPathSetup(); + var executor = new OperationExecutor(runner, missingFiles: _ => []); + + var (events, error) = await Collect(executor, plan); + + Assert.Null(error); + var completedIds = events.Where(e => e.Status == ChecklistStatus.Complete).Select(e => e.Id).ToList(); + Assert.Equal(["mount-iso", "verify-usb", "prepare-usb", "copy-files", "validate", "eject", "completed"], completedIds); + + // The destructive step must come only after the identity re-check. + var destructiveIndex = runner.Commands.FindIndex(c => c.IsDestructive); + var identityIndex = runner.Commands.FindIndex(c => c.Arguments.Any(a => a.EndsWith("disk-info.ps1"))); + Assert.True(identityIndex >= 0 && destructiveIndex > identityIndex); + + // Robocopy copies the mounted ISO to the freshly formatted volume. + var robocopy = runner.Commands.Single(c => c.Executable.EndsWith("robocopy.exe")); + Assert.Equal([@"F:\", @"E:\"], robocopy.Arguments.Take(2)); + Assert.Contains("/E", robocopy.Arguments); + Assert.DoesNotContain("/XF", robocopy.Arguments); + + // The read-only ISO mount is always released at the end. + Assert.Contains(runner.Commands, c => c.Arguments.Any(a => a.EndsWith("dismount-iso.ps1"))); + } + + [Fact] + public async Task OversizedWim_IsExcludedFromCopyAndSplit() + { + var (plan, runner) = HappyPathSetup(installWimSize: 5_100_000_000); + runner.RespondToScript("split-wim.ps1", """{"Status":"ok"}"""); + var executor = new OperationExecutor(runner, missingFiles: _ => []); + + var (events, error) = await Collect(executor, plan); + + Assert.Null(error); + Assert.Contains(events, e => e.Id == "split-wim" && e.Status == ChecklistStatus.Complete); + + var robocopy = runner.Commands.Single(c => c.Executable.EndsWith("robocopy.exe")); + Assert.Contains("/XF", robocopy.Arguments); + Assert.Contains("install.wim", robocopy.Arguments); + } + + [Fact] + public async Task IdentityMismatch_AbortsBeforeAnyDestructiveCommand() + { + var (plan, runner) = HappyPathSetup(); + // The disk shrank between confirmation and execution: someone swapped drives. + runner.RespondToScript("disk-info.ps1", DiskInfoJson(plan.Drive, sizeOverride: 8_000_000_000)); + var executor = new OperationExecutor(runner, missingFiles: _ => []); + + var (_, error) = await Collect(executor, plan); + + var execution = Assert.IsType(error); + Assert.Equal(ExecutionErrorKind.IdentityMismatch, execution.Kind); + Assert.DoesNotContain(runner.Commands, c => c.IsDestructive); + } + + [Fact] + public async Task SystemDisk_IsRefusedBeforeAnyDestructiveCommand() + { + var (plan, runner) = HappyPathSetup(); + runner.RespondToScript("disk-info.ps1", DiskInfoJson(plan.Drive, isSystem: true)); + var executor = new OperationExecutor(runner, missingFiles: _ => []); + + var (_, error) = await Collect(executor, plan); + + var execution = Assert.IsType(error); + Assert.Equal(ExecutionErrorKind.RefusedSystemDisk, execution.Kind); + Assert.DoesNotContain(runner.Commands, c => c.IsDestructive); + } + + [Fact] + public async Task ValidationFailure_BlocksSuccessAndSkipsEject() + { + var (plan, runner) = HappyPathSetup(); + var executor = new OperationExecutor(runner, missingFiles: _ => [@"E:\sources\boot.wim"]); + + var (events, error) = await Collect(executor, plan); + + var execution = Assert.IsType(error); + Assert.Equal(ExecutionErrorKind.ValidationFailed, execution.Kind); + Assert.Contains(events, e => e.Id == "validate" && e.Status == ChecklistStatus.Failed); + Assert.DoesNotContain(runner.Commands, c => c.Arguments.Any(a => a.EndsWith("eject-disk.ps1"))); + } + + [Fact] + public async Task RobocopyInformationalExitCodesAreSuccess() + { + var (plan, runner) = HappyPathSetup(); + runner.RespondToExecutable("robocopy.exe", "", exitCode: 3); + var executor = new OperationExecutor(runner, missingFiles: _ => []); + + var (_, error) = await Collect(executor, plan); + Assert.Null(error); + } + + [Fact] + public async Task RobocopyFailureExitCodeAborts() + { + var (plan, runner) = HappyPathSetup(); + runner.RespondToExecutable("robocopy.exe", "", exitCode: 8); + var executor = new OperationExecutor(runner, missingFiles: _ => []); + + var (_, error) = await Collect(executor, plan); + + var execution = Assert.IsType(error); + Assert.Equal(ExecutionErrorKind.CommandFailed, execution.Kind); + } + + [Fact] + public async Task Simulation_CompletesWithoutRealCommands() + { + var engine = new BootableUsbEngine(); + var iso = TestFixtures.WindowsIso(engine); + var drive = TestFixtures.RemovableDrive(); + var plan = engine.MakePlan(iso, drive); + engine.ConfirmErase(drive, drive.DisplayName); + + var logger = new LocalLogger(Path.Combine(Path.GetTempPath(), $"winstaller-test-{Guid.NewGuid():N}")); + var executor = new OperationExecutor( + runner: new DryRunCommandRunner(plan, stepDelay: TimeSpan.FromMilliseconds(1)), + logger: logger, + missingFiles: _ => []); + + var (events, error) = await Collect(executor, plan); + + Assert.Null(error); + Assert.Contains(events, e => e.Id == "completed" && e.Status == ChecklistStatus.Complete); + Assert.NotEmpty(logger.AllEntries); + } + + [Fact] + public async Task Cancellation_StopsThePipeline() + { + var (plan, _) = HappyPathSetup(); + using var source = new CancellationTokenSource(); + var executor = new OperationExecutor( + runner: new DryRunCommandRunner(plan, stepDelay: TimeSpan.FromSeconds(30)), + missingFiles: _ => []); + + source.CancelAfter(TimeSpan.FromMilliseconds(50)); + var events = new List(); + Exception? error = null; + try + { + await foreach (var engineEvent in executor.Run(plan, source.Token)) + { + events.Add(engineEvent); + } + } + catch (Exception exception) + { + error = exception; + } + + var execution = Assert.IsType(error); + Assert.Equal(ExecutionErrorKind.Cancelled, execution.Kind); + Assert.DoesNotContain(events, e => e.Id == "completed"); + } +} diff --git a/apps/windows/WInstaller.Core.Tests/TestFixtures.cs b/apps/windows/WInstaller.Core.Tests/TestFixtures.cs new file mode 100644 index 0000000..24cbda7 --- /dev/null +++ b/apps/windows/WInstaller.Core.Tests/TestFixtures.cs @@ -0,0 +1,51 @@ +namespace WInstaller.Core.Tests; + +internal static class TestFixtures +{ + public static readonly string[] WindowsIsoEntries = + [ + "setup.exe", + "boot", + "efi", + "efi/boot", + "efi/boot/bootx64.efi", + "sources", + "sources/boot.wim", + "sources/install.wim", + ]; + + public static UsbDrive RemovableDrive(long size = 64_000_000_000) => new( + DiskNumber: 3, + DisplayName: "Kingston DataTraveler 3.0", + MediaName: "Kingston DataTraveler 3.0", + Size: size, + IsRemovable: true, + IsSystemDisk: false, + ConnectionType: "USB", + PartitionScheme: "MBR", + FileSystem: "exFAT", + Volumes: ["UNTITLED"]); + + public static UsbDrive SystemDrive() => new( + DiskNumber: 0, + DisplayName: "Samsung SSD 980", + MediaName: "Samsung SSD 980", + Size: 1_000_000_000_000, + IsRemovable: false, + IsSystemDisk: true, + ConnectionType: "NVMe", + PartitionScheme: "GPT", + FileSystem: "NTFS", + Volumes: ["Windows"]); + + public static InstallerIso WindowsIso(BootableUsbEngine? engine = null, long installWimSize = 3_800_000_000) + { + engine ??= new BootableUsbEngine(); + return engine.AnalyzeIso( + path: @"C:\Users\example\Downloads\Win11_English_x64.iso", + size: 6_500_000_000, + volumeLabel: "CCCOMA_X64FRE", + directoryEntries: WindowsIsoEntries, + fileSizes: new Dictionary { ["sources/install.wim"] = installWimSize }); + } +} diff --git a/apps/windows/WInstaller.Core.Tests/WInstaller.Core.Tests.csproj b/apps/windows/WInstaller.Core.Tests/WInstaller.Core.Tests.csproj new file mode 100644 index 0000000..d437cf3 --- /dev/null +++ b/apps/windows/WInstaller.Core.Tests/WInstaller.Core.Tests.csproj @@ -0,0 +1,20 @@ + + + + net8.0 + enable + enable + false + + + + + + + + + + + + + diff --git a/apps/windows/WInstaller.Core/BootableUsbEngine.cs b/apps/windows/WInstaller.Core/BootableUsbEngine.cs new file mode 100644 index 0000000..e86e3ff --- /dev/null +++ b/apps/windows/WInstaller.Core/BootableUsbEngine.cs @@ -0,0 +1,275 @@ +namespace WInstaller.Core; + +/// +/// The typed state machine behind the assistant flow (BOOTABLE_USB_ENGINE.md). +/// Pure logic only: analysis and planning never touch a real disk, so every +/// safety gate is unit-testable. This is the Windows-native port of the macOS +/// BootableUSBEngine; the OS-specific commands it plans differ, the +/// detection logic and safety rules do not. +/// +public sealed class BootableUsbEngine +{ + public EngineState State { get; private set; } = EngineState.Idle; + + public void Reset() => State = EngineState.Idle; + + /// + /// Classifies an ISO from its directory listing. Detection is marker-based: + /// Windows media must expose setup.exe / boot.wim / install.wim|esd / + /// bootx64.efi; Linux media is recognized by its boot loaders and metadata. + /// + public InstallerIso AnalyzeIso( + string path, + long size, + string? volumeLabel, + IReadOnlyList directoryEntries, + IReadOnlyDictionary fileSizes) + { + State = EngineState.AnalyzingIso; + + var normalized = directoryEntries.Select(Normalize).ToHashSet(); + var bootFiles = normalized + .Where(p => p.Contains("boot") || p.Contains("efi") || p.Contains("isolinux") || p.Contains("syslinux")) + .OrderBy(p => p, StringComparer.Ordinal) + .ToList(); + + string[] windowsMarkers = + [ + "setup.exe", + "sources/boot.wim", + "sources/install.wim", + "sources/install.esd", + "efi/boot/bootx64.efi", + ]; + var windowsMatches = windowsMarkers.Count(normalized.Contains); + + string[] linuxMarkers = ["efi", "isolinux", "syslinux", "casper", ".disk/info"]; + var hasLinuxMarkers = linuxMarkers.Any(marker => + normalized.Contains(marker) || normalized.Any(entry => entry.StartsWith(marker + "/", StringComparison.Ordinal))); + + DetectedOperatingSystem detectedOs; + DetectionConfidence confidence; + WindowsImageInfo? windowsImageInfo; + + if (windowsMatches >= 3) + { + detectedOs = DetectedOperatingSystem.Windows(); + confidence = windowsMatches >= 4 ? DetectionConfidence.High : DetectionConfidence.Medium; + long? wimSize = fileSizes.TryGetValue("sources/install.wim", out var natural) + ? natural + : fileSizes.TryGetValue("SOURCES/INSTALL.WIM", out var upper) ? upper : null; + windowsImageInfo = new WindowsImageInfo(wimSize, normalized.Contains("sources/install.esd")); + } + else if (hasLinuxMarkers) + { + detectedOs = DetectedOperatingSystem.Linux(volumeLabel); + confidence = DetectionConfidence.Medium; + windowsImageInfo = null; + } + else + { + detectedOs = DetectedOperatingSystem.Unknown; + confidence = DetectionConfidence.Low; + windowsImageInfo = null; + } + + var iso = new InstallerIso( + Path: path, + DisplayName: System.IO.Path.GetFileName(path), + Size: size, + VolumeLabel: volumeLabel, + DetectedOs: detectedOs, + Confidence: confidence, + BootFiles: bootFiles, + WindowsImageInfo: windowsImageInfo); + + if (confidence == DetectionConfidence.Low) + { + State = EngineState.Failed; + throw new BootableUsbException(UsbErrorKind.UnsupportedIso); + } + + State = EngineState.WaitingForUsb; + return iso; + } + + /// + /// Builds the full operation plan and enforces every pre-flight safety gate. + /// Planned commands are argv arrays (never shell strings) and destructive + /// steps are marked explicitly (TERMINAL_AUTOMATION.md). + /// + public OperationPlan MakePlan(InstallerIso iso, UsbDrive drive, ToolAvailability? tools = null) + { + tools ??= new ToolAvailability(); + State = EngineState.Planning; + + if (!drive.IsRemovable) + { + State = EngineState.Failed; + throw new BootableUsbException(UsbErrorKind.DiskNotRemovable); + } + if (drive.IsSystemDisk) + { + State = EngineState.Failed; + throw new BootableUsbException(UsbErrorKind.DiskIsSystem); + } + if (drive.Size < iso.Size) + { + State = EngineState.Failed; + throw new BootableUsbException(UsbErrorKind.InsufficientCapacity); + } + if (!tools.PowerShell) + { + State = EngineState.Failed; + throw new BootableUsbException(UsbErrorKind.MissingTool, "powershell.exe"); + } + if (!tools.Robocopy) + { + State = EngineState.Failed; + throw new BootableUsbException(UsbErrorKind.MissingTool, "robocopy.exe"); + } + + var requiresWimSplit = iso.WindowsImageInfo?.RequiresSplit == true; + if (requiresWimSplit && !tools.Dism) + { + State = EngineState.Failed; + throw new BootableUsbException(UsbErrorKind.MissingTool, "dism.exe"); + } + + var strategy = new BootStrategy( + TargetPartitionScheme: "GPT", + TargetFileSystem: "FAT32", + RequiresErase: true, + RequiresWimSplit: requiresWimSplit, + Warnings: StrategyWarnings(iso, drive, requiresWimSplit)); + + var diskNumber = drive.DiskNumber.ToString(System.Globalization.CultureInfo.InvariantCulture); + var steps = new List + { + new( + "mount-iso", "Mount ISO read-only", "Inspect the installer without modifying it.", + OperationKind.AnalyzeIso, + WindowsCommands.Script("mount-iso.ps1", ["-IsoPath", iso.Path], isDestructive: false)), + new( + "verify-usb", "Re-check USB identity", $"Confirm {drive.DisplayName} is still {drive.Identifier}.", + OperationKind.VerifyUsb, + WindowsCommands.Script("disk-info.ps1", ["-DiskNumber", diskNumber], isDestructive: false)), + new( + "prepare-usb", "Erase and format USB drive", "Clean the disk, create a GPT/FAT32 installer volume.", + OperationKind.EraseDisk, + WindowsCommands.Script( + "prepare-usb.ps1", + ["-DiskNumber", diskNumber, "-Label", OperationExecutor.TargetVolumeLabel], + isDestructive: true, + requiresElevation: true)), + new( + "copy-files", "Copy installer files", "Preserve the ISO directory structure on the target volume.", + OperationKind.CopyFiles, + new PlannedCommand( + WindowsCommands.SystemExecutable("robocopy.exe"), + ["", "", "/E"], + IsDestructive: false)), + }; + + if (requiresWimSplit) + { + steps.Add(new( + "split-wim", "Split oversized Windows image", "Create setup-compatible SWM parts below the FAT32 file limit.", + OperationKind.SplitWim, + WindowsCommands.Script( + "split-wim.ps1", + ["-ImageFile", @"\sources\install.wim", "-SwmFile", @"\sources\install.swm", "-PartSizeMB", "3800"], + isDestructive: false, + requiresElevation: true))); + } + + steps.Add(new( + "validate", "Validate boot files", "Check required boot folders and Windows source files.", + OperationKind.ValidateBootFiles, Command: null)); + steps.Add(new( + "eject", "Eject USB safely", "Finish only after Windows releases the drive.", + OperationKind.EjectDisk, + WindowsCommands.Script("eject-disk.ps1", ["-DriveLetter", ""], isDestructive: false))); + + State = EngineState.AwaitingEraseConfirmation; + + return new OperationPlan( + Iso: iso, + Drive: drive, + Strategy: strategy, + Steps: steps, + RequiresAuthorization: true, + EstimatedBytesToCopy: iso.Size, + ValidationChecks: ValidationChecks(iso)); + } + + /// The high-friction gate: the typed name must match the drive exactly. + public void ConfirmErase(UsbDrive drive, string typedName) + { + if (State != EngineState.AwaitingEraseConfirmation) + { + throw new BootableUsbException(UsbErrorKind.InvalidState); + } + if (!string.Equals(typedName, drive.DisplayName, StringComparison.Ordinal)) + { + throw new BootableUsbException(UsbErrorKind.ConfirmationMismatch); + } + State = EngineState.PreparingDrive; + } + + public IReadOnlyList DryRunEvents(OperationPlan plan) + { + var events = new List + { + new("iso", EngineState.AnalyzingIso, "ISO verified", plan.Iso.DetectedOs.DisplayName, ChecklistStatus.Complete), + new("usb", EngineState.AnalyzingUsb, "USB selected", $"{plan.Drive.DisplayName} ({plan.Drive.Identifier})", ChecklistStatus.Complete), + new("erase", EngineState.PreparingDrive, "USB erase planned", "Requires explicit confirmation before execution.", ChecklistStatus.Waiting), + new("copy", EngineState.CopyingFiles, "Files ready to copy", ByteFormat.Bytes(plan.EstimatedBytesToCopy), ChecklistStatus.Waiting), + }; + + if (plan.Strategy.RequiresWimSplit) + { + events.Add(new("wim", EngineState.SplittingWim, "WIM split required", "DISM will create SWM parts.", ChecklistStatus.Waiting)); + } + + events.Add(new("validate", EngineState.Validating, "Boot validation planned", string.Join(", ", plan.ValidationChecks), ChecklistStatus.Waiting)); + events.Add(new("eject", EngineState.Ejecting, "Safe eject planned", plan.Drive.Identifier, ChecklistStatus.Waiting)); + + return events; + } + + private static IReadOnlyList StrategyWarnings(InstallerIso iso, UsbDrive drive, bool requiresWimSplit) + { + var warnings = new List(); + if (!string.Equals(drive.FileSystem, "FAT32", StringComparison.OrdinalIgnoreCase)) + { + warnings.Add("The USB drive will be reformatted as FAT32 for UEFI boot compatibility."); + } + if (drive.Size > OperationExecutor.MaxFat32PartitionBytes) + { + warnings.Add("Windows formats FAT32 volumes up to 32 GB, so a 32 GB installer partition will be created and the rest left unallocated."); + } + if (requiresWimSplit) + { + warnings.Add("The Windows image is larger than FAT32 allows and must be split."); + } + if (iso.Confidence == DetectionConfidence.Medium) + { + warnings.Add("ISO detection confidence is medium; validation must pass before success."); + } + return warnings; + } + + private static IReadOnlyList ValidationChecks(InstallerIso iso) => iso.DetectedOs.Kind switch + { + OperatingSystemKind.Windows when iso.WindowsImageInfo?.RequiresSplit == true => + ["boot directory", "efi directory", @"sources\boot.wim", @"sources\install.swm"], + OperatingSystemKind.Windows => + ["boot directory", "efi directory", @"sources\boot.wim", @"sources\install.wim or install.esd"], + OperatingSystemKind.Linux => ["EFI or boot directory", "copy completed", "safe eject"], + _ => ["copy completed", "safe eject"], + }; + + private static string Normalize(string path) => + path.Replace('\\', '/').Trim('/').ToLowerInvariant(); +} diff --git a/apps/windows/WInstaller.Core/CommandRunner.cs b/apps/windows/WInstaller.Core/CommandRunner.cs new file mode 100644 index 0000000..1e728c8 --- /dev/null +++ b/apps/windows/WInstaller.Core/CommandRunner.cs @@ -0,0 +1,214 @@ +using System.Diagnostics; + +namespace WInstaller.Core; + +/// +/// The result of running a single command. Command output is treated as +/// untrusted input (TERMINAL_AUTOMATION.md): callers parse it defensively and +/// never evaluate it as code. +/// +public sealed record CommandResult( + string Executable, + IReadOnlyList Arguments, + string StandardOutput, + string StandardError, + int ExitCode, + DateTimeOffset StartedAt, + DateTimeOffset FinishedAt) +{ + public bool Succeeded => ExitCode == 0; +} + +/// Timeout classes recommended by TERMINAL_AUTOMATION.md. +public readonly struct CommandTimeout +{ + public TimeSpan? Interval { get; } + + private CommandTimeout(TimeSpan? interval) => Interval = interval; + + /// Fast metadata query (generous enough for PowerShell startup). + public static readonly CommandTimeout Metadata = new(TimeSpan.FromSeconds(30)); + /// Mount / unmount an image. + public static readonly CommandTimeout Mount = new(TimeSpan.FromSeconds(90)); + /// Clean + format a removable disk. + public static readonly CommandTimeout Format = new(TimeSpan.FromSeconds(300)); + /// Eject a volume. + public static readonly CommandTimeout Eject = new(TimeSpan.FromSeconds(60)); + /// Long-running work watched by progress rather than a hard timeout. + public static readonly CommandTimeout Watched = new(null); + + public static CommandTimeout Seconds(double seconds) => new(TimeSpan.FromSeconds(seconds)); +} + +public enum CommandRunnerErrorKind +{ + LaunchFailed, + TimedOut, + ElevationDeclined, + Cancelled, +} + +public sealed class CommandRunnerException : Exception +{ + public CommandRunnerErrorKind Kind { get; } + + public CommandRunnerException(CommandRunnerErrorKind kind, string message) + : base(message) + { + Kind = kind; + } +} + +/// +/// Abstraction over command execution so the whole pipeline stays testable +/// without touching a real disk. Commands are always an executable plus an +/// argument array — never a shell-interpolated string. +/// +public interface ICommandRunner +{ + Task RunAsync(PlannedCommand command, CommandTimeout timeout, CancellationToken cancellationToken = default); +} + +/// Well-known executable and helper-script locations. +public static class WindowsCommands +{ + /// + /// Absolute path of a tool under System32 (falls back to the bare name off + /// the Windows system directory, e.g. in unit tests on other OSes). + /// + public static string SystemExecutable(string name) + { + var system = Environment.GetFolderPath(Environment.SpecialFolder.System); + return string.IsNullOrEmpty(system) ? name : Path.Combine(system, name); + } + + /// Windows PowerShell 5.1, present on every supported Windows install. + public static string PowerShell => SystemExecutable(Path.Combine("WindowsPowerShell", "v1.0", "powershell.exe")); + + /// Directory holding the bundled .ps1 helpers, next to the app binaries. + public static string ScriptsDirectory => Path.Combine(AppContext.BaseDirectory, "Scripts"); + + /// + /// Builds an argv-only PowerShell invocation of a bundled helper script. + /// Parameters are passed as separate argv entries, never interpolated into + /// a command string. + /// + public static PlannedCommand Script( + string scriptName, + IReadOnlyList parameters, + bool isDestructive, + bool requiresElevation = false) + { + var arguments = new List + { + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", "Bypass", + "-File", Path.Combine(ScriptsDirectory, scriptName), + }; + arguments.AddRange(parameters); + return new PlannedCommand(PowerShell, arguments, isDestructive, requiresElevation); + } +} + +/// +/// Runs real processes. Non-elevated commands are captured via redirected +/// stdout/stderr. Elevated commands (ADR-0003: a single UAC prompt scoped to +/// the destructive step, never the whole app) run through ShellExecute +/// "runas", which cannot redirect output — those scripts report their result +/// through a caller-provided result file instead. +/// +public sealed class ProcessCommandRunner : ICommandRunner +{ + public async Task RunAsync(PlannedCommand command, CommandTimeout timeout, CancellationToken cancellationToken = default) + { + var startedAt = DateTimeOffset.Now; + var info = new ProcessStartInfo + { + FileName = command.Executable, + UseShellExecute = command.RequiresElevation, + CreateNoWindow = true, + RedirectStandardOutput = !command.RequiresElevation, + RedirectStandardError = !command.RequiresElevation, + }; + if (command.RequiresElevation) + { + info.Verb = "runas"; + info.WindowStyle = ProcessWindowStyle.Hidden; + } + foreach (var argument in command.Arguments) + { + info.ArgumentList.Add(argument); + } + + Process process; + try + { + process = Process.Start(info) ?? throw new CommandRunnerException( + CommandRunnerErrorKind.LaunchFailed, $"Could not start {command.Executable}."); + } + catch (System.ComponentModel.Win32Exception exception) when (exception.NativeErrorCode == 1223) + { + // ERROR_CANCELLED: the user declined the UAC prompt. + throw new CommandRunnerException( + CommandRunnerErrorKind.ElevationDeclined, + "The administrator prompt was declined, so the drive was not modified."); + } + catch (Exception exception) when (exception is not CommandRunnerException) + { + throw new CommandRunnerException(CommandRunnerErrorKind.LaunchFailed, exception.Message); + } + + using (process) + { + var stdoutTask = command.RequiresElevation + ? Task.FromResult(string.Empty) + : process.StandardOutput.ReadToEndAsync(cancellationToken); + var stderrTask = command.RequiresElevation + ? Task.FromResult(string.Empty) + : process.StandardError.ReadToEndAsync(cancellationToken); + + using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + if (timeout.Interval is { } interval) + { + timeoutSource.CancelAfter(interval); + } + + try + { + await process.WaitForExitAsync(timeoutSource.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + try + { + process.Kill(entireProcessTree: true); + } + catch + { + // The process may have exited between the timeout and the kill. + } + + if (cancellationToken.IsCancellationRequested) + { + throw new OperationCanceledException(cancellationToken); + } + throw new CommandRunnerException( + CommandRunnerErrorKind.TimedOut, + $"{Path.GetFileName(command.Executable)} did not finish within {timeout.Interval?.TotalSeconds:0} seconds."); + } + + var standardOutput = await stdoutTask.ConfigureAwait(false); + var standardError = await stderrTask.ConfigureAwait(false); + + return new CommandResult( + command.Executable, + command.Arguments, + standardOutput, + standardError, + process.ExitCode, + startedAt, + DateTimeOffset.Now); + } + } +} diff --git a/apps/windows/WInstaller.Core/DiskEnumerator.cs b/apps/windows/WInstaller.Core/DiskEnumerator.cs new file mode 100644 index 0000000..50947ab --- /dev/null +++ b/apps/windows/WInstaller.Core/DiskEnumerator.cs @@ -0,0 +1,167 @@ +using System.Text.Json; + +namespace WInstaller.Core; + +/// +/// Enumerates physical disks through the bundled list-disks.ps1 / +/// disk-info.ps1 helpers (Get-Disk + Get-Partition as JSON) and maps +/// them onto the domain model. System/boot disks are +/// marked unsafe for erase and filtered out by default (REQ-USB-002, +/// REQ-USB-005). +/// +/// All parsing is exposed as pure static functions so it can be fixture-tested +/// without a real disk. +/// +public sealed class DiskEnumerator +{ + private readonly ICommandRunner _runner; + + public DiskEnumerator(ICommandRunner? runner = null) + { + _runner = runner ?? new ProcessCommandRunner(); + } + + /// Removable, non-system drives that are safe to consider as erase targets. + public async Task> RemovableDrivesAsync(CancellationToken cancellationToken = default) + { + var result = await _runner.RunAsync( + WindowsCommands.Script("list-disks.ps1", [], isDestructive: false), + CommandTimeout.Metadata, + cancellationToken).ConfigureAwait(false); + + if (!result.Succeeded) + { + return []; + } + + return ParseDiskList(result.StandardOutput) + .Where(drive => drive.IsRemovable && !drive.IsSystemDisk) + .ToList(); + } + + /// + /// Re-reads a single disk's identity immediately before a destructive step. + /// Used by to abort if the device changed. + /// + public async Task InfoAsync(int diskNumber, CancellationToken cancellationToken = default) + { + var result = await _runner.RunAsync( + WindowsCommands.Script( + "disk-info.ps1", + ["-DiskNumber", diskNumber.ToString(System.Globalization.CultureInfo.InvariantCulture)], + isDestructive: false), + CommandTimeout.Metadata, + cancellationToken).ConfigureAwait(false); + + if (!result.Succeeded) + { + throw new CommandRunnerException( + CommandRunnerErrorKind.LaunchFailed, + $"Could not re-read disk {diskNumber}: {result.StandardError}"); + } + + return ParseDriveInfo(result.StandardOutput); + } + + // MARK: Pure parsing + + /// Parses the JSON array produced by list-disks.ps1. + public static IReadOnlyList ParseDiskList(string json) + { + using var document = JsonDocument.Parse(json); + var root = document.RootElement; + + // ConvertTo-Json collapses single-element arrays to a bare object. + if (root.ValueKind == JsonValueKind.Object) + { + return [ParseDisk(root)]; + } + if (root.ValueKind != JsonValueKind.Array) + { + return []; + } + return root.EnumerateArray().Select(ParseDisk).ToList(); + } + + /// Parses the single JSON object produced by disk-info.ps1. + public static UsbDrive ParseDriveInfo(string json) + { + using var document = JsonDocument.Parse(json); + return ParseDisk(document.RootElement); + } + + private static UsbDrive ParseDisk(JsonElement element) + { + var busType = GetString(element, "BusType") ?? "Unknown"; + var isRemovableMedia = GetBool(element, "IsRemovableMedia"); + var isBoot = GetBool(element, "IsBoot"); + var isSystem = GetBool(element, "IsSystem"); + + var volumes = new List(); + string? fileSystem = null; + if (element.TryGetProperty("Volumes", out var volumesElement) && volumesElement.ValueKind == JsonValueKind.Array) + { + foreach (var volume in volumesElement.EnumerateArray()) + { + var label = GetString(volume, "FileSystemLabel"); + var letter = GetString(volume, "DriveLetter"); + fileSystem ??= GetString(volume, "FileSystem"); + var name = !string.IsNullOrWhiteSpace(label) ? label! + : !string.IsNullOrWhiteSpace(letter) ? $"{letter}:" : null; + if (name is not null) + { + volumes.Add(name); + } + } + } + + var friendlyName = FirstNonEmpty( + GetString(element, "FriendlyName"), + GetString(element, "Model")); + var diskNumber = GetInt(element, "Number") ?? -1; + + return new UsbDrive( + DiskNumber: diskNumber, + DisplayName: friendlyName ?? $"Disk {diskNumber}", + MediaName: friendlyName ?? $"Disk {diskNumber}", + Size: GetLong(element, "Size") ?? 0, + // The Windows storage stack reports USB thumb drives as + // BusType=USB; card readers additionally set IsRemovableMedia. + IsRemovable: string.Equals(busType, "USB", StringComparison.OrdinalIgnoreCase) || isRemovableMedia, + IsSystemDisk: isBoot || isSystem, + ConnectionType: busType, + PartitionScheme: PartitionScheme(GetString(element, "PartitionStyle")), + FileSystem: FirstNonEmpty(fileSystem) ?? "Unformatted", + Volumes: volumes); + } + + internal static string PartitionScheme(string? style) => style switch + { + "GPT" => "GPT", + "MBR" => "MBR", + "RAW" => "Unformatted", + var value when !string.IsNullOrWhiteSpace(value) => value!, + _ => "Unknown", + }; + + private static string? FirstNonEmpty(params string?[] values) => + values.FirstOrDefault(value => !string.IsNullOrWhiteSpace(value)); + + private static string? GetString(JsonElement element, string name) => + element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String + ? value.GetString() + : null; + + private static bool GetBool(JsonElement element, string name) => + element.TryGetProperty(name, out var value) && value.ValueKind is JsonValueKind.True; + + private static int? GetInt(JsonElement element, string name) => + element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number + ? value.GetInt32() + : null; + + private static long? GetLong(JsonElement element, string name) => + element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number + ? value.GetInt64() + : null; +} diff --git a/apps/windows/WInstaller.Core/IsoInspector.cs b/apps/windows/WInstaller.Core/IsoInspector.cs new file mode 100644 index 0000000..8fc53ad --- /dev/null +++ b/apps/windows/WInstaller.Core/IsoInspector.cs @@ -0,0 +1,187 @@ +using System.Text.Json; + +namespace WInstaller.Core; + +public enum IsoInspectionErrorKind +{ + MountFailed, + NoMountPoint, +} + +public sealed class IsoInspectionException : Exception +{ + public IsoInspectionErrorKind Kind { get; } + + public IsoInspectionException(IsoInspectionErrorKind kind, string? detail = null) + : base(detail ?? "") + { + Kind = kind; + } + + public string UserMessage => Kind switch + { + IsoInspectionErrorKind.MountFailed => "wInstaller could not mount this ISO. It may be damaged or unsupported.", + _ => "The ISO mounted but no readable volume was found.", + }; +} + +/// +/// Mounts an ISO read-only through mount-iso.ps1 (Mount-DiskImage +/// -Access ReadOnly), walks its directory tree to gather the entries and file +/// sizes that needs, then dismounts +/// the image. The image is never modified (REQ-ISO-003, REQ-ISO-007). +/// +public sealed class IsoInspector +{ + private readonly ICommandRunner _runner; + private readonly BootableUsbEngine _engine; + + public IsoInspector(ICommandRunner? runner = null, BootableUsbEngine? engine = null) + { + _runner = runner ?? new ProcessCommandRunner(); + _engine = engine ?? new BootableUsbEngine(); + } + + public async Task InspectAsync(string isoPath, CancellationToken cancellationToken = default) + { + var mountResult = await _runner.RunAsync( + WindowsCommands.Script("mount-iso.ps1", ["-IsoPath", isoPath], isDestructive: false), + CommandTimeout.Mount, + cancellationToken).ConfigureAwait(false); + + if (!mountResult.Succeeded) + { + throw new IsoInspectionException(IsoInspectionErrorKind.MountFailed, mountResult.StandardError); + } + + var mount = ParseMount(mountResult.StandardOutput); + if (string.IsNullOrEmpty(mount.DriveLetter)) + { + await DismountAsync(isoPath, cancellationToken).ConfigureAwait(false); + throw new IsoInspectionException(IsoInspectionErrorKind.NoMountPoint); + } + + try + { + var mountRoot = $"{mount.DriveLetter}:{Path.DirectorySeparatorChar}"; + var scan = Scan(mountRoot); + var size = FileSize(isoPath); + return _engine.AnalyzeIso( + path: isoPath, + size: size, + volumeLabel: mount.VolumeLabel, + directoryEntries: scan.Entries, + fileSizes: scan.FileSizes); + } + finally + { + // Always dismount, whether analysis succeeds or throws + // (e.g. unsupported ISO). + await DismountAsync(isoPath, cancellationToken).ConfigureAwait(false); + } + } + + private async Task DismountAsync(string isoPath, CancellationToken cancellationToken) + { + try + { + await _runner.RunAsync( + WindowsCommands.Script("dismount-iso.ps1", ["-IsoPath", isoPath], isDestructive: false), + CommandTimeout.Mount, + cancellationToken).ConfigureAwait(false); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + // Best-effort cleanup; the mount is read-only either way. + } + } + + private static long FileSize(string path) + { + try + { + return new FileInfo(path).Length; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return 0; + } + } + + // MARK: Pure parsing / scanning + + public sealed record MountInfo(string? DriveLetter, string? VolumeLabel); + + /// Extracts the mounted volume from mount-iso.ps1 JSON output. + public static MountInfo ParseMount(string json) + { + using var document = JsonDocument.Parse(json); + var root = document.RootElement; + string? letter = null; + string? label = null; + if (root.TryGetProperty("DriveLetter", out var letterElement) && letterElement.ValueKind == JsonValueKind.String) + { + letter = letterElement.GetString(); + } + if (root.TryGetProperty("VolumeLabel", out var labelElement) && labelElement.ValueKind == JsonValueKind.String) + { + label = labelElement.GetString(); + } + return new MountInfo(string.IsNullOrWhiteSpace(letter) ? null : letter, label); + } + + public sealed record ScanResult(IReadOnlyList Entries, IReadOnlyDictionary FileSizes); + + /// + /// Walks a mounted volume and returns relative paths (normalized to forward + /// slashes) plus file sizes. Sizes are recorded under both the natural-case + /// and lowercased relative path so the engine's lookups resolve on any ISO + /// layout. Hidden files are included: Linux media is detected via + /// .disk/info. + /// + public static ScanResult Scan(string mountRoot) + { + var entries = new List(); + var fileSizes = new Dictionary(); + + var root = new DirectoryInfo(mountRoot); + if (!root.Exists) + { + return new ScanResult(entries, fileSizes); + } + + var basePath = root.FullName.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + var options = new EnumerationOptions + { + RecurseSubdirectories = true, + AttributesToSkip = 0, + IgnoreInaccessible = true, + }; + + foreach (var info in root.EnumerateFileSystemInfos("*", options)) + { + var fullPath = info.FullName; + if (!fullPath.StartsWith(basePath, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + var relative = fullPath[basePath.Length..] + .TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + .Replace('\\', '/'); + if (relative.Length == 0) + { + continue; + } + + entries.Add(relative); + + if (info is FileInfo file) + { + fileSizes[relative] = file.Length; + fileSizes[relative.ToLowerInvariant()] = file.Length; + } + } + + return new ScanResult(entries, fileSizes); + } +} diff --git a/apps/windows/WInstaller.Core/LocalLogger.cs b/apps/windows/WInstaller.Core/LocalLogger.cs new file mode 100644 index 0000000..e27888f --- /dev/null +++ b/apps/windows/WInstaller.Core/LocalLogger.cs @@ -0,0 +1,126 @@ +using System.Text.RegularExpressions; + +namespace WInstaller.Core; + +/// +/// A single local log entry. No ISO contents, license keys, or unrelated disk +/// contents are ever recorded (TERMINAL_AUTOMATION.md logging rules). +/// +public sealed record LogEntry( + string OperationId, + string Tool, + IReadOnlyList Arguments, + int? ExitCode, + string UserMessage, + string? TechnicalDetail = null) +{ + public DateTimeOffset Timestamp { get; init; } = DateTimeOffset.Now; +} + +/// +/// Local-only logging (REQ-LOG-001..004). Logs are stored under Local AppData +/// and can be exported with user-profile paths redacted. +/// +public sealed class LocalLogger +{ + private readonly object _lock = new(); + private readonly string? _filePath; + private readonly List _entries = []; + + public LocalLogger(string? directory = null) + { + var baseDirectory = directory ?? DefaultDirectory(); + if (baseDirectory is not null) + { + try + { + Directory.CreateDirectory(baseDirectory); + _filePath = Path.Combine(baseDirectory, "winstaller.log"); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + _filePath = null; + } + } + } + + public void Record(LogEntry entry) + { + lock (_lock) + { + _entries.Add(entry); + Persist(); + } + } + + public IReadOnlyList AllEntries + { + get + { + lock (_lock) + { + return _entries.ToList(); + } + } + } + + /// A redacted, human-readable transcript suitable for support bundles. + public string ExportText() + { + lock (_lock) + { + return string.Join("\n", _entries.Select(Format)); + } + } + + private void Persist() + { + if (_filePath is null) + { + return; + } + try + { + File.WriteAllText(_filePath, string.Join("\n", _entries.Select(Format))); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // Logging must never take the pipeline down. + } + } + + public static string Format(LogEntry entry) + { + var time = entry.Timestamp.ToString("yyyy-MM-dd'T'HH:mm:ssK", System.Globalization.CultureInfo.InvariantCulture); + var args = Redact(string.Join(" ", entry.Arguments)); + var exit = entry.ExitCode is { } code ? $" exit={code}" : ""; + var line = $"[{time}] {entry.OperationId} {entry.Tool} {args}{exit} — {entry.UserMessage}"; + if (!string.IsNullOrEmpty(entry.TechnicalDetail)) + { + line += "\n " + Redact(entry.TechnicalDetail!).Replace("\n", "\n "); + } + return line; + } + + private static readonly Regex UsersPathPattern = new( + @"(?i)([a-z]):[\\/]users[\\/][^\\/\s]+", + RegexOptions.Compiled); + + /// Redacts the current user's profile directory and any C:\Users\name path. + public static string Redact(string text) + { + var result = text; + var profile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + if (!string.IsNullOrEmpty(profile)) + { + result = result.Replace(profile, "~"); + } + return UsersPathPattern.Replace(result, @"$1:\Users\"); + } + + private static string? DefaultDirectory() + { + var appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + return string.IsNullOrEmpty(appData) ? null : Path.Combine(appData, "wInstaller", "logs"); + } +} diff --git a/apps/windows/WInstaller.Core/Models.cs b/apps/windows/WInstaller.Core/Models.cs new file mode 100644 index 0000000..87fc38b --- /dev/null +++ b/apps/windows/WInstaller.Core/Models.cs @@ -0,0 +1,213 @@ +namespace WInstaller.Core; + +public enum OperatingSystemKind +{ + Windows, + Linux, + Unknown, +} + +/// The operating system detected inside an installer ISO. +public sealed record DetectedOperatingSystem(OperatingSystemKind Kind, string? Detail) +{ + public static DetectedOperatingSystem Windows(string? version = null) => new(OperatingSystemKind.Windows, version); + public static DetectedOperatingSystem Linux(string? distribution = null) => new(OperatingSystemKind.Linux, distribution); + public static readonly DetectedOperatingSystem Unknown = new(OperatingSystemKind.Unknown, null); + + public string DisplayName => Kind switch + { + OperatingSystemKind.Windows when !string.IsNullOrEmpty(Detail) => $"Windows {Detail}", + OperatingSystemKind.Windows => "Windows installer", + OperatingSystemKind.Linux when !string.IsNullOrEmpty(Detail) => Detail!, + OperatingSystemKind.Linux => "Linux installer", + _ => "Unknown installer", + }; +} + +public enum DetectionConfidence +{ + Low = 0, + Medium = 1, + High = 2, +} + +public sealed record WindowsImageInfo(long? InstallWimSize, bool HasInstallEsd) +{ + /// FAT32 cannot store a file of 4 GiB or larger. + public const long Fat32SingleFileLimit = 4_294_967_295; + + public bool RequiresSplit => InstallWimSize is > Fat32SingleFileLimit; +} + +public sealed record InstallerIso( + string Path, + string DisplayName, + long Size, + string? VolumeLabel, + DetectedOperatingSystem DetectedOs, + DetectionConfidence Confidence, + IReadOnlyList BootFiles, + WindowsImageInfo? WindowsImageInfo); + +/// +/// A physical disk as surfaced by the Windows storage stack (Get-Disk). +/// mirrors the macOS "internal" concept: a disk that +/// hosts the boot or system volumes and must never be offered as an erase target. +/// +public sealed record UsbDrive( + int DiskNumber, + string DisplayName, + string MediaName, + long Size, + bool IsRemovable, + bool IsSystemDisk, + string ConnectionType, + string PartitionScheme, + string FileSystem, + IReadOnlyList Volumes) +{ + /// Stable identifier shown to the user next to the friendly name. + public string Identifier => $"Disk {DiskNumber}"; +} + +public enum EngineState +{ + Idle, + AnalyzingIso, + WaitingForUsb, + AnalyzingUsb, + Planning, + AwaitingEraseConfirmation, + PreparingDrive, + CopyingFiles, + SplittingWim, + Validating, + Ejecting, + Completed, + Failed, + Cancelled, +} + +public enum UsbErrorKind +{ + UnsupportedIso, + DiskNotRemovable, + DiskIsSystem, + InsufficientCapacity, + MissingTool, + ConfirmationMismatch, + InvalidState, +} + +public sealed class BootableUsbException : Exception +{ + public UsbErrorKind Kind { get; } + + public BootableUsbException(UsbErrorKind kind, string? detail = null) + : base(detail ?? UserMessageFor(kind, detail)) + { + Kind = kind; + } + + public string UserMessage => UserMessageFor(Kind, Message); + + private static string UserMessageFor(UsbErrorKind kind, string? detail) => kind switch + { + UsbErrorKind.UnsupportedIso => "wInstaller could not identify this ISO as supported installation media.", + UsbErrorKind.DiskNotRemovable => "The selected drive is not marked as removable.", + UsbErrorKind.DiskIsSystem => "wInstaller refuses to erase the Windows system disk or any internal disk.", + UsbErrorKind.InsufficientCapacity => "The selected USB drive does not have enough capacity.", + UsbErrorKind.MissingTool => $"A required tool is not available: {detail}.", + UsbErrorKind.ConfirmationMismatch => "The confirmation does not match the selected drive.", + UsbErrorKind.InvalidState => "The operation cannot continue from the current state.", + _ => "An unexpected error occurred.", + }; +} + +public enum OperationKind +{ + AnalyzeIso, + VerifyUsb, + EraseDisk, + CopyFiles, + SplitWim, + ValidateBootFiles, + EjectDisk, +} + +public sealed record PlannedCommand( + string Executable, + IReadOnlyList Arguments, + bool IsDestructive, + bool RequiresElevation = false); + +public sealed record OperationStep( + string Id, + string Title, + string Detail, + OperationKind Kind, + PlannedCommand? Command); + +public sealed record BootStrategy( + string TargetPartitionScheme, + string TargetFileSystem, + bool RequiresErase, + bool RequiresWimSplit, + IReadOnlyList Warnings); + +public sealed record OperationPlan( + InstallerIso Iso, + UsbDrive Drive, + BootStrategy Strategy, + IReadOnlyList Steps, + bool RequiresAuthorization, + long EstimatedBytesToCopy, + IReadOnlyList ValidationChecks) +{ + public IReadOnlyList DestructiveSteps => + Steps.Where(step => step.Command?.IsDestructive == true).ToList(); +} + +public enum ChecklistStatus +{ + Waiting, + Running, + Complete, + Warning, + Failed, +} + +public sealed record EngineEvent( + string Id, + EngineState State, + string Title, + string Detail, + ChecklistStatus Status); + +/// +/// Windows ships every tool the pipeline needs; the flags exist so tests can +/// exercise the missing-tool guidance paths. +/// +public sealed record ToolAvailability( + bool PowerShell = true, + bool Robocopy = true, + bool Dism = true); + +public static class ByteFormat +{ + /// Human-readable size in decimal units (matches Finder/Explorer style). + public static string Bytes(long value) + { + string[] units = ["bytes", "KB", "MB", "GB", "TB"]; + double size = value; + var unit = 0; + while (size >= 1000 && unit < units.Length - 1) + { + size /= 1000; + unit += 1; + } + return unit == 0 + ? $"{value} {units[unit]}" + : string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{size:0.#} {units[unit]}"); + } +} diff --git a/apps/windows/WInstaller.Core/OperationExecutor.cs b/apps/windows/WInstaller.Core/OperationExecutor.cs new file mode 100644 index 0000000..f02d54b --- /dev/null +++ b/apps/windows/WInstaller.Core/OperationExecutor.cs @@ -0,0 +1,345 @@ +using System.Threading.Channels; + +namespace WInstaller.Core; + +public enum ExecutionErrorKind +{ + IdentityMismatch, + RefusedSystemDisk, + MountFailed, + CommandFailed, + ValidationFailed, + Cancelled, +} + +public sealed class ExecutionException : Exception +{ + public ExecutionErrorKind Kind { get; } + public string UserMessage { get; } + + public ExecutionException(ExecutionErrorKind kind, string userMessage, string? detail = null) + : base(detail ?? userMessage) + { + Kind = kind; + UserMessage = userMessage; + } + + public static ExecutionException IdentityMismatch(string expected, string found) => new( + ExecutionErrorKind.IdentityMismatch, + "The USB drive changed since it was confirmed. wInstaller stopped before erasing anything.", + $"expected {expected}, found {found}"); + + public static ExecutionException RefusedSystemDisk() => new( + ExecutionErrorKind.RefusedSystemDisk, + "The target became a system disk. wInstaller refuses to erase system disks."); + + public static ExecutionException MountFailed(string detail) => new( + ExecutionErrorKind.MountFailed, + "wInstaller could not mount the ISO to copy its files.", + detail); + + public static ExecutionException CommandFailed(string step, int exitCode, string message) => new( + ExecutionErrorKind.CommandFailed, + $"A step failed while {step}. See technical details for the command output.", + $"exit {exitCode}: {message}"); + + public static ExecutionException ValidationFailed(IReadOnlyList missing) => new( + ExecutionErrorKind.ValidationFailed, + $"The bootable USB is missing required files: {string.Join(", ", missing)}."); + + public static ExecutionException Cancelled() => new( + ExecutionErrorKind.Cancelled, + "The operation was cancelled."); +} + +/// +/// Executes an for real, one step at a time, +/// through an . Emits typed +/// s so the UI never has to infer progress from raw +/// command strings (ARCHITECTURE.md). +/// +/// The destructive pipeline follows TERMINAL_AUTOMATION.md: the drive identity +/// is re-queried immediately before erase and the run aborts on any mismatch +/// or system disk. Only the erase/format step (and DISM image servicing) runs +/// elevated — a single UAC prompt scoped to that operation, per ADR-0003. +/// +public sealed class OperationExecutor +{ + public const string TargetVolumeLabel = "WINSTALLER"; + + /// Windows will not format FAT32 volumes larger than 32 GiB. + public const long MaxFat32PartitionBytes = 34_359_738_368; + + private readonly ICommandRunner _runner; + private readonly DiskEnumerator _enumerator; + private readonly LocalLogger? _logger; + /// Injectable so tests can assert validation without a real volume. + private readonly Func, IReadOnlyList> _missingFiles; + + public OperationExecutor( + ICommandRunner? runner = null, + DiskEnumerator? enumerator = null, + LocalLogger? logger = null, + Func, IReadOnlyList>? missingFiles = null) + { + _runner = runner ?? new ProcessCommandRunner(); + _enumerator = enumerator ?? new DiskEnumerator(_runner); + _logger = logger; + _missingFiles = missingFiles ?? (paths => + paths.Where(path => !File.Exists(path) && !Directory.Exists(path)).ToList()); + } + + /// Runs the plan and streams progress. Cancel via the token. + public IAsyncEnumerable Run(OperationPlan plan, CancellationToken cancellationToken = default) + { + var channel = Channel.CreateUnbounded(); + _ = Task.Run(async () => + { + try + { + await ExecuteAsync(plan, channel.Writer, cancellationToken).ConfigureAwait(false); + channel.Writer.TryComplete(); + } + catch (OperationCanceledException) + { + channel.Writer.TryComplete(ExecutionException.Cancelled()); + } + catch (Exception exception) + { + channel.Writer.TryComplete(exception); + } + }, CancellationToken.None); + return channel.Reader.ReadAllAsync(CancellationToken.None); + } + + private async Task ExecuteAsync( + OperationPlan plan, + ChannelWriter events, + CancellationToken cancellationToken) + { + var mountedIsoPath = (string?)null; + + async Task CleanupAsync() + { + if (mountedIsoPath is null) + { + return; + } + try + { + await _runner.RunAsync( + WindowsCommands.Script("dismount-iso.ps1", ["-IsoPath", mountedIsoPath], isDestructive: false), + CommandTimeout.Mount, + CancellationToken.None).ConfigureAwait(false); + } + catch + { + // Best-effort cleanup; the ISO mount is read-only either way. + } + } + + try + { + // 1. Mount the ISO read-only. + var mountResult = await RunStepAsync( + "mount-iso", EngineState.AnalyzingIso, "Mount ISO read-only", + WindowsCommands.Script("mount-iso.ps1", ["-IsoPath", plan.Iso.Path], isDestructive: false), + CommandTimeout.Mount, events, cancellationToken).ConfigureAwait(false); + mountedIsoPath = plan.Iso.Path; + var mount = IsoInspector.ParseMount(mountResult.StandardOutput); + if (string.IsNullOrEmpty(mount.DriveLetter)) + { + throw ExecutionException.MountFailed("no drive letter"); + } + var isoRoot = $@"{mount.DriveLetter}:\"; + + // 2. Re-check the USB identity immediately before any destructive work. + cancellationToken.ThrowIfCancellationRequested(); + var fresh = await _enumerator.InfoAsync(plan.Drive.DiskNumber, cancellationToken).ConfigureAwait(false); + if (fresh.IsSystemDisk) + { + throw ExecutionException.RefusedSystemDisk(); + } + if (fresh.DiskNumber != plan.Drive.DiskNumber + || fresh.Size != plan.Drive.Size + || !string.Equals(fresh.MediaName, plan.Drive.MediaName, StringComparison.Ordinal)) + { + throw ExecutionException.IdentityMismatch(plan.Drive.Identifier, fresh.Identifier); + } + await events.WriteAsync(new EngineEvent( + "verify-usb", EngineState.AnalyzingUsb, "USB identity re-checked", + $"{fresh.DisplayName} ({fresh.Identifier}) confirmed.", ChecklistStatus.Complete), cancellationToken).ConfigureAwait(false); + + // 3. Clean + format (DESTRUCTIVE, elevated — the single UAC prompt). + var diskNumber = plan.Drive.DiskNumber.ToString(System.Globalization.CultureInfo.InvariantCulture); + var prepareResult = await RunElevatedStepAsync( + "prepare-usb", EngineState.PreparingDrive, "Erase and format USB drive", + "prepare-usb.ps1", + [ + "-DiskNumber", diskNumber, + "-Label", TargetVolumeLabel, + "-SizeLimitBytes", MaxFat32PartitionBytes.ToString(System.Globalization.CultureInfo.InvariantCulture), + ], + isDestructive: true, CommandTimeout.Format, events, cancellationToken).ConfigureAwait(false); + var target = IsoInspector.ParseMount(prepareResult); + if (string.IsNullOrEmpty(target.DriveLetter)) + { + throw ExecutionException.CommandFailed("preparing the USB drive", 0, "the formatted volume has no drive letter"); + } + var targetRoot = $@"{target.DriveLetter}:\"; + + // 4. Copy installer files. When a WIM split is required, exclude the + // oversized image and split it separately in step 5. + var robocopyArgs = new List { isoRoot, targetRoot, "/E", "/NFL", "/NDL", "/NJH", "/NP" }; + if (plan.Strategy.RequiresWimSplit) + { + robocopyArgs.Add("/XF"); + robocopyArgs.Add("install.wim"); + } + _ = await RunStepAsync( + "copy-files", EngineState.CopyingFiles, "Copy installer files", + new PlannedCommand(WindowsCommands.SystemExecutable("robocopy.exe"), robocopyArgs, IsDestructive: false), + CommandTimeout.Watched, events, cancellationToken, + // Robocopy exit codes below 8 mean success (possibly with + // informational flags); 8+ means at least one copy failed. + succeeded: exitCode => exitCode < 8).ConfigureAwait(false); + + // 5. Split the Windows image when it exceeds the FAT32 file limit. + if (plan.Strategy.RequiresWimSplit) + { + _ = await RunElevatedStepAsync( + "split-wim", EngineState.SplittingWim, "Split oversized Windows image", + "split-wim.ps1", + [ + "-ImageFile", Path.Combine(isoRoot, "sources", "install.wim"), + "-SwmFile", Path.Combine(targetRoot, "sources", "install.swm"), + "-PartSizeMB", "3800", + ], + isDestructive: false, CommandTimeout.Watched, events, cancellationToken).ConfigureAwait(false); + } + + // 6. Validate required boot files exist on the target. + var missing = _missingFiles(ExpectedFiles(plan, targetRoot)); + if (missing.Count > 0) + { + await events.WriteAsync(new EngineEvent( + "validate", EngineState.Validating, "Boot validation failed", + string.Join(", ", missing), ChecklistStatus.Failed), cancellationToken).ConfigureAwait(false); + throw ExecutionException.ValidationFailed(missing); + } + await events.WriteAsync(new EngineEvent( + "validate", EngineState.Validating, "Boot files validated", + string.Join(", ", plan.ValidationChecks), ChecklistStatus.Complete), cancellationToken).ConfigureAwait(false); + + // 7. Eject safely. + _ = await RunStepAsync( + "eject", EngineState.Ejecting, "Eject USB safely", + WindowsCommands.Script("eject-disk.ps1", ["-DriveLetter", target.DriveLetter!], isDestructive: false), + CommandTimeout.Eject, events, cancellationToken).ConfigureAwait(false); + + await CleanupAsync().ConfigureAwait(false); + mountedIsoPath = null; + await events.WriteAsync(new EngineEvent( + "completed", EngineState.Completed, "Bootable USB ready", + $"{plan.Iso.DetectedOs.DisplayName} on {plan.Drive.DisplayName}.", ChecklistStatus.Complete), cancellationToken).ConfigureAwait(false); + } + catch + { + await CleanupAsync().ConfigureAwait(false); + throw; + } + } + + private async Task RunStepAsync( + string id, + EngineState state, + string title, + PlannedCommand command, + CommandTimeout timeout, + ChannelWriter events, + CancellationToken cancellationToken, + Func? succeeded = null) + { + cancellationToken.ThrowIfCancellationRequested(); + await events.WriteAsync(new EngineEvent(id, state, title, "Running…", ChecklistStatus.Running), cancellationToken).ConfigureAwait(false); + + var result = await _runner.RunAsync(command, timeout, cancellationToken).ConfigureAwait(false); + _logger?.Record(new LogEntry( + OperationId: id, + Tool: command.Executable, + Arguments: command.Arguments, + ExitCode: result.ExitCode, + UserMessage: title, + TechnicalDetail: result.StandardError)); + + var isSuccess = succeeded?.Invoke(result.ExitCode) ?? result.Succeeded; + if (!isSuccess) + { + await events.WriteAsync(new EngineEvent( + id, EngineState.Failed, title, $"Failed (exit {result.ExitCode}).", ChecklistStatus.Failed), cancellationToken).ConfigureAwait(false); + throw ExecutionException.CommandFailed(title, result.ExitCode, result.StandardError); + } + + await events.WriteAsync(new EngineEvent(id, state, title, "Complete.", ChecklistStatus.Complete), cancellationToken).ConfigureAwait(false); + return result; + } + + /// + /// Runs a helper script elevated. ShellExecute "runas" cannot redirect + /// output, so the script writes its JSON result to a temp file the + /// executor reads back; runners that do capture stdout (dry-run) are + /// supported by falling back to standard output. + /// + private async Task RunElevatedStepAsync( + string id, + EngineState state, + string title, + string scriptName, + IReadOnlyList parameters, + bool isDestructive, + CommandTimeout timeout, + ChannelWriter events, + CancellationToken cancellationToken) + { + var resultPath = Path.Combine(Path.GetTempPath(), $"winstaller-{id}-{Guid.NewGuid():N}.json"); + try + { + var arguments = new List(parameters) { "-ResultPath", resultPath }; + var command = WindowsCommands.Script(scriptName, arguments, isDestructive, requiresElevation: true); + var result = await RunStepAsync(id, state, title, command, timeout, events, cancellationToken).ConfigureAwait(false); + return File.Exists(resultPath) + ? await File.ReadAllTextAsync(resultPath, cancellationToken).ConfigureAwait(false) + : result.StandardOutput; + } + finally + { + try + { + File.Delete(resultPath); + } + catch + { + // Leaving a stray temp file behind is harmless. + } + } + } + + private static IReadOnlyList ExpectedFiles(OperationPlan plan, string targetRoot) + { + switch (plan.Iso.DetectedOs.Kind) + { + case OperatingSystemKind.Windows: + var files = new List + { + Path.Combine(targetRoot, "sources", "boot.wim"), + Path.Combine(targetRoot, "efi"), + }; + files.Add(plan.Strategy.RequiresWimSplit + ? Path.Combine(targetRoot, "sources", "install.swm") + : Path.Combine(targetRoot, "sources", "install.wim")); + return files; + default: + return [targetRoot]; + } + } +} diff --git a/apps/windows/WInstaller.Core/Scripts/disk-info.ps1 b/apps/windows/WInstaller.Core/Scripts/disk-info.ps1 new file mode 100644 index 0000000..3a72872 --- /dev/null +++ b/apps/windows/WInstaller.Core/Scripts/disk-info.ps1 @@ -0,0 +1,47 @@ +# Re-reads a single disk's identity as compact JSON. Used immediately before +# any destructive step so the pipeline can abort if the device changed. +# Read-only: this script never modifies any disk. +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [int]$DiskNumber +) + +$ErrorActionPreference = 'Stop' + +try { + $disk = Get-Disk -Number $DiskNumber + + $partitions = @(Get-Partition -DiskNumber $disk.Number -ErrorAction SilentlyContinue) + $volumes = @(foreach ($partition in $partitions) { + $volume = Get-Volume -Partition $partition -ErrorAction SilentlyContinue + if ($volume) { + [pscustomobject]@{ + DriveLetter = if ($volume.DriveLetter) { [string]$volume.DriveLetter } else { $null } + FileSystemLabel = [string]$volume.FileSystemLabel + FileSystem = [string]$volume.FileSystem + } + } + }) + + $wmiDisk = Get-CimInstance Win32_DiskDrive -Filter "Index=$($disk.Number)" -ErrorAction SilentlyContinue + + $result = [pscustomobject]@{ + Number = [int]$disk.Number + FriendlyName = [string]$disk.FriendlyName + Size = [long]$disk.Size + BusType = [string]$disk.BusType + IsBoot = [bool]$disk.IsBoot + IsSystem = [bool]$disk.IsSystem + IsRemovableMedia = [bool]($wmiDisk -and $wmiDisk.MediaType -match 'Removable') + PartitionStyle = [string]$disk.PartitionStyle + Volumes = $volumes + } + + ConvertTo-Json -InputObject $result -Depth 4 -Compress + exit 0 +} +catch { + [Console]::Error.WriteLine($_.Exception.Message) + exit 1 +} diff --git a/apps/windows/WInstaller.Core/Scripts/dismount-iso.ps1 b/apps/windows/WInstaller.Core/Scripts/dismount-iso.ps1 new file mode 100644 index 0000000..d21e1ec --- /dev/null +++ b/apps/windows/WInstaller.Core/Scripts/dismount-iso.ps1 @@ -0,0 +1,17 @@ +# Dismounts a previously mounted ISO. Safe to call repeatedly. +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [string]$IsoPath +) + +$ErrorActionPreference = 'Stop' + +try { + Dismount-DiskImage -ImagePath $IsoPath | Out-Null + exit 0 +} +catch { + [Console]::Error.WriteLine($_.Exception.Message) + exit 1 +} diff --git a/apps/windows/WInstaller.Core/Scripts/eject-disk.ps1 b/apps/windows/WInstaller.Core/Scripts/eject-disk.ps1 new file mode 100644 index 0000000..72c74a7 --- /dev/null +++ b/apps/windows/WInstaller.Core/Scripts/eject-disk.ps1 @@ -0,0 +1,26 @@ +# Safely ejects a removable volume so it can be unplugged. +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [ValidatePattern('^[A-Za-z]$')] + [string]$DriveLetter +) + +$ErrorActionPreference = 'Stop' + +try { + $shell = New-Object -ComObject Shell.Application + $volume = $shell.Namespace(17).ParseName("$($DriveLetter):") + if (-not $volume) { + throw "Volume $($DriveLetter): was not found." + } + $volume.InvokeVerb('Eject') + + # Give the shell a moment to flush and release the device. + Start-Sleep -Seconds 2 + exit 0 +} +catch { + [Console]::Error.WriteLine($_.Exception.Message) + exit 1 +} diff --git a/apps/windows/WInstaller.Core/Scripts/list-disks.ps1 b/apps/windows/WInstaller.Core/Scripts/list-disks.ps1 new file mode 100644 index 0000000..72e192e --- /dev/null +++ b/apps/windows/WInstaller.Core/Scripts/list-disks.ps1 @@ -0,0 +1,43 @@ +# Lists every physical disk as compact JSON for WInstaller.Core.DiskEnumerator. +# Read-only: this script never modifies any disk. +[CmdletBinding()] +param() + +$ErrorActionPreference = 'Stop' + +try { + $disks = @(Get-Disk | ForEach-Object { + $partitions = @(Get-Partition -DiskNumber $_.Number -ErrorAction SilentlyContinue) + $volumes = @(foreach ($partition in $partitions) { + $volume = Get-Volume -Partition $partition -ErrorAction SilentlyContinue + if ($volume) { + [pscustomobject]@{ + DriveLetter = if ($volume.DriveLetter) { [string]$volume.DriveLetter } else { $null } + FileSystemLabel = [string]$volume.FileSystemLabel + FileSystem = [string]$volume.FileSystem + } + } + }) + + $wmiDisk = Get-CimInstance Win32_DiskDrive -Filter "Index=$($_.Number)" -ErrorAction SilentlyContinue + + [pscustomobject]@{ + Number = [int]$_.Number + FriendlyName = [string]$_.FriendlyName + Size = [long]$_.Size + BusType = [string]$_.BusType + IsBoot = [bool]$_.IsBoot + IsSystem = [bool]$_.IsSystem + IsRemovableMedia = [bool]($wmiDisk -and $wmiDisk.MediaType -match 'Removable') + PartitionStyle = [string]$_.PartitionStyle + Volumes = $volumes + } + }) + + ConvertTo-Json -InputObject $disks -Depth 4 -Compress + exit 0 +} +catch { + [Console]::Error.WriteLine($_.Exception.Message) + exit 1 +} diff --git a/apps/windows/WInstaller.Core/Scripts/mount-iso.ps1 b/apps/windows/WInstaller.Core/Scripts/mount-iso.ps1 new file mode 100644 index 0000000..68b56d2 --- /dev/null +++ b/apps/windows/WInstaller.Core/Scripts/mount-iso.ps1 @@ -0,0 +1,38 @@ +# Mounts an ISO strictly read-only and reports its drive letter as JSON. +# The image is never modified (REQ-ISO-003, REQ-ISO-007). +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [string]$IsoPath +) + +$ErrorActionPreference = 'Stop' + +try { + $image = Mount-DiskImage -ImagePath $IsoPath -Access ReadOnly -PassThru + + # The volume can take a moment to surface after the mount call returns. + $volume = $null + for ($attempt = 0; $attempt -lt 20; $attempt++) { + $volume = $image | Get-Volume -ErrorAction SilentlyContinue + if ($volume -and $volume.DriveLetter) { break } + Start-Sleep -Milliseconds 500 + $image = Get-DiskImage -ImagePath $IsoPath + } + + if (-not $volume -or -not $volume.DriveLetter) { + Dismount-DiskImage -ImagePath $IsoPath | Out-Null + throw 'The ISO mounted but no drive letter was assigned.' + } + + $result = [pscustomobject]@{ + DriveLetter = [string]$volume.DriveLetter + VolumeLabel = [string]$volume.FileSystemLabel + } + ConvertTo-Json -InputObject $result -Compress + exit 0 +} +catch { + [Console]::Error.WriteLine($_.Exception.Message) + exit 1 +} diff --git a/apps/windows/WInstaller.Core/Scripts/prepare-usb.ps1 b/apps/windows/WInstaller.Core/Scripts/prepare-usb.ps1 new file mode 100644 index 0000000..b7f0437 --- /dev/null +++ b/apps/windows/WInstaller.Core/Scripts/prepare-usb.ps1 @@ -0,0 +1,68 @@ +# DESTRUCTIVE: cleans a removable USB disk and creates a GPT/FAT32 installer +# volume. This is the only step wInstaller runs elevated (ADR-0003) — it is +# invoked through a single UAC prompt after the user has already typed the +# drive name in the confirmation gate. +# +# Safety gates are re-checked *inside* the elevated context: the script refuses +# boot/system disks and any disk that is not on the USB bus, regardless of what +# the caller asked for. +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [int]$DiskNumber, + + [Parameter(Mandatory = $true)] + [string]$Label, + + # Windows will not format FAT32 volumes larger than 32 GiB. + [long]$SizeLimitBytes = 34359738368, + + # Where to write the JSON result; elevation cannot redirect stdout. + [string]$ResultPath = '' +) + +$ErrorActionPreference = 'Stop' + +try { + $disk = Get-Disk -Number $DiskNumber + + if ($disk.IsBoot -or $disk.IsSystem) { + throw "Refusing to erase disk $DiskNumber - it hosts the running system." + } + if ($disk.BusType -ne 'USB') { + throw "Refusing to erase disk $DiskNumber - it is not a USB device (BusType: $($disk.BusType))." + } + + if ($disk.PartitionStyle -ne 'RAW') { + Clear-Disk -Number $DiskNumber -RemoveData -RemoveOEM -Confirm:$false + } + Initialize-Disk -Number $DiskNumber -PartitionStyle GPT -ErrorAction SilentlyContinue | Out-Null + + $disk = Get-Disk -Number $DiskNumber + if ($disk.Size -gt $SizeLimitBytes) { + $partition = New-Partition -DiskNumber $DiskNumber -Size $SizeLimitBytes -AssignDriveLetter + } + else { + $partition = New-Partition -DiskNumber $DiskNumber -UseMaximumSize -AssignDriveLetter + } + + $volume = Format-Volume -Partition $partition -FileSystem FAT32 -NewFileSystemLabel $Label -Confirm:$false + + $result = [pscustomobject]@{ + DriveLetter = [string]$volume.DriveLetter + VolumeLabel = [string]$volume.FileSystemLabel + } + $json = ConvertTo-Json -InputObject $result -Compress + if ($ResultPath) { + Set-Content -Path $ResultPath -Value $json -Encoding utf8 -NoNewline + } + $json + exit 0 +} +catch { + if ($ResultPath) { + Set-Content -Path $ResultPath -Value '' -Encoding utf8 -NoNewline + } + [Console]::Error.WriteLine($_.Exception.Message) + exit 1 +} diff --git a/apps/windows/WInstaller.Core/Scripts/split-wim.ps1 b/apps/windows/WInstaller.Core/Scripts/split-wim.ps1 new file mode 100644 index 0000000..30c3747 --- /dev/null +++ b/apps/windows/WInstaller.Core/Scripts/split-wim.ps1 @@ -0,0 +1,41 @@ +# Splits an install.wim that exceeds the FAT32 single-file limit into +# setup-compatible .swm parts using DISM (which ships with Windows). +# Reads the source image from the read-only ISO mount; writes only to the +# installer USB volume. +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [string]$ImageFile, + + [Parameter(Mandatory = $true)] + [string]$SwmFile, + + [int]$PartSizeMB = 3800, + + # Where to write the JSON result; elevation cannot redirect stdout. + [string]$ResultPath = '' +) + +$ErrorActionPreference = 'Stop' + +try { + $dism = Join-Path $env:SystemRoot 'System32\Dism.exe' + & $dism /Split-Image "/ImageFile:$ImageFile" "/SWMFile:$SwmFile" "/FileSize:$PartSizeMB" | Out-Null + if ($LASTEXITCODE -ne 0) { + throw "DISM /Split-Image failed with exit code $LASTEXITCODE." + } + + $json = ConvertTo-Json -InputObject ([pscustomobject]@{ Status = 'ok' }) -Compress + if ($ResultPath) { + Set-Content -Path $ResultPath -Value $json -Encoding utf8 -NoNewline + } + $json + exit 0 +} +catch { + if ($ResultPath) { + Set-Content -Path $ResultPath -Value '' -Encoding utf8 -NoNewline + } + [Console]::Error.WriteLine($_.Exception.Message) + exit 1 +} diff --git a/apps/windows/WInstaller.Core/Simulation.cs b/apps/windows/WInstaller.Core/Simulation.cs new file mode 100644 index 0000000..c5f9e43 --- /dev/null +++ b/apps/windows/WInstaller.Core/Simulation.cs @@ -0,0 +1,86 @@ +using System.Text.Json; + +namespace WInstaller.Core; + +/// +/// Simulate (dry-run) support: an whose runner +/// answers every planned command with a canned success and never touches a +/// disk. The UI runs the exact same pipeline, checklist, and logging as a real +/// run (USER_FLOW.md's Simulate toggle). +/// +public static class Simulation +{ + public static OperationExecutor Executor(OperationPlan plan, LocalLogger? logger = null) => new( + runner: new DryRunCommandRunner(plan), + logger: logger, + missingFiles: _ => []); +} + +/// +/// Answers each helper script with plausible output: the mounted ISO gets a +/// fake drive letter, the identity re-check echoes the planned drive back, and +/// destructive commands succeed without running anything. +/// +public sealed class DryRunCommandRunner : ICommandRunner +{ + private readonly OperationPlan _plan; + private readonly TimeSpan _stepDelay; + + public DryRunCommandRunner(OperationPlan plan, TimeSpan? stepDelay = null) + { + _plan = plan; + _stepDelay = stepDelay ?? TimeSpan.FromMilliseconds(400); + } + + public async Task RunAsync(PlannedCommand command, CommandTimeout timeout, CancellationToken cancellationToken = default) + { + await Task.Delay(_stepDelay, cancellationToken).ConfigureAwait(false); + + var startedAt = DateTimeOffset.Now; + var output = Output(command); + return new CommandResult( + command.Executable, + command.Arguments, + output, + StandardError: "", + ExitCode: 0, + startedAt, + DateTimeOffset.Now); + } + + private string Output(PlannedCommand command) + { + var script = command.Arguments + .Select(Path.GetFileName) + .FirstOrDefault(name => name?.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase) == true); + + switch (script) + { + case "mount-iso.ps1": + return """{"DriveLetter":"W","VolumeLabel":"SIMULATED"}"""; + case "disk-info.ps1": + // Echo the planned drive so the identity safety gate passes. + return JsonSerializer.Serialize(new + { + Number = _plan.Drive.DiskNumber, + FriendlyName = _plan.Drive.MediaName, + Size = _plan.Drive.Size, + BusType = _plan.Drive.ConnectionType, + IsBoot = false, + IsSystem = false, + IsRemovableMedia = true, + PartitionStyle = _plan.Drive.PartitionScheme, + Volumes = _plan.Drive.Volumes.Select(volume => new + { + DriveLetter = (string?)null, + FileSystemLabel = volume, + FileSystem = _plan.Drive.FileSystem, + }), + }); + case "prepare-usb.ps1": + return """{"DriveLetter":"X"}"""; + default: + return ""; + } + } +} diff --git a/apps/windows/WInstaller.Core/WInstaller.Core.csproj b/apps/windows/WInstaller.Core/WInstaller.Core.csproj new file mode 100644 index 0000000..bf91574 --- /dev/null +++ b/apps/windows/WInstaller.Core/WInstaller.Core.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + WInstaller.Core + enable + enable + true + + + + + + + + + + + + diff --git a/apps/windows/WInstaller.sln b/apps/windows/WInstaller.sln new file mode 100644 index 0000000..b9424eb --- /dev/null +++ b/apps/windows/WInstaller.sln @@ -0,0 +1,61 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WInstaller.Core", "WInstaller.Core\WInstaller.Core.csproj", "{6F9A3A66-0C21-4C34-8F5B-2E1A57C0A001}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WInstaller.Core.Tests", "WInstaller.Core.Tests\WInstaller.Core.Tests.csproj", "{6F9A3A66-0C21-4C34-8F5B-2E1A57C0A002}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WInstaller.App", "WInstaller.App\WInstaller.App.csproj", "{6F9A3A66-0C21-4C34-8F5B-2E1A57C0A003}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|ARM64 = Debug|ARM64 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|ARM64 = Release|ARM64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A001}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A001}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A001}.Debug|x64.ActiveCfg = Debug|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A001}.Debug|x64.Build.0 = Debug|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A001}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A001}.Debug|ARM64.Build.0 = Debug|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A001}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A001}.Release|Any CPU.Build.0 = Release|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A001}.Release|x64.ActiveCfg = Release|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A001}.Release|x64.Build.0 = Release|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A001}.Release|ARM64.ActiveCfg = Release|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A001}.Release|ARM64.Build.0 = Release|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A002}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A002}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A002}.Debug|x64.ActiveCfg = Debug|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A002}.Debug|x64.Build.0 = Debug|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A002}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A002}.Debug|ARM64.Build.0 = Debug|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A002}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A002}.Release|Any CPU.Build.0 = Release|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A002}.Release|x64.ActiveCfg = Release|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A002}.Release|x64.Build.0 = Release|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A002}.Release|ARM64.ActiveCfg = Release|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A002}.Release|ARM64.Build.0 = Release|Any CPU + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A003}.Debug|Any CPU.ActiveCfg = Debug|x64 + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A003}.Debug|Any CPU.Build.0 = Debug|x64 + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A003}.Debug|x64.ActiveCfg = Debug|x64 + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A003}.Debug|x64.Build.0 = Debug|x64 + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A003}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A003}.Debug|ARM64.Build.0 = Debug|ARM64 + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A003}.Release|Any CPU.ActiveCfg = Release|x64 + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A003}.Release|Any CPU.Build.0 = Release|x64 + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A003}.Release|x64.ActiveCfg = Release|x64 + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A003}.Release|x64.Build.0 = Release|x64 + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A003}.Release|ARM64.ActiveCfg = Release|ARM64 + {6F9A3A66-0C21-4C34-8F5B-2E1A57C0A003}.Release|ARM64.Build.0 = Release|ARM64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/docs/screen-inventory.yaml b/docs/screen-inventory.yaml index 50be022..dddbf45 100644 --- a/docs/screen-inventory.yaml +++ b/docs/screen-inventory.yaml @@ -19,7 +19,7 @@ steps: required_data: [] platforms: macos: implemented - windows: planned + windows: implemented linux: planned - id: choose-iso @@ -27,7 +27,7 @@ steps: required_data: [iso_path] platforms: macos: implemented - windows: planned + windows: implemented linux: planned - id: verify-iso @@ -35,7 +35,7 @@ steps: required_data: [iso_name, iso_size, volume_label, detected_os, confidence, boot_strategy] platforms: macos: implemented - windows: planned + windows: implemented linux: planned - id: insert-usb @@ -43,7 +43,7 @@ steps: required_data: [drive_list] platforms: macos: implemented - windows: planned + windows: implemented linux: planned - id: analyze-usb @@ -51,7 +51,7 @@ steps: required_data: [drive_details, current_partition_scheme, required_format] platforms: macos: implemented - windows: planned + windows: implemented linux: planned - id: confirm-erase @@ -59,7 +59,7 @@ steps: required_data: [drive_name, drive_identifier, drive_capacity] platforms: macos: implemented - windows: planned + windows: implemented linux: planned - id: create-usb @@ -67,7 +67,7 @@ steps: required_data: [progress_checklist] platforms: macos: implemented - windows: planned + windows: implemented linux: planned - id: done @@ -75,7 +75,7 @@ steps: required_data: [usb_name, usb_identifier, detected_os, validation_checklist] platforms: macos: implemented - windows: planned + windows: implemented linux: planned - id: use-with-vmware diff --git a/docs/site/index.html b/docs/site/index.html index 4cc2193..0bdca39 100644 --- a/docs/site/index.html +++ b/docs/site/index.html @@ -21,7 +21,7 @@

wInstaller

Windows - Coming soon + Download Linux diff --git a/docs/specs/ROADMAP.md b/docs/specs/ROADMAP.md index 6c75240..d2de118 100644 --- a/docs/specs/ROADMAP.md +++ b/docs/specs/ROADMAP.md @@ -2,13 +2,25 @@ ## Implementation status (current) -Delivered so far: the assistant shell and mock data (0.1); real ISO/USB analysis, -disk-safety filtering, and dry-run planning (0.2); the erase→format→copy→validate→ -eject execution pipeline with the identity-recheck safety gate (0.3); oversized -`install.wim` detection and `wimlib-imagex` splitting (0.4); and VMware Fusion / -UTM / Parallels detection with a guided handoff (0.5). Remaining before 1.0: -hardware QA on real media, Linux distro-family validation (0.6), advanced recovery -and support-bundle export (0.7), and Developer ID signing + notarization (1.0). +Delivered so far on macOS: the assistant shell and mock data (0.1); real ISO/USB +analysis, disk-safety filtering, and dry-run planning (0.2); the erase→format→ +copy→validate→eject execution pipeline with the identity-recheck safety gate +(0.3); oversized `install.wim` detection and `wimlib-imagex` splitting (0.4); and +VMware Fusion / UTM / Parallels detection with a guided handoff (0.5). + +Delivered on Windows (`apps/windows/`): the full native WinUI 3 + C#/.NET app +covering the same happy path — C# domain core with the same state machine and +safety gates, PowerShell-based disk enumeration and read-only ISO inspection, +the elevated-once erase→GPT/FAT32 format→robocopy→validate→eject pipeline, +`DISM /Split-Image` for oversized WIMs, Simulate mode, redacted local logging, +and CI (build + tests on a Windows runner, plus a portable-zip release +workflow). The virtualization-handoff step is not-applicable on Windows per +`docs/screen-inventory.yaml`. + +Remaining before 1.0: hardware QA on real media (macOS and Windows), Linux +distro-family validation (0.6), the Linux native app (Phase 2), advanced +recovery and support-bundle export (0.7), and per-OS release signing — +Developer ID + notarization on macOS, Authenticode/MSIX on Windows (1.0). ## 0.1: Product Foundation diff --git a/scripts/gen_strings_dotnet.py b/scripts/gen_strings_dotnet.py new file mode 100644 index 0000000..299c723 --- /dev/null +++ b/scripts/gen_strings_dotnet.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""Generate the Windows app's .resx string table from shared/strings/copy.yaml. + +shared/strings/copy.yaml is the single hand-edited source of user-facing copy +across the three native UIs (docs/adr/0008-feature-parity-enforcement.md). +This script flattens it to "." resources and writes a +deterministic apps/windows/WInstaller.App/Strings/AppStrings.resx. + +Usage: + python3 scripts/gen_strings_dotnet.py # regenerate the .resx + python3 scripts/gen_strings_dotnet.py --check # fail if committed output is stale +""" +import sys +from pathlib import Path +from xml.sax.saxutils import escape + +import yaml + +REPO_ROOT = Path(__file__).resolve().parent.parent +COPY_PATH = REPO_ROOT / "shared" / "strings" / "copy.yaml" +OUTPUT_PATH = REPO_ROOT / "apps" / "windows" / "WInstaller.App" / "Strings" / "AppStrings.resx" + +HEADER = """\ + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + +""" + +FOOTER = "\n" + + +def flatten(copy: dict) -> dict[str, str]: + flat: dict[str, str] = {} + for section, entries in copy.items(): + if not isinstance(entries, dict): + raise SystemExit(f"copy.yaml section '{section}' must be a mapping") + for key, value in entries.items(): + if not isinstance(value, str): + raise SystemExit(f"copy.yaml value '{section}.{key}' must be a string") + flat[f"{section}.{key}"] = value + return flat + + +def render(flat: dict[str, str]) -> str: + body = [] + for key in sorted(flat): + value = escape(flat[key]) + body.append(f' \n' + f" {value}\n" + " \n") + return HEADER + "".join(body) + FOOTER + + +def main() -> int: + check_only = "--check" in sys.argv[1:] + copy = yaml.safe_load(COPY_PATH.read_text(encoding="utf-8")) + rendered = render(flatten(copy)) + + if check_only: + committed = OUTPUT_PATH.read_text(encoding="utf-8") if OUTPUT_PATH.exists() else "" + if committed != rendered: + print( + f"{OUTPUT_PATH.relative_to(REPO_ROOT)} is out of date with " + "shared/strings/copy.yaml.\nRegenerate it with: " + "python3 scripts/gen_strings_dotnet.py" + ) + return 1 + print("Windows strings are in sync with copy.yaml.") + return 0 + + OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True) + OUTPUT_PATH.write_text(rendered, encoding="utf-8") + print(f"Wrote {OUTPUT_PATH.relative_to(REPO_ROOT)} ({len(flatten(copy))} strings).") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/make-ico.py b/scripts/make-ico.py new file mode 100644 index 0000000..7e74705 --- /dev/null +++ b/scripts/make-ico.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Build the Windows app icon (.ico) from the existing PNG icon set. + +ICO files may embed PNG-compressed images directly (supported since Windows +Vista), so this needs no imaging library. Output: +apps/windows/WInstaller.App/Assets/wInstaller.ico +""" +import struct +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +ICONSET = REPO_ROOT / "Assets" / "AppIcon.appiconset" +OUTPUT = REPO_ROOT / "apps" / "windows" / "WInstaller.App" / "Assets" / "wInstaller.ico" + +SIZES = [16, 32, 64, 128, 256] + + +def main() -> None: + images = [(size, (ICONSET / f"icon_{size}.png").read_bytes()) for size in SIZES] + + header = struct.pack("= 256 else size # 0 encodes 256 in ICO entries + entries += struct.pack( + "