commit 5daecad2f27ef54974456206f131f91b2ac9b6cb Author: dennii Date: Fri Nov 27 12:48:23 2026 +1100 Initial commit: .NET NativeAOT Microsoft 365 en-US offline .img downloader and setup installer diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..013fb38 --- /dev/null +++ b/.gitignore @@ -0,0 +1,19 @@ +# Build outputs & intermediates +bin/ +obj/ +dist/ +installer/bin/ +installer/obj/ +installer/payload.gz + +# Generated build icon (re-generated automatically by build.ps1, or keep src/app.ico tracked) +# Local download artifacts +*.img +*.part +*.meta + +# IDE / OS files +.vs/ +.vscode/ +Thumbs.db +Desktop.ini diff --git a/M365IsoDownloader.csproj b/M365IsoDownloader.csproj new file mode 100644 index 0000000..6450f1b --- /dev/null +++ b/M365IsoDownloader.csproj @@ -0,0 +1,26 @@ + + + WinExe + net9.0 + win-x64 + true + true + enable + disable + true + Speed + true + src\app.manifest + src\app.ico + M365IsoDownloader + 1.0.0 + M365 Tools + Microsoft 365 Offline Image Downloader + Single-file .NET NativeAOT GUI for checking and downloading Microsoft 365 en-US offline .img installers. + + + + + + + diff --git a/README.md b/README.md new file mode 100644 index 0000000..7931b67 --- /dev/null +++ b/README.md @@ -0,0 +1,25 @@ +# Microsoft 365 Offline Image Downloader (`en-US`) — .NET NativeAOT + +A single-file, zero-dependency Windows desktop GUI (`dist\M365IsoDownloader.exe`) compiled ahead-of-time to native `win-x64` machine code with **.NET 9 NativeAOT** (`true`). + +## Supported Editions (`en-US`, 32-bit & 64-bit) +- **Microsoft 365 Apps for Enterprise** (`O365ProPlusRetail.img`) +- **Microsoft 365 Apps for Business** (`O365BusinessRetail.img`) +- **Microsoft 365 Personal / Family** (`O365HomePremRetail.img`) + +## Highlights +- **True `.NET NativeAOT` Single-File `.exe`:** Compiled directly to native x64 machine code with no JIT, no external DLLs, and no `.NET` runtime required on target Windows 10/11 PCs. +- **Crisp Windows 11 Desktop UI:** Hardware-composited rounded window corners, Per-Monitor v2 High-DPI scaling, ClearType typography, and double-buffered GDI+ Fluent card layout. +- **Instant Build Inspection (Zero Full Download Needed):** Sends HTTP `HEAD` + a 192 KB HTTP `Range` request (`bytes=32768-229375`) to read the ISO-9660 volume header and display the exact `16.0.xxxxx.xxxxx` build version, publish date, and file size before downloading. +- **Local `.img` Build Comparison:** Reads byte `32768` of any existing `.img` files in your save folder to compare local vs. CDN builds (`Up to Date` vs. `Update Available`). +- **Pause & Resume Support:** Streams via `SocketsHttpHandler` (HTTP/2 + TLS 1.3) into `.img.part` files with `ETag` verification, live transfer speed, and ETA. +- **Automatic CDN Fallback:** Uses `/db/` primary endpoints and transparently falls back to `/pr/`. + +## Building from Source +Requires the `.NET 9+ SDK` and Visual Studio 2022 C++ Build Tools (`MSVC` + Windows SDK): + +```powershell +powershell -ExecutionPolicy Bypass -File .\build.ps1 +``` + +Output executable: `dist\M365IsoDownloader.exe` diff --git a/build.ps1 b/build.ps1 new file mode 100644 index 0000000..9d1e830 --- /dev/null +++ b/build.ps1 @@ -0,0 +1,143 @@ +$ErrorActionPreference = "Stop" + +$root = Split-Path -Parent $MyInvocation.MyCommand.Path +$srcDir = Join-Path $root "src" +$installerDir = Join-Path $root "installer" +$distDir = Join-Path $root "dist" +New-Item -ItemType Directory -Force -Path $distDir | Out-Null + +# 1. Generate multi-resolution Windows .ico file (16, 32, 48, 256 px) if not already created +$icoPath = Join-Path $srcDir "app.ico" +if (-not (Test-Path $icoPath)) { + Add-Type -AssemblyName System.Drawing + + function New-IconPngBytes([int]$size) { + $bmp = New-Object System.Drawing.Bitmap($size, $size, [System.Drawing.Imaging.PixelFormat]::Format32bppArgb) + $g = [System.Drawing.Graphics]::FromImage($bmp) + $g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias + $g.Clear([System.Drawing.Color]::Transparent) + + $pad = [float]($size * 0.06) + $rectSize = [float]($size - 2 * $pad) + $radius = [float]($size * 0.22) + $d = $radius * 2 + + $path = New-Object System.Drawing.Drawing2D.GraphicsPath + $path.AddArc($pad, $pad, $d, $d, 180, 90) + $path.AddArc($pad + $rectSize - $d, $pad, $d, $d, 270, 90) + $path.AddArc($pad + $rectSize - $d, $pad + $rectSize - $d, $d, $d, 0, 90) + $path.AddArc($pad, $pad + $rectSize - $d, $d, $d, 90, 90) + $path.CloseFigure() + + $brush = New-Object System.Drawing.Drawing2D.LinearGradientBrush( + (New-Object System.Drawing.PointF(0, 0)), + (New-Object System.Drawing.PointF($size, $size)), + [System.Drawing.Color]::FromArgb(255, 0, 114, 214), + [System.Drawing.Color]::FromArgb(255, 0, 74, 152) + ) + $g.FillPath($brush, $path) + + $strokeW = [Math]::Max(1.6, [float]($size * 0.095)) + $pen = New-Object System.Drawing.Pen([System.Drawing.Color]::White, $strokeW) + $pen.StartCap = [System.Drawing.Drawing2D.LineCap]::Round + $pen.EndCap = [System.Drawing.Drawing2D.LineCap]::Round + $pen.LineJoin = [System.Drawing.Drawing2D.LineJoin]::Round + + $cx = [float]($size * 0.5) + $topY = [float]($size * 0.24) + $tipY = [float]($size * 0.62) + $wingDx = [float]($size * 0.19) + $wingY = [float]($size * 0.44) + $trayY = [float]($size * 0.76) + $trayHalf = [float]($size * 0.24) + + $g.DrawLine($pen, $cx, $topY, $cx, $tipY) + $g.DrawLine($pen, ($cx - $wingDx), $wingY, $cx, $tipY) + $g.DrawLine($pen, ($cx + $wingDx), $wingY, $cx, $tipY) + $g.DrawLine($pen, ($cx - $trayHalf), $trayY, ($cx + $trayHalf), $trayY) + + $ms = New-Object System.IO.MemoryStream + $bmp.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png) + $pen.Dispose(); $brush.Dispose(); $path.Dispose(); $g.Dispose(); $bmp.Dispose() + return ,$ms.ToArray() + } + + $sizes = @(16, 32, 48, 256) + $pngBlobs = @() + foreach ($s in $sizes) { $pngBlobs += ,(New-IconPngBytes $s) } + + $fs = [System.IO.File]::Open($icoPath, [System.IO.FileMode]::Create) + $bw = New-Object System.IO.BinaryWriter($fs) + $bw.Write([uint16]0); $bw.Write([uint16]1); $bw.Write([uint16]$sizes.Count) + $offset = 6 + (16 * $sizes.Count) + for ($i = 0; $i -lt $sizes.Count; $i++) { + $s = $sizes[$i]; $blob = $pngBlobs[$i] + $dimByte = if ($s -ge 256) { [byte]0 } else { [byte]$s } + $bw.Write($dimByte); $bw.Write($dimByte); $bw.Write([byte]0); $bw.Write([byte]0) + $bw.Write([uint16]1); $bw.Write([uint16]32) + $bw.Write([uint32]$blob.Length); $bw.Write([uint32]$offset) + $offset += $blob.Length + } + for ($i = 0; $i -lt $sizes.Count; $i++) { $bw.Write($pngBlobs[$i]) } + $bw.Flush(); $bw.Close(); $fs.Close() +} + +# 2. Locate .NET SDK (system or portable scratch SDK) +$dotnetExe = $null +if (Get-Command dotnet -ErrorAction SilentlyContinue) { + $sdks = & dotnet --list-sdks 2>$null + if ($sdks) { $dotnetExe = (Get-Command dotnet).Source } +} +if (-not $dotnetExe) { + $portableDotnet = Join-Path (Split-Path -Parent $root) ".dotnet\dotnet.exe" + if (Test-Path $portableDotnet) { $dotnetExe = $portableDotnet } +} +if (-not $dotnetExe) { + throw "No .NET SDK found. Install the .NET 9+ SDK and Visual Studio C++ Build Tools." +} + +$env:DOTNET_CLI_TELEMETRY_OPTOUT = "1" +$env:DOTNET_NOLOGO = "1" + +# 3. Publish Portable NativeAOT single-file executable (skip overwriting if currently running) +$portableExe = Join-Path $distDir "M365IsoDownloader.exe" +$isRunning = @(Get-Process -Name "M365IsoDownloader" -ErrorAction SilentlyContinue).Count -gt 0 +if (-not $isRunning -or -not (Test-Path $portableExe)) { + $projFile = Join-Path $root "M365IsoDownloader.csproj" + & $dotnetExe publish $projFile -c Release -r win-x64 --nologo -o $distDir + if ($LASTEXITCODE -ne 0) { + throw "NativeAOT app publish failed with exit code $LASTEXITCODE" + } +} else { + Write-Host "M365IsoDownloader.exe is currently running; preserving existing binary in dist\." +} + +# 4. Compress M365IsoDownloader.exe into installer\payload.gz and publish NativeAOT Setup Installer +$setupProj = Join-Path $installerDir "M365IsoDownloader.Setup.csproj" +if (Test-Path $setupProj) { + $payloadGz = Join-Path $installerDir "payload.gz" + $inFs = New-Object System.IO.FileStream($portableExe, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite) + $outFs = [System.IO.File]::Create($payloadGz) + $gz = New-Object System.IO.Compression.GZipStream($outFs, [System.IO.Compression.CompressionLevel]::Optimal) + $inFs.CopyTo($gz) + $gz.Dispose() + $outFs.Dispose() + $inFs.Dispose() + + $setupOutDir = Join-Path $installerDir "bin\publish" + & $dotnetExe publish $setupProj -c Release -r win-x64 --nologo -o $setupOutDir + if ($LASTEXITCODE -ne 0) { + throw "NativeAOT setup installer publish failed with exit code $LASTEXITCODE" + } + + Copy-Item (Join-Path $setupOutDir "M365IsoDownloader-Setup.exe") (Join-Path $distDir "M365IsoDownloader-Setup.exe") -Force + Remove-Item $payloadGz -Force -ErrorAction SilentlyContinue +} + +# Clean up any non-exe artifacts in dist +Get-ChildItem $distDir -File | Where-Object { $_.Extension -ne ".exe" } | Remove-Item -Force + +Write-Host "`nBuilt .NET NativeAOT deliverables in dist\:" +Get-ChildItem $distDir -Filter "*.exe" | ForEach-Object { + Write-Host (" {0,-32} {1,6:N2} MB ({2})" -f $_.Name, ($_.Length / 1MB), $_.FullName) +} diff --git a/installer/M365IsoDownloader.Setup.csproj b/installer/M365IsoDownloader.Setup.csproj new file mode 100644 index 0000000..7e11e53 --- /dev/null +++ b/installer/M365IsoDownloader.Setup.csproj @@ -0,0 +1,24 @@ + + + WinExe + net9.0-windows + win-x64 + true + true + enable + disable + true + Size + true + ..\src\app.manifest + ..\src\app.ico + M365IsoDownloader-Setup + 1.0.0 + M365 Tools + Microsoft 365 Offline Image Downloader Setup + + + + + + diff --git a/installer/SetupProgram.cs b/installer/SetupProgram.cs new file mode 100644 index 0000000..aea6250 --- /dev/null +++ b/installer/SetupProgram.cs @@ -0,0 +1,1145 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.IO.Compression; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Microsoft.Win32; + +namespace M365IsoDownloaderSetup +{ + internal static unsafe class SetupNative + { + public const uint WS_OVERLAPPED = 0x00000000; + public const uint WS_CAPTION = 0x00C00000; + public const uint WS_SYSMENU = 0x00080000; + public const uint WS_MINIMIZEBOX = 0x00020000; + public const uint CS_HREDRAW = 0x0002; + public const uint CS_VREDRAW = 0x0001; + + public const uint WM_DESTROY = 0x0002; + public const uint WM_PAINT = 0x000F; + public const uint WM_CLOSE = 0x0010; + public const uint WM_ERASEBKGND = 0x0014; + public const uint WM_SETCURSOR = 0x0020; + public const uint WM_MOUSEMOVE = 0x0200; + public const uint WM_LBUTTONDOWN = 0x0201; + public const uint WM_LBUTTONUP = 0x0202; + public const uint WM_MOUSELEAVE = 0x02A3; + public const uint WM_DPICHANGED = 0x02E0; + + public const int SW_SHOW = 5; + public const int IDC_ARROW = 32512; + public const int IDC_HAND = 32649; + public const uint SRCCOPY = 0x00CC0020; + public const uint MB_OK = 0x00000000; + public const uint MB_YESNO = 0x00000004; + public const uint MB_ICONINFORMATION = 0x00000040; + public const uint MB_ICONQUESTION = 0x00000020; + public const uint MB_ICONERROR = 0x00000010; + public const int IDYES = 6; + + [StructLayout(LayoutKind.Sequential)] + public struct POINT { public int X, Y; } + + [StructLayout(LayoutKind.Sequential)] + public struct RECT { public int Left, Top, Right, Bottom; } + + [StructLayout(LayoutKind.Sequential)] + public struct MSG + { + public IntPtr hwnd; + public uint message; + public nuint wParam; + public nint lParam; + public uint time; + public POINT pt; + } + + [StructLayout(LayoutKind.Sequential)] + public struct PAINTSTRUCT + { + public IntPtr hdc; + public int fErase; + public RECT rcPaint; + public int fRestore; + public int fIncUpdate; + public fixed byte rgbReserved[32]; + } + + [StructLayout(LayoutKind.Sequential)] + public struct TRACKMOUSEEVENT + { + public uint cbSize; + public uint dwFlags; + public IntPtr hwndTrack; + public uint dwHoverTime; + } + + [StructLayout(LayoutKind.Sequential)] + public struct WNDCLASSEXW + { + public uint cbSize; + public uint style; + public delegate* unmanaged[Stdcall] lpfnWndProc; + public int cbClsExtra; + public int cbWndExtra; + public IntPtr hInstance; + public IntPtr hIcon; + public IntPtr hCursor; + public IntPtr hbrBackground; + public char* lpszMenuName; + public char* lpszClassName; + public IntPtr hIconSm; + } + + [StructLayout(LayoutKind.Sequential)] + public struct BITMAPINFOHEADER + { + public uint biSize; + public int biWidth; + public int biHeight; + public ushort biPlanes; + public ushort biBitCount; + public uint biCompression; + public uint biSizeImage; + public int biXPelsPerMeter; + public int biYPelsPerMeter; + public uint biClrUsed; + public uint biClrImportant; + } + + [StructLayout(LayoutKind.Sequential)] + public struct RectF + { + public float X, Y, Width, Height; + public RectF(float x, float y, float w, float h) { X = x; Y = y; Width = w; Height = h; } + public bool Contains(float px, float py) => px >= X && px <= X + Width && py >= Y && py <= Y + Height; + } + + [StructLayout(LayoutKind.Sequential)] + public struct GdiplusStartupInput + { + public uint GdiplusVersion; + public IntPtr DebugEventCallback; + public int SuppressBackgroundThread; + public int SuppressExternalCodecs; + } + + [DllImport("kernel32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern IntPtr GetModuleHandleW(char* lpModuleName); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern ushort RegisterClassExW(ref WNDCLASSEXW lpwcx); + + [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern IntPtr CreateWindowExW( + uint dwExStyle, char* lpClassName, char* lpWindowName, uint dwStyle, + int x, int y, int nWidth, int nHeight, + IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int ShowWindow(IntPtr hWnd, int nCmdShow); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int UpdateWindow(IntPtr hWnd); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int DestroyWindow(IntPtr hWnd); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern void PostQuitMessage(int nExitCode); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern nint DefWindowProcW(IntPtr hWnd, uint msg, nuint wParam, nint lParam); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int GetMessageW(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int TranslateMessage(ref MSG lpMsg); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern nint DispatchMessageW(ref MSG lpMsg); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int InvalidateRect(IntPtr hWnd, IntPtr lpRect, int bErase); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int GetClientRect(IntPtr hWnd, out RECT lpRect); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern IntPtr BeginPaint(IntPtr hWnd, out PAINTSTRUCT lpPaint); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int EndPaint(IntPtr hWnd, ref PAINTSTRUCT lpPaint); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern IntPtr LoadCursorW(IntPtr hInstance, IntPtr lpCursorName); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern IntPtr SetCursor(IntPtr hCursor); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern IntPtr LoadIconW(IntPtr hInstance, IntPtr lpIconName); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern uint GetDpiForWindow(IntPtr hwnd); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int GetSystemMetrics(int nIndex); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int TrackMouseEvent(ref TRACKMOUSEEVENT lpEventTrack); + + [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern int MessageBoxW(IntPtr hWnd, string lpText, string lpCaption, uint uType); + + [DllImport("dwmapi.dll", ExactSpelling = true)] + public static extern int DwmSetWindowAttribute(IntPtr hwnd, uint dwAttribute, void* pvAttribute, uint cbAttribute); + + [DllImport("gdi32.dll", ExactSpelling = true)] + public static extern IntPtr CreateCompatibleDC(IntPtr hdc); + + [DllImport("gdi32.dll", ExactSpelling = true)] + public static extern int DeleteDC(IntPtr hdc); + + [DllImport("gdi32.dll", ExactSpelling = true)] + public static extern IntPtr CreateDIBSection(IntPtr hdc, ref BITMAPINFOHEADER pbmi, uint usage, out IntPtr ppvBits, IntPtr hSection, uint offset); + + [DllImport("gdi32.dll", ExactSpelling = true)] + public static extern IntPtr SelectObject(IntPtr hdc, IntPtr h); + + [DllImport("gdi32.dll", ExactSpelling = true)] + public static extern int DeleteObject(IntPtr ho); + + [DllImport("gdi32.dll", ExactSpelling = true)] + public static extern int BitBlt(IntPtr hdc, int x, int y, int cx, int cy, IntPtr hdcSrc, int x1, int y1, uint rop); + + [DllImport("shell32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern IntPtr ShellExecuteW(IntPtr hwnd, string lpOperation, string lpFile, string? lpParameters, string? lpDirectory, int nShowCmd); + + [DllImport("ole32.dll", ExactSpelling = true)] + public static extern int CoInitializeEx(IntPtr pvReserved, uint dwCoInit); + + [DllImport("ole32.dll", ExactSpelling = true)] + public static extern void CoUninitialize(); + + [DllImport("ole32.dll", ExactSpelling = true)] + public static extern int CoCreateInstance(ref Guid rclsid, IntPtr pUnkOuter, uint dwClsContext, ref Guid riid, out void* ppv); + + // GDI+ + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdiplusStartup(out nuint token, ref GdiplusStartupInput input, IntPtr output); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern void GdiplusShutdown(nuint token); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipCreateFromHDC(IntPtr hdc, out IntPtr graphics); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDeleteGraphics(IntPtr graphics); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipSetSmoothingMode(IntPtr graphics, int smoothingMode); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipSetPixelOffsetMode(IntPtr graphics, int pixelOffsetMode); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipSetTextRenderingHint(IntPtr graphics, int mode); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipGraphicsClear(IntPtr graphics, uint color); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipCreateSolidFill(uint color, out IntPtr brush); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDeleteBrush(IntPtr brush); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipCreatePen1(uint color, float width, int unit, out IntPtr pen); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipSetPenLineCap197819(IntPtr pen, int startCap, int endCap, int dashCap); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipSetPenLineJoin(IntPtr pen, int lineJoin); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDeletePen(IntPtr pen); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDrawLine(IntPtr graphics, IntPtr pen, float x1, float y1, float x2, float y2); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipFillRectangle(IntPtr graphics, IntPtr brush, float x, float y, float width, float height); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipCreatePath(int brushMode, out IntPtr path); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDeletePath(IntPtr path); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipAddPathArc(IntPtr path, float x, float y, float width, float height, float startAngle, float sweepAngle); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipClosePathFigure(IntPtr path); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipFillPath(IntPtr graphics, IntPtr brush, IntPtr path); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDrawPath(IntPtr graphics, IntPtr pen, IntPtr path); + + [DllImport("gdiplus.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern int GdipCreateFontFamilyFromName(string name, IntPtr fontCollection, out IntPtr fontFamily); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDeleteFontFamily(IntPtr fontFamily); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipCreateFont(IntPtr fontFamily, float emSize, int style, int unit, out IntPtr font); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDeleteFont(IntPtr font); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipCreateStringFormat(int formatAttributes, int language, out IntPtr format); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDeleteStringFormat(IntPtr format); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipSetStringFormatAlign(IntPtr format, int align); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipSetStringFormatLineAlign(IntPtr format, int align); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipSetStringFormatTrimming(IntPtr format, int trimming); + + [DllImport("gdiplus.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern int GdipDrawString(IntPtr graphics, string str, int length, IntPtr font, ref RectF layoutRect, IntPtr stringFormat, IntPtr brush); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipCreateBitmapFromScan0(int width, int height, int stride, int format, IntPtr scan0, out IntPtr bitmap); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDisposeImage(IntPtr image); + + [DllImport("gdiplus.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern int GdipSaveImageToFile(IntPtr image, string filename, ref Guid clsidEncoder, IntPtr encoderParams); + + // NativeAOT COM wrapper for creating standard Windows .lnk shortcuts + public static void CreateShortcut(string shortcutPath, string targetExePath, string workingDir, string description) + { + string? parentDir = Path.GetDirectoryName(shortcutPath); + if (!string.IsNullOrEmpty(parentDir) && !Directory.Exists(parentDir)) + { + Directory.CreateDirectory(parentDir); + } + + Guid clsidShellLink = new Guid("00021401-0000-0000-C000-000000000046"); + Guid iidShellLinkW = new Guid("000214F9-0000-0000-C000-000000000046"); + Guid iidPersistFile = new Guid("0000010b-0000-0000-C000-000000000046"); + + void* pShellLink = null; + if (CoCreateInstance(ref clsidShellLink, IntPtr.Zero, 1 /* CLSCTX_INPROC_SERVER */, ref iidShellLinkW, out pShellLink) < 0 || pShellLink == null) + { + return; + } + + try + { + void** vtbl = *(void***)pShellLink; + var setDescription = (delegate* unmanaged[Stdcall])vtbl[7]; + var setWorkingDir = (delegate* unmanaged[Stdcall])vtbl[9]; + var setIconLocation = (delegate* unmanaged[Stdcall])vtbl[17]; + var setPath = (delegate* unmanaged[Stdcall])vtbl[20]; + var queryInterface = (delegate* unmanaged[Stdcall])vtbl[0]; + + fixed (char* pTarget = targetExePath) + fixed (char* pWorkDir = workingDir) + fixed (char* pDesc = description) + { + setPath(pShellLink, pTarget); + setWorkingDir(pShellLink, pWorkDir); + setDescription(pShellLink, pDesc); + setIconLocation(pShellLink, pTarget, 0); + } + + void* pPersistFile = null; + if (queryInterface(pShellLink, &iidPersistFile, &pPersistFile) >= 0 && pPersistFile != null) + { + try + { + void** pfVtbl = *(void***)pPersistFile; + var save = (delegate* unmanaged[Stdcall])pfVtbl[6]; + fixed (char* pLnk = shortcutPath) + { + save(pPersistFile, pLnk, 1); + } + } + finally + { + var releasePf = (delegate* unmanaged[Stdcall])(*(void***)pPersistFile)[2]; + releasePf(pPersistFile); + } + } + } + finally + { + var releaseSl = (delegate* unmanaged[Stdcall])(*(void***)pShellLink)[2]; + releaseSl(pShellLink); + } + } + } + + internal sealed unsafe class InstallerWindow + { + public static InstallerWindow? Instance; + + private const string AppDisplayName = "Microsoft 365 Offline Image Downloader"; + private const string AppVersion = "1.0.0"; + private const string UninstallRegSubKey = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\M365IsoDownloader"; + + private IntPtr _hwnd; + private IntPtr _fontFamily; + private IntPtr _cursorArrow; + private IntPtr _cursorHand; + private float _dpiScale = 1.0f; + + private readonly string _installDir; + private bool _createStartMenuShortcut = true; + private bool _createDesktopShortcut = true; + private bool _launchAfterInstall = true; + private bool _installedSuccessfully; + private string _statusMessage = "Ready to install to your user profile (no administrator rights required)."; + + private SetupNative.RectF _cbStartMenuRect; + private SetupNative.RectF _cbDesktopRect; + private SetupNative.RectF _cbLaunchRect; + private SetupNative.RectF _primaryBtnRect; + private SetupNative.RectF _cancelBtnRect; + + private int _hoveredId = -1; + private int _pressedId = -1; + private bool _mouseDown; + private bool _trackingMouse; + + public InstallerWindow() + { + string localPrograms = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs"); + _installDir = Path.Combine(localPrograms, "M365IsoDownloader"); + } + + private void EnsureFont() + { + if (_fontFamily == IntPtr.Zero) + { + if (SetupNative.GdipCreateFontFamilyFromName("Segoe UI", IntPtr.Zero, out _fontFamily) != 0 || _fontFamily == IntPtr.Zero) + { + SetupNative.GdipCreateFontFamilyFromName("Arial", IntPtr.Zero, out _fontFamily); + } + } + } + + public int RunPreviewPng(string outPath) + { + EnsureFont(); + int w = 560, h = 410; + IntPtr memDc = SetupNative.CreateCompatibleDC(IntPtr.Zero); + SetupNative.BITMAPINFOHEADER bmi = new SetupNative.BITMAPINFOHEADER + { + biSize = (uint)sizeof(SetupNative.BITMAPINFOHEADER), + biWidth = w, + biHeight = -h, + biPlanes = 1, + biBitCount = 32 + }; + IntPtr hDib = SetupNative.CreateDIBSection(memDc, ref bmi, 0, out IntPtr bits, IntPtr.Zero, 0); + IntPtr oldBmp = SetupNative.SelectObject(memDc, hDib); + + if (SetupNative.GdipCreateFromHDC(memDc, out IntPtr g) == 0 && g != IntPtr.Zero) + { + Paint(g, w, h, 1.0f); + SetupNative.GdipDeleteGraphics(g); + } + + if (SetupNative.GdipCreateBitmapFromScan0(w, h, w * 4, 0x00022009, bits, out IntPtr gdipBmp) == 0 && gdipBmp != IntPtr.Zero) + { + Guid pngEncoder = new Guid("557CF406-1A04-11D3-9A73-0000F81EF32E"); + string? dir = Path.GetDirectoryName(outPath); + if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) Directory.CreateDirectory(dir); + SetupNative.GdipSaveImageToFile(gdipBmp, outPath, ref pngEncoder, IntPtr.Zero); + SetupNative.GdipDisposeImage(gdipBmp); + } + + SetupNative.SelectObject(memDc, oldBmp); + SetupNative.DeleteObject(hDib); + SetupNative.DeleteDC(memDc); + return 0; + } + + public static int RunUninstall(bool silent) + { + string localPrograms = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs"); + string installDir = Path.Combine(localPrograms, "M365IsoDownloader"); + + if (!silent) + { + int confirm = SetupNative.MessageBoxW( + IntPtr.Zero, + "Uninstall Microsoft 365 Offline Image Downloader from your computer?\n\n(Any downloaded .img files in your Downloads folder will be kept.)", + "Uninstall Microsoft 365 Offline Image Downloader", + SetupNative.MB_YESNO | SetupNative.MB_ICONQUESTION); + if (confirm != SetupNative.IDYES) return 0; + } + + try + { + foreach (Process proc in Process.GetProcessesByName("M365IsoDownloader")) + { + try { proc.Kill(); proc.WaitForExit(2000); } catch { } + } + + string startMenuLnk = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), AppDisplayName + ".lnk"); + string desktopLnk = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), AppDisplayName + ".lnk"); + if (File.Exists(startMenuLnk)) File.Delete(startMenuLnk); + if (File.Exists(desktopLnk)) File.Delete(desktopLnk); + + Registry.CurrentUser.DeleteSubKeyTree(UninstallRegSubKey, throwOnMissingSubKey: false); + + string appExe = Path.Combine(installDir, "M365IsoDownloader.exe"); + if (File.Exists(appExe)) File.Delete(appExe); + + // Schedule self-cleanup of Uninstall.exe and folder after process exits + if (Directory.Exists(installDir)) + { + ProcessStartInfo psi = new ProcessStartInfo + { + FileName = "cmd.exe", + Arguments = $"/C ping 127.0.0.1 -n 2 > nul & rmdir /S /Q \"{installDir}\"", + CreateNoWindow = true, + UseShellExecute = false + }; + Process.Start(psi); + } + + if (!silent) + { + SetupNative.MessageBoxW(IntPtr.Zero, AppDisplayName + " has been uninstalled.", "Uninstall Complete", SetupNative.MB_OK | SetupNative.MB_ICONINFORMATION); + } + return 0; + } + catch (Exception ex) + { + if (!silent) + { + SetupNative.MessageBoxW(IntPtr.Zero, "Uninstall encountered an error:\n" + ex.Message, "Uninstall Error", SetupNative.MB_OK | SetupNative.MB_ICONERROR); + } + return 1; + } + } + + public int RunGui() + { + EnsureFont(); + _cursorArrow = SetupNative.LoadCursorW(IntPtr.Zero, (IntPtr)SetupNative.IDC_ARROW); + _cursorHand = SetupNative.LoadCursorW(IntPtr.Zero, (IntPtr)SetupNative.IDC_HAND); + + IntPtr hInstance = SetupNative.GetModuleHandleW(null); + IntPtr hIcon = SetupNative.LoadIconW(hInstance, (IntPtr)32512); + if (hIcon == IntPtr.Zero) hIcon = SetupNative.LoadIconW(IntPtr.Zero, (IntPtr)32512); + + fixed (char* cls = "M365IsoDownloaderSetupWnd") + fixed (char* title = "Microsoft 365 Offline Image Downloader Setup") + { + SetupNative.WNDCLASSEXW wc = new SetupNative.WNDCLASSEXW + { + cbSize = (uint)sizeof(SetupNative.WNDCLASSEXW), + style = SetupNative.CS_HREDRAW | SetupNative.CS_VREDRAW, + lpfnWndProc = &StaticWndProc, + hInstance = hInstance, + hIcon = hIcon, + hIconSm = hIcon, + hCursor = _cursorArrow, + lpszClassName = cls + }; + SetupNative.RegisterClassExW(ref wc); + + int sw = SetupNative.GetSystemMetrics(0); + int sh = SetupNative.GetSystemMetrics(1); + int winW = 580, winH = 445; + + _hwnd = SetupNative.CreateWindowExW( + 0, cls, title, + SetupNative.WS_OVERLAPPED | SetupNative.WS_CAPTION | SetupNative.WS_SYSMENU | SetupNative.WS_MINIMIZEBOX, + Math.Max(40, (sw - winW) / 2), Math.Max(40, (sh - winH) / 2), + winW, winH, + IntPtr.Zero, IntPtr.Zero, hInstance, IntPtr.Zero); + + if (_hwnd == IntPtr.Zero) return 1; + + uint dpi = SetupNative.GetDpiForWindow(_hwnd); + if (dpi > 0) _dpiScale = dpi / 96.0f; + if (Math.Abs(_dpiScale - 1.0f) > 0.01f) + { + int scaledW = (int)Math.Round(winW * _dpiScale); + int scaledH = (int)Math.Round(winH * _dpiScale); + SetupNative.SetWindowPos(_hwnd, IntPtr.Zero, Math.Max(20, (sw - scaledW) / 2), Math.Max(20, (sh - scaledH) / 2), scaledW, scaledH, 0x0004); + } + + int dark = 0; + SetupNative.DwmSetWindowAttribute(_hwnd, 20, &dark, sizeof(int)); + int round = 2; + SetupNative.DwmSetWindowAttribute(_hwnd, 33, &round, sizeof(int)); + uint captionCol = 0x00FFFFFF; + SetupNative.DwmSetWindowAttribute(_hwnd, 35, &captionCol, sizeof(uint)); + + SetupNative.ShowWindow(_hwnd, SetupNative.SW_SHOW); + SetupNative.UpdateWindow(_hwnd); + + while (SetupNative.GetMessageW(out SetupNative.MSG msg, IntPtr.Zero, 0, 0) > 0) + { + SetupNative.TranslateMessage(ref msg); + SetupNative.DispatchMessageW(ref msg); + } + } + return 0; + } + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])] + private static nint StaticWndProc(IntPtr hwnd, uint msg, nuint wParam, nint lParam) + { + return Instance != null + ? Instance.HandleMessage(hwnd, msg, wParam, lParam) + : SetupNative.DefWindowProcW(hwnd, msg, wParam, lParam); + } + + private nint HandleMessage(IntPtr hwnd, uint msg, nuint wParam, nint lParam) + { + switch (msg) + { + case SetupNative.WM_ERASEBKGND: + return 1; + + case SetupNative.WM_DPICHANGED: + { + uint dpi = (uint)(wParam & 0xFFFF); + if (dpi > 0) _dpiScale = dpi / 96.0f; + SetupNative.RECT* rc = (SetupNative.RECT*)lParam; + SetupNative.SetWindowPos(hwnd, IntPtr.Zero, rc->Left, rc->Top, rc->Right - rc->Left, rc->Bottom - rc->Top, 0x0014); + SetupNative.InvalidateRect(hwnd, IntPtr.Zero, 0); + return 0; + } + + case SetupNative.WM_SETCURSOR: + if (((int)lParam & 0xFFFF) == 1) + { + SetupNative.SetCursor(_hoveredId >= 0 ? _cursorHand : _cursorArrow); + return 1; + } + break; + + case SetupNative.WM_MOUSEMOVE: + { + if (!_trackingMouse) + { + SetupNative.TRACKMOUSEEVENT tme = new SetupNative.TRACKMOUSEEVENT + { + cbSize = (uint)sizeof(SetupNative.TRACKMOUSEEVENT), + dwFlags = 2, + hwndTrack = hwnd + }; + SetupNative.TrackMouseEvent(ref tme); + _trackingMouse = true; + } + float mx = (short)(lParam & 0xFFFF); + float my = (short)((lParam >> 16) & 0xFFFF); + int hit = HitTest(mx, my); + if (hit != _hoveredId) + { + _hoveredId = hit; + SetupNative.SetCursor(_hoveredId >= 0 ? _cursorHand : _cursorArrow); + SetupNative.InvalidateRect(hwnd, IntPtr.Zero, 0); + } + return 0; + } + + case SetupNative.WM_MOUSELEAVE: + _trackingMouse = false; + _mouseDown = false; + _pressedId = -1; + if (_hoveredId != -1) { _hoveredId = -1; SetupNative.InvalidateRect(hwnd, IntPtr.Zero, 0); } + return 0; + + case SetupNative.WM_LBUTTONDOWN: + { + float mx = (short)(lParam & 0xFFFF); + float my = (short)((lParam >> 16) & 0xFFFF); + _mouseDown = true; + _pressedId = HitTest(mx, my); + SetupNative.InvalidateRect(hwnd, IntPtr.Zero, 0); + return 0; + } + + case SetupNative.WM_LBUTTONUP: + { + float mx = (short)(lParam & 0xFFFF); + float my = (short)((lParam >> 16) & 0xFFFF); + int hit = HitTest(mx, my); + int wasPressed = _pressedId; + _mouseDown = false; + _pressedId = -1; + SetupNative.InvalidateRect(hwnd, IntPtr.Zero, 0); + if (hit >= 0 && hit == wasPressed) OnClick(hit); + return 0; + } + + case SetupNative.WM_PAINT: + { + IntPtr hdc = SetupNative.BeginPaint(hwnd, out SetupNative.PAINTSTRUCT ps); + SetupNative.GetClientRect(hwnd, out SetupNative.RECT rc); + int w = Math.Max(1, rc.Right - rc.Left); + int h = Math.Max(1, rc.Bottom - rc.Top); + + IntPtr memDc = SetupNative.CreateCompatibleDC(hdc); + SetupNative.BITMAPINFOHEADER bmi = new SetupNative.BITMAPINFOHEADER + { + biSize = (uint)sizeof(SetupNative.BITMAPINFOHEADER), + biWidth = w, + biHeight = -h, + biPlanes = 1, + biBitCount = 32 + }; + IntPtr hDib = SetupNative.CreateDIBSection(memDc, ref bmi, 0, out _, IntPtr.Zero, 0); + IntPtr old = SetupNative.SelectObject(memDc, hDib); + + if (SetupNative.GdipCreateFromHDC(memDc, out IntPtr g) == 0 && g != IntPtr.Zero) + { + Paint(g, w, h, _dpiScale); + SetupNative.GdipDeleteGraphics(g); + } + + SetupNative.BitBlt(hdc, 0, 0, w, h, memDc, 0, 0, SetupNative.SRCCOPY); + SetupNative.SelectObject(memDc, old); + SetupNative.DeleteObject(hDib); + SetupNative.DeleteDC(memDc); + SetupNative.EndPaint(hwnd, ref ps); + return 0; + } + + case SetupNative.WM_CLOSE: + SetupNative.DestroyWindow(hwnd); + return 0; + + case SetupNative.WM_DESTROY: + SetupNative.PostQuitMessage(0); + return 0; + } + return SetupNative.DefWindowProcW(hwnd, msg, wParam, lParam); + } + + private int HitTest(float x, float y) + { + if (!_installedSuccessfully) + { + if (_cbStartMenuRect.Contains(x, y)) return 1; + if (_cbDesktopRect.Contains(x, y)) return 2; + } + if (_cbLaunchRect.Contains(x, y)) return 3; + if (_primaryBtnRect.Contains(x, y)) return 4; + if (_cancelBtnRect.Contains(x, y)) return 5; + return -1; + } + + private void OnClick(int id) + { + switch (id) + { + case 1: + _createStartMenuShortcut = !_createStartMenuShortcut; + SetupNative.InvalidateRect(_hwnd, IntPtr.Zero, 0); + break; + case 2: + _createDesktopShortcut = !_createDesktopShortcut; + SetupNative.InvalidateRect(_hwnd, IntPtr.Zero, 0); + break; + case 3: + _launchAfterInstall = !_launchAfterInstall; + SetupNative.InvalidateRect(_hwnd, IntPtr.Zero, 0); + break; + case 4: + if (!_installedSuccessfully) + { + PerformInstallation(); + } + else + { + if (_launchAfterInstall) + { + string appExe = Path.Combine(_installDir, "M365IsoDownloader.exe"); + if (File.Exists(appExe)) + { + SetupNative.ShellExecuteW(_hwnd, "open", appExe, null, _installDir, SetupNative.SW_SHOW); + } + } + SetupNative.DestroyWindow(_hwnd); + } + break; + case 5: + SetupNative.DestroyWindow(_hwnd); + break; + } + } + + private void PerformInstallation() + { + try + { + foreach (Process proc in Process.GetProcessesByName("M365IsoDownloader")) + { + try { proc.Kill(); proc.WaitForExit(2000); } catch { } + } + + Directory.CreateDirectory(_installDir); + string targetExe = Path.Combine(_installDir, "M365IsoDownloader.exe"); + + using (Stream? resStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("AppPayload.gz")) + { + if (resStream == null) throw new InvalidOperationException("Embedded application payload was not found."); + using GZipStream gz = new GZipStream(resStream, CompressionMode.Decompress); + using FileStream outFs = new FileStream(targetExe, FileMode.Create, FileAccess.Write, FileShare.None); + gz.CopyTo(outFs); + } + + // Copy installer binary as Uninstall.exe for Windows Settings -> Installed Apps support + string? currentSetupExe = Environment.ProcessPath; + string uninstallExe = Path.Combine(_installDir, "Uninstall.exe"); + if (!string.IsNullOrEmpty(currentSetupExe) && File.Exists(currentSetupExe)) + { + File.Copy(currentSetupExe, uninstallExe, overwrite: true); + } + + if (_createStartMenuShortcut) + { + string startMenuLnk = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), AppDisplayName + ".lnk"); + SetupNative.CreateShortcut(startMenuLnk, targetExe, _installDir, "Check and download official Microsoft 365 en-US offline .img installers"); + } + + if (_createDesktopShortcut) + { + string desktopLnk = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), AppDisplayName + ".lnk"); + SetupNative.CreateShortcut(desktopLnk, targetExe, _installDir, "Check and download official Microsoft 365 en-US offline .img installers"); + } + + using (RegistryKey? key = Registry.CurrentUser.CreateSubKey(UninstallRegSubKey)) + { + if (key != null) + { + long sizeKb = new FileInfo(targetExe).Length / 1024; + key.SetValue("DisplayName", AppDisplayName); + key.SetValue("DisplayVersion", AppVersion); + key.SetValue("Publisher", "M365 Tools"); + key.SetValue("DisplayIcon", targetExe); + key.SetValue("InstallLocation", _installDir); + key.SetValue("UninstallString", $"\"{uninstallExe}\" --uninstall"); + key.SetValue("QuietUninstallString", $"\"{uninstallExe}\" --uninstall --silent"); + key.SetValue("EstimatedSize", (int)sizeKb, RegistryValueKind.DWord); + key.SetValue("NoModify", 1, RegistryValueKind.DWord); + key.SetValue("NoRepair", 1, RegistryValueKind.DWord); + } + } + + _installedSuccessfully = true; + _statusMessage = "Installation complete! Registered in Start Menu and Windows Installed Apps."; + SetupNative.InvalidateRect(_hwnd, IntPtr.Zero, 0); + } + catch (Exception ex) + { + SetupNative.MessageBoxW(_hwnd, "Installation failed:\n" + ex.Message, "Setup Error", SetupNative.MB_OK | SetupNative.MB_ICONERROR); + } + } + + private void Paint(IntPtr g, int width, int height, float s) + { + SetupNative.GdipSetSmoothingMode(g, 4); + SetupNative.GdipSetPixelOffsetMode(g, 4); + SetupNative.GdipSetTextRenderingHint(g, 5); + SetupNative.GdipGraphicsClear(g, 0xFFF3F5F8); + + IntPtr fTitle = CreateFont(17.5f * s, true); + IntPtr fSub = CreateFont(12.2f * s, false); + IntPtr fSemi = CreateFont(12.8f * s, true); + IntPtr fBody = CreateFont(12.5f * s, false); + IntPtr fSmall = CreateFont(11.6f * s, false); + + try + { + float padX = 24f * s; + float headerH = 78f * s; + float footerH = 62f * s; + + // Header + FillRect(g, 0, 0, width, headerH, 0xFFFFFFFF); + DrawLine(g, 0, headerH, width, headerH, 0xFFE2E8F0, 1f * s); + + float iconBox = 44f * s; + float iconY = (headerH - iconBox) * 0.5f; + FillRoundRect(g, new SetupNative.RectF(padX, iconY, iconBox, iconBox), 10f * s, _installedSuccessfully ? 0xFF0F7B0F : 0xFF0067C0); + if (_installedSuccessfully) + { + DrawCheckmark(g, new SetupNative.RectF(padX + iconBox * 0.18f, iconY + iconBox * 0.18f, iconBox * 0.64f, iconBox * 0.64f), 2.8f * s); + } + else + { + DrawDownloadGlyph(g, padX + iconBox * 0.5f, iconY + iconBox * 0.5f, iconBox * 0.48f, 2.3f * s); + } + + float titleX = padX + iconBox + 14f * s; + float titleW = width - titleX - padX; + DrawText(g, _installedSuccessfully ? "Installation Complete" : "Install Microsoft 365 Image Downloader", fTitle, new SetupNative.RectF(titleX, 16f * s, titleW, 24f * s), 0xFF0F172A, 0, true); + DrawText(g, "Version 1.0.0 • .NET NativeAOT (win-x64) • en-US Offline Installer Utility", fSub, new SetupNative.RectF(titleX, 42f * s, titleW, 20f * s), 0xFF64748B, 0, true); + + // Main Card + float cardY = headerH + 18f * s; + float cardH = height - footerH - cardY - 18f * s; + SetupNative.RectF card = new SetupNative.RectF(padX, cardY, width - 2 * padX, cardH); + FillRoundRect(g, card, 10f * s, 0xFFFFFFFF); + StrokeRoundRect(g, card, 10f * s, 0xFFE2E8F0, 1f * s); + + float cx = card.X + 18f * s; + float cw = card.Width - 36f * s; + float cy = card.Y + 16f * s; + + DrawText(g, "Destination Folder:", fSemi, new SetupNative.RectF(cx, cy, cw, 20f * s), 0xFF334155, 0, true); + cy += 24f * s; + + SetupNative.RectF pathRect = new SetupNative.RectF(cx, cy, cw, 32f * s); + FillRoundRect(g, pathRect, 6f * s, 0xFFF8FAFC); + StrokeRoundRect(g, pathRect, 6f * s, 0xFFCBD5E1, 1f * s); + DrawText(g, _installDir, fBody, new SetupNative.RectF(cx + 10f * s, cy, cw - 20f * s, 32f * s), 0xFF1E293B, 0, true, pathEllipsis: true); + cy += 46f * s; + + if (!_installedSuccessfully) + { + _cbStartMenuRect = new SetupNative.RectF(cx, cy, cw, 24f * s); + DrawOptionRow(g, _cbStartMenuRect, _createStartMenuShortcut, "Create Start Menu shortcut", fBody, _hoveredId == 1, s); + cy += 32f * s; + + _cbDesktopRect = new SetupNative.RectF(cx, cy, cw, 24f * s); + DrawOptionRow(g, _cbDesktopRect, _createDesktopShortcut, "Create Desktop shortcut", fBody, _hoveredId == 2, s); + cy += 32f * s; + } + + _cbLaunchRect = new SetupNative.RectF(cx, cy, cw, 24f * s); + DrawOptionRow(g, _cbLaunchRect, _launchAfterInstall, "Launch Microsoft 365 Image Downloader when finished", fBody, _hoveredId == 3, s); + + DrawText(g, _statusMessage, fSmall, new SetupNative.RectF(cx, card.Y + card.Height - 28f * s, cw, 18f * s), _installedSuccessfully ? 0xFF0F7B0F : 0xFF64748B, 0, true); + + // Footer + float footerY = height - footerH; + FillRect(g, 0, footerY, width, footerH, 0xFFFFFFFF); + DrawLine(g, 0, footerY, width, footerY, 0xFFE2E8F0, 1f * s); + + float btnH = 34f * s; + float btnY = footerY + (footerH - btnH) * 0.5f; + float primW = 128f * s; + float cancelW = 92f * s; + + _primaryBtnRect = new SetupNative.RectF(width - padX - primW, btnY, primW, btnH); + _cancelBtnRect = new SetupNative.RectF(_primaryBtnRect.X - 10f * s - cancelW, btnY, cancelW, btnH); + + if (!_installedSuccessfully) + { + DrawButton(g, _cancelBtnRect, "Cancel", fSemi, false, _hoveredId == 5, _mouseDown && _pressedId == 5, s); + DrawButton(g, _primaryBtnRect, "Install Now", fSemi, true, _hoveredId == 4, _mouseDown && _pressedId == 4, s); + } + else + { + _cancelBtnRect = default; + DrawButton(g, _primaryBtnRect, _launchAfterInstall ? "Finish & Launch" : "Finish", fSemi, true, _hoveredId == 4, _mouseDown && _pressedId == 4, s); + } + } + finally + { + SetupNative.GdipDeleteFont(fTitle); + SetupNative.GdipDeleteFont(fSub); + SetupNative.GdipDeleteFont(fSemi); + SetupNative.GdipDeleteFont(fBody); + SetupNative.GdipDeleteFont(fSmall); + } + } + + private IntPtr CreateFont(float px, bool bold) + { + SetupNative.GdipCreateFont(_fontFamily, px, bold ? 1 : 0, 2, out IntPtr f); + return f; + } + + private static void DrawOptionRow(IntPtr g, SetupNative.RectF row, bool isChecked, string label, IntPtr font, bool hovered, float s) + { + float box = 19f * s; + SetupNative.RectF cb = new SetupNative.RectF(row.X, row.Y + (row.Height - box) * 0.5f, box, box); + if (isChecked) + { + FillRoundRect(g, cb, 5f * s, hovered ? 0xFF005A9E : 0xFF0067C0); + DrawCheckmark(g, cb, 2.0f * s); + } + else + { + FillRoundRect(g, cb, 5f * s, hovered ? 0xFFF1F5F9 : 0xFFFFFFFF); + StrokeRoundRect(g, cb, 5f * s, hovered ? 0xFF64748B : 0xFF94A3B8, 1.4f * s); + } + DrawText(g, label, font, new SetupNative.RectF(row.X + box + 10f * s, row.Y, row.Width - box - 10f * s, row.Height), 0xFF1E293B, 0, true); + } + + private static void DrawCheckmark(IntPtr g, SetupNative.RectF r, float strokeW) + { + if (SetupNative.GdipCreatePen1(0xFFFFFFFF, strokeW, 2, out IntPtr pen) == 0) + { + SetupNative.GdipSetPenLineCap197819(pen, 2, 2, 2); + SetupNative.GdipSetPenLineJoin(pen, 2); + SetupNative.GdipDrawLine(g, pen, r.X + r.Width * 0.24f, r.Y + r.Height * 0.52f, r.X + r.Width * 0.43f, r.Y + r.Height * 0.72f); + SetupNative.GdipDrawLine(g, pen, r.X + r.Width * 0.43f, r.Y + r.Height * 0.72f, r.X + r.Width * 0.77f, r.Y + r.Height * 0.30f); + SetupNative.GdipDeletePen(pen); + } + } + + private static void DrawDownloadGlyph(IntPtr g, float cx, float cy, float size, float strokeW) + { + if (SetupNative.GdipCreatePen1(0xFFFFFFFF, strokeW, 2, out IntPtr pen) == 0) + { + SetupNative.GdipSetPenLineCap197819(pen, 2, 2, 2); + SetupNative.GdipSetPenLineJoin(pen, 2); + float half = size * 0.5f; + SetupNative.GdipDrawLine(g, pen, cx, cy - half * 0.85f, cx, cy + half * 0.35f); + SetupNative.GdipDrawLine(g, pen, cx - half * 0.58f, cy - half * 0.12f, cx, cy + half * 0.35f); + SetupNative.GdipDrawLine(g, pen, cx + half * 0.58f, cy - half * 0.12f, cx, cy + half * 0.35f); + SetupNative.GdipDrawLine(g, pen, cx - half * 0.72f, cy + half * 0.82f, cx + half * 0.72f, cy + half * 0.82f); + SetupNative.GdipDeletePen(pen); + } + } + + private static void DrawButton(IntPtr g, SetupNative.RectF r, string text, IntPtr font, bool primary, bool hovered, bool pressed, float s) + { + uint bg = primary + ? (pressed ? 0xFF004578u : (hovered ? 0xFF005A9Eu : 0xFF0067C0u)) + : (pressed ? 0xFFE2E8F0u : (hovered ? 0xFFF8FAFCu : 0xFFFFFFFFu)); + uint fg = primary ? 0xFFFFFFFFu : 0xFF1E293Bu; + FillRoundRect(g, r, 6f * s, bg); + if (!primary) StrokeRoundRect(g, r, 6f * s, hovered ? 0xFF94A3B8u : 0xFFCBD5E1u, 1f * s); + DrawText(g, text, font, r, fg, 1, true); + } + + private static void FillRect(IntPtr g, float x, float y, float w, float h, uint argb) + { + if (SetupNative.GdipCreateSolidFill(argb, out IntPtr b) == 0) + { + SetupNative.GdipFillRectangle(g, b, x, y, w, h); + SetupNative.GdipDeleteBrush(b); + } + } + + private static void DrawLine(IntPtr g, float x1, float y1, float x2, float y2, uint argb, float w) + { + if (SetupNative.GdipCreatePen1(argb, w, 2, out IntPtr p) == 0) + { + SetupNative.GdipDrawLine(g, p, x1, y1, x2, y2); + SetupNative.GdipDeletePen(p); + } + } + + private static IntPtr CreateRoundedPath(SetupNative.RectF r, float radius) + { + SetupNative.GdipCreatePath(0, out IntPtr path); + float d = Math.Min(radius * 2f, Math.Min(r.Width, r.Height)); + SetupNative.GdipAddPathArc(path, r.X, r.Y, d, d, 180f, 90f); + SetupNative.GdipAddPathArc(path, r.X + r.Width - d, r.Y, d, d, 270f, 90f); + SetupNative.GdipAddPathArc(path, r.X + r.Width - d, r.Y + r.Height - d, d, d, 0f, 90f); + SetupNative.GdipAddPathArc(path, r.X, r.Y + r.Height - d, d, d, 90f, 90f); + SetupNative.GdipClosePathFigure(path); + return path; + } + + private static void FillRoundRect(IntPtr g, SetupNative.RectF r, float radius, uint argb) + { + IntPtr path = CreateRoundedPath(r, radius); + if (SetupNative.GdipCreateSolidFill(argb, out IntPtr b) == 0) + { + SetupNative.GdipFillPath(g, b, path); + SetupNative.GdipDeleteBrush(b); + } + SetupNative.GdipDeletePath(path); + } + + private static void StrokeRoundRect(IntPtr g, SetupNative.RectF r, float radius, uint argb, float strokeW) + { + IntPtr path = CreateRoundedPath(r, radius); + if (SetupNative.GdipCreatePen1(argb, strokeW, 2, out IntPtr p) == 0) + { + SetupNative.GdipDrawPath(g, p, path); + SetupNative.GdipDeletePen(p); + } + SetupNative.GdipDeletePath(path); + } + + private static void DrawText(IntPtr g, string text, IntPtr font, SetupNative.RectF rect, uint argb, int align, bool vCenter, bool pathEllipsis = false) + { + SetupNative.GdipCreateStringFormat(0x00001000, 0, out IntPtr fmt); + SetupNative.GdipSetStringFormatAlign(fmt, align); + SetupNative.GdipSetStringFormatLineAlign(fmt, vCenter ? 1 : 0); + SetupNative.GdipSetStringFormatTrimming(fmt, pathEllipsis ? 5 : 3); + if (SetupNative.GdipCreateSolidFill(argb, out IntPtr b) == 0) + { + SetupNative.GdipDrawString(g, text, text.Length, font, ref rect, fmt, b); + SetupNative.GdipDeleteBrush(b); + } + SetupNative.GdipDeleteStringFormat(fmt); + } + } + + public static class SetupProgram + { + public static int Main(string[] args) + { + SetupNative.CoInitializeEx(IntPtr.Zero, 2); + SetupNative.GdiplusStartupInput input = new SetupNative.GdiplusStartupInput { GdiplusVersion = 1 }; + SetupNative.GdiplusStartup(out nuint token, ref input, IntPtr.Zero); + + try + { + if (args.Length >= 1 && string.Equals(args[0], "--uninstall", StringComparison.OrdinalIgnoreCase)) + { + bool silent = args.Length >= 2 && string.Equals(args[1], "--silent", StringComparison.OrdinalIgnoreCase); + return InstallerWindow.RunUninstall(silent); + } + + InstallerWindow win = new InstallerWindow(); + InstallerWindow.Instance = win; + + if (args.Length >= 2 && string.Equals(args[0], "--self-test-preview", StringComparison.OrdinalIgnoreCase)) + { + return win.RunPreviewPng(args[1]); + } + + return win.RunGui(); + } + finally + { + InstallerWindow.Instance = null; + if (token != 0) SetupNative.GdiplusShutdown(token); + SetupNative.CoUninitialize(); + } + } + } +} diff --git a/nuget.config b/nuget.config new file mode 100644 index 0000000..4d736c1 --- /dev/null +++ b/nuget.config @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/Program.cs b/src/Program.cs new file mode 100644 index 0000000..710de13 --- /dev/null +++ b/src/Program.cs @@ -0,0 +1,2452 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; + +namespace M365IsoDownloader +{ + internal enum EditionStatus + { + Idle, + Checking, + NotDownloaded, + ResumeAvailable, + UpToDate, + UpdateAvailable, + Queued, + Downloading, + Paused, + Error + } + + internal sealed class RemoteImageInfo + { + public string ActiveUrl = string.Empty; + public long ContentLength; + public string ETag = string.Empty; + public DateTimeOffset? LastModified; + public string BuildVersion = string.Empty; + } + + internal sealed class EditionItem + { + public string Key { get; } + public string Title { get; } + public string Subtitle { get; } + public string FileName { get; } + public string PrimaryUrl { get; } + public string FallbackUrl { get; } + + public bool IsSelected; + public EditionStatus Status = EditionStatus.Idle; + public string StatusText = "Ready"; + public uint BadgeBg = 0xFFF0F2F5; + public uint BadgeFg = 0xFF475569; + + public RemoteImageInfo? RemoteInfo; + public string RemoteVersionText = "—"; + public string RemoteDateText = "—"; + public string RemoteSizeText = "—"; + public string LocalStatusText = "Not checked yet"; + + public string LocalVersion = string.Empty; + public long LocalLength; + public long PartialLength; + public string StoredETag = string.Empty; + public bool HasLocalFile; + + public bool ShowProgress; + public double ProgressPercent; + public string ProgressDetailsText = string.Empty; + + public string PrimaryActionText = "Download"; + public bool CanPrimaryAction = true; + public bool IsBusy; + public bool PauseRequested; + public CancellationTokenSource? ActiveDownloadCts; + + public EditionItem(string key, string title, string subtitle, string fileName, bool selectedByDefault) + { + Key = key; + Title = title; + Subtitle = subtitle; + FileName = fileName; + PrimaryUrl = "https://officecdn.microsoft.com/db/492350f6-3a01-4f97-b9c0-c7c6ddf67d60/media/en-US/" + fileName; + FallbackUrl = "https://officecdn.microsoft.com/pr/492350f6-3a01-4f97-b9c0-c7c6ddf67d60/media/en-US/" + fileName; + IsSelected = selectedByDefault; + ApplyStatus(EditionStatus.Idle, "Ready"); + } + + public bool CanCancel => IsBusy && (Status == EditionStatus.Downloading || Status == EditionStatus.Queued); + + public void ApplyStatus(EditionStatus status, string? customLabel = null) + { + Status = status; + switch (status) + { + case EditionStatus.Checking: + StatusText = customLabel ?? "Checking CDN..."; + BadgeBg = 0xFFE8F1FB; + BadgeFg = 0xFF005FB8; + PrimaryActionText = "Checking..."; + CanPrimaryAction = false; + break; + case EditionStatus.UpToDate: + StatusText = customLabel ?? "Up to Date"; + BadgeBg = 0xFFDFF6DD; + BadgeFg = 0xFF0F7B0F; + PrimaryActionText = "Re-download"; + CanPrimaryAction = true; + break; + case EditionStatus.UpdateAvailable: + StatusText = customLabel ?? "Update Available"; + BadgeBg = 0xFFFFF4CE; + BadgeFg = 0xFF9D5D00; + PrimaryActionText = "Download Update"; + CanPrimaryAction = true; + break; + case EditionStatus.ResumeAvailable: + StatusText = customLabel ?? "Partial Download"; + BadgeBg = 0xFFE8F1FB; + BadgeFg = 0xFF005FB8; + PrimaryActionText = "Resume"; + CanPrimaryAction = true; + break; + case EditionStatus.Paused: + StatusText = customLabel ?? "Paused"; + BadgeBg = 0xFFFFF4CE; + BadgeFg = 0xFF9D5D00; + PrimaryActionText = "Resume"; + CanPrimaryAction = true; + break; + case EditionStatus.Queued: + StatusText = customLabel ?? "Queued"; + BadgeBg = 0xFFF0F2F5; + BadgeFg = 0xFF475569; + PrimaryActionText = "Queued"; + CanPrimaryAction = false; + break; + case EditionStatus.Downloading: + StatusText = customLabel ?? "Downloading"; + BadgeBg = 0xFFE8F1FB; + BadgeFg = 0xFF005FB8; + PrimaryActionText = "Pause"; + CanPrimaryAction = true; + break; + case EditionStatus.Error: + StatusText = customLabel ?? "Error"; + BadgeBg = 0xFFFDE7E9; + BadgeFg = 0xFFC42B1C; + PrimaryActionText = "Retry"; + CanPrimaryAction = true; + break; + case EditionStatus.NotDownloaded: + StatusText = customLabel ?? "Not Downloaded"; + BadgeBg = 0xFFF0F2F5; + BadgeFg = 0xFF475569; + PrimaryActionText = "Download"; + CanPrimaryAction = true; + break; + default: + StatusText = customLabel ?? "Ready"; + BadgeBg = 0xFFF0F2F5; + BadgeFg = 0xFF475569; + PrimaryActionText = "Download"; + CanPrimaryAction = true; + break; + } + } + } + + internal static class ImageInspector + { + private static readonly Regex BuildRegex = new Regex(@"16\.0\.\d{4,6}\.\d{4,6}", RegexOptions.CultureInvariant); + + // ISO-9660 Primary Volume Descriptor starts at byte 32768 (sector 16). + // Microsoft embeds the exact Click-to-Run build version (e.g. 16.0.17928.20148) right inside this descriptor. + private const long ProbeStartOffset = 32768; + private const int ProbeByteCount = 196608; // 192 KB covers ISO9660 + UDF volume & root descriptors + + public static string ExtractBuildFromBytes(byte[] buffer, int count) + { + if (buffer == null || count <= 0) return string.Empty; + + string ascii = Encoding.ASCII.GetString(buffer, 0, count); + string found = FindBestVersion(ascii); + if (found.Length > 0) return found; + + int evenCount = count - (count % 2); + if (evenCount > 0) + { + string utf16Le = Encoding.Unicode.GetString(buffer, 0, evenCount); + found = FindBestVersion(utf16Le); + if (found.Length > 0) return found; + + string utf16Be = Encoding.BigEndianUnicode.GetString(buffer, 0, evenCount); + found = FindBestVersion(utf16Be); + if (found.Length > 0) return found; + } + return string.Empty; + } + + private static string FindBestVersion(string text) + { + MatchCollection matches = BuildRegex.Matches(text); + Version? bestVer = null; + string bestStr = string.Empty; + foreach (Match m in matches) + { + if (Version.TryParse(m.Value, out Version? parsed) && parsed != null) + { + if (parsed.Build > 1000 && (bestVer == null || parsed > bestVer)) + { + bestVer = parsed; + bestStr = m.Value; + } + } + } + return bestStr; + } + + public static string ReadLocalImageBuild(string filePath) + { + if (!File.Exists(filePath)) return string.Empty; + try + { + using FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + if (fs.Length <= ProbeStartOffset + 128) return string.Empty; + fs.Seek(ProbeStartOffset, SeekOrigin.Begin); + int toRead = (int)Math.Min(ProbeByteCount, fs.Length - ProbeStartOffset); + byte[] buffer = new byte[toRead]; + int totalRead = 0; + while (totalRead < toRead) + { + int n = fs.Read(buffer, totalRead, toRead - totalRead); + if (n <= 0) break; + totalRead += n; + } + return ExtractBuildFromBytes(buffer, totalRead); + } + catch + { + return string.Empty; + } + } + + public static async Task QueryCdnAsync(HttpClient httpClient, string primaryUrl, string fallbackUrl, CancellationToken ct) + { + Exception? lastError = null; + string[] urls = [primaryUrl, fallbackUrl]; + + foreach (string url in urls) + { + if (string.IsNullOrEmpty(url)) continue; + try + { + RemoteImageInfo info = new RemoteImageInfo { ActiveUrl = url }; + + using (HttpRequestMessage headReq = new HttpRequestMessage(HttpMethod.Head, url)) + using (HttpResponseMessage headResp = await httpClient.SendAsync(headReq, HttpCompletionOption.ResponseHeadersRead, ct)) + { + headResp.EnsureSuccessStatusCode(); + info.ContentLength = headResp.Content.Headers.ContentLength ?? 0; + info.LastModified = headResp.Content.Headers.LastModified; + if (headResp.Headers.ETag != null) + { + info.ETag = headResp.Headers.ETag.Tag; + } + else if (headResp.Headers.TryGetValues("ETag", out IEnumerable? rawEtags)) + { + foreach (string e in rawEtags) { info.ETag = e; break; } + } + } + + try + { + using HttpRequestMessage rangeReq = new HttpRequestMessage(HttpMethod.Get, url); + rangeReq.Headers.Range = new RangeHeaderValue(ProbeStartOffset, ProbeStartOffset + ProbeByteCount - 1); + using HttpResponseMessage rangeResp = await httpClient.SendAsync(rangeReq, HttpCompletionOption.ResponseHeadersRead, ct); + if (rangeResp.StatusCode == HttpStatusCode.PartialContent || rangeResp.IsSuccessStatusCode) + { + using Stream s = await rangeResp.Content.ReadAsStreamAsync(ct); + using MemoryStream ms = new MemoryStream(ProbeByteCount); + byte[] chunk = new byte[16384]; + int read; + while (ms.Length < ProbeByteCount && + (read = await s.ReadAsync(chunk.AsMemory(0, (int)Math.Min(chunk.Length, ProbeByteCount - ms.Length)), ct)) > 0) + { + ms.Write(chunk, 0, read); + } + byte[] data = ms.ToArray(); + info.BuildVersion = ExtractBuildFromBytes(data, data.Length); + } + } + catch (OperationCanceledException) + { + throw; + } + catch + { + // Non-fatal if range probe fails; ETag + LastModified + ContentLength remain valid + } + + return info; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + lastError = ex; + } + } + + throw lastError ?? new IOException("Unable to reach Microsoft CDN."); + } + } + + internal static class MetadataStore + { + public static Dictionary ReadKeyValueFile(string path) + { + Dictionary dict = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (!File.Exists(path)) return dict; + try + { + foreach (string line in File.ReadAllLines(path, Encoding.UTF8)) + { + if (string.IsNullOrWhiteSpace(line)) continue; + int eq = line.IndexOf('='); + if (eq > 0) + { + dict[line.Substring(0, eq).Trim()] = line.Substring(eq + 1).Trim(); + } + } + } + catch { } + return dict; + } + + public static void WriteKeyValueFile(string path, Dictionary values) + { + try + { + string? dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) + { + Directory.CreateDirectory(dir); + } + StringBuilder sb = new StringBuilder(); + foreach (KeyValuePair kv in values) + { + sb.Append(kv.Key).Append('=').Append(kv.Value).AppendLine(); + } + File.WriteAllText(path, sb.ToString(), Encoding.UTF8); + } + catch { } + } + } + + internal static unsafe class Win32Native + { + public const uint WS_OVERLAPPEDWINDOW = 0x00CF0000; + public const uint WS_CLIPCHILDREN = 0x02000000; + public const uint CS_HREDRAW = 0x0002; + public const uint CS_VREDRAW = 0x0001; + + public const uint WM_DESTROY = 0x0002; + public const uint WM_SIZE = 0x0005; + public const uint WM_PAINT = 0x000F; + public const uint WM_CLOSE = 0x0010; + public const uint WM_ERASEBKGND = 0x0014; + public const uint WM_SETCURSOR = 0x0020; + public const uint WM_GETMINMAXINFO = 0x0024; + public const uint WM_MOUSEMOVE = 0x0200; + public const uint WM_LBUTTONDOWN = 0x0201; + public const uint WM_LBUTTONUP = 0x0202; + public const uint WM_MOUSELEAVE = 0x02A3; + public const uint WM_DPICHANGED = 0x02E0; + public const uint WM_APP_SYNC = 0x8001; + + public const int SW_SHOW = 5; + public const int IDC_ARROW = 32512; + public const int IDC_HAND = 32649; + public const uint SRCCOPY = 0x00CC0020; + public const uint MB_OK = 0x00000000; + public const uint MB_YESNO = 0x00000004; + public const uint MB_ICONINFORMATION = 0x00000040; + public const uint MB_ICONWARNING = 0x00000030; + public const uint MB_ICONERROR = 0x00000010; + public const uint MB_ICONQUESTION = 0x00000020; + public const int IDYES = 6; + + [StructLayout(LayoutKind.Sequential)] + public struct POINT { public int X, Y; } + + [StructLayout(LayoutKind.Sequential)] + public struct RECT { public int Left, Top, Right, Bottom; } + + [StructLayout(LayoutKind.Sequential)] + public struct MINMAXINFO + { + public POINT ptReserved; + public POINT ptMaxSize; + public POINT ptMaxPosition; + public POINT ptMinTrackSize; + public POINT ptMaxTrackSize; + } + + [StructLayout(LayoutKind.Sequential)] + public struct MSG + { + public IntPtr hwnd; + public uint message; + public nuint wParam; + public nint lParam; + public uint time; + public POINT pt; + } + + [StructLayout(LayoutKind.Sequential)] + public struct PAINTSTRUCT + { + public IntPtr hdc; + public int fErase; + public RECT rcPaint; + public int fRestore; + public int fIncUpdate; + public fixed byte rgbReserved[32]; + } + + [StructLayout(LayoutKind.Sequential)] + public struct TRACKMOUSEEVENT + { + public uint cbSize; + public uint dwFlags; + public IntPtr hwndTrack; + public uint dwHoverTime; + } + + [StructLayout(LayoutKind.Sequential)] + public struct WNDCLASSEXW + { + public uint cbSize; + public uint style; + public delegate* unmanaged[Stdcall] lpfnWndProc; + public int cbClsExtra; + public int cbWndExtra; + public IntPtr hInstance; + public IntPtr hIcon; + public IntPtr hCursor; + public IntPtr hbrBackground; + public char* lpszMenuName; + public char* lpszClassName; + public IntPtr hIconSm; + } + + [StructLayout(LayoutKind.Sequential)] + public struct BITMAPINFOHEADER + { + public uint biSize; + public int biWidth; + public int biHeight; + public ushort biPlanes; + public ushort biBitCount; + public uint biCompression; + public uint biSizeImage; + public int biXPelsPerMeter; + public int biYPelsPerMeter; + public uint biClrUsed; + public uint biClrImportant; + } + + [StructLayout(LayoutKind.Sequential)] + public struct RectF + { + public float X, Y, Width, Height; + public RectF(float x, float y, float w, float h) { X = x; Y = y; Width = w; Height = h; } + public bool Contains(float px, float py) => px >= X && px <= X + Width && py >= Y && py <= Y + Height; + } + + [StructLayout(LayoutKind.Sequential)] + public struct GdiplusStartupInput + { + public uint GdiplusVersion; + public IntPtr DebugEventCallback; + public int SuppressBackgroundThread; + public int SuppressExternalCodecs; + } + + [DllImport("kernel32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern IntPtr GetModuleHandleW(char* lpModuleName); + + [DllImport("kernel32.dll", ExactSpelling = true)] + public static extern IntPtr GlobalAlloc(uint uFlags, nuint dwBytes); + + [DllImport("kernel32.dll", ExactSpelling = true)] + public static extern IntPtr GlobalLock(IntPtr hMem); + + [DllImport("kernel32.dll", ExactSpelling = true)] + public static extern int GlobalUnlock(IntPtr hMem); + + [DllImport("kernel32.dll", ExactSpelling = true)] + public static extern IntPtr GlobalFree(IntPtr hMem); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern ushort RegisterClassExW(ref WNDCLASSEXW lpwcx); + + [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern IntPtr CreateWindowExW( + uint dwExStyle, char* lpClassName, char* lpWindowName, uint dwStyle, + int x, int y, int nWidth, int nHeight, + IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int ShowWindow(IntPtr hWnd, int nCmdShow); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int UpdateWindow(IntPtr hWnd); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int DestroyWindow(IntPtr hWnd); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern void PostQuitMessage(int nExitCode); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern nint DefWindowProcW(IntPtr hWnd, uint msg, nuint wParam, nint lParam); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int GetMessageW(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int TranslateMessage(ref MSG lpMsg); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern nint DispatchMessageW(ref MSG lpMsg); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int PostMessageW(IntPtr hWnd, uint Msg, nuint wParam, nint lParam); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int InvalidateRect(IntPtr hWnd, IntPtr lpRect, int bErase); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int GetClientRect(IntPtr hWnd, out RECT lpRect); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern IntPtr BeginPaint(IntPtr hWnd, out PAINTSTRUCT lpPaint); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int EndPaint(IntPtr hWnd, ref PAINTSTRUCT lpPaint); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern IntPtr LoadCursorW(IntPtr hInstance, IntPtr lpCursorName); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern IntPtr SetCursor(IntPtr hCursor); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern IntPtr LoadIconW(IntPtr hInstance, IntPtr lpIconName); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern uint GetDpiForWindow(IntPtr hwnd); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int GetSystemMetrics(int nIndex); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int TrackMouseEvent(ref TRACKMOUSEEVENT lpEventTrack); + + [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern int MessageBoxW(IntPtr hWnd, string lpText, string lpCaption, uint uType); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int OpenClipboard(IntPtr hWndNewOwner); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int EmptyClipboard(); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem); + + [DllImport("user32.dll", ExactSpelling = true)] + public static extern int CloseClipboard(); + + [DllImport("dwmapi.dll", ExactSpelling = true)] + public static extern int DwmSetWindowAttribute(IntPtr hwnd, uint dwAttribute, void* pvAttribute, uint cbAttribute); + + [DllImport("gdi32.dll", ExactSpelling = true)] + public static extern IntPtr CreateCompatibleDC(IntPtr hdc); + + [DllImport("gdi32.dll", ExactSpelling = true)] + public static extern int DeleteDC(IntPtr hdc); + + [DllImport("gdi32.dll", ExactSpelling = true)] + public static extern IntPtr CreateDIBSection(IntPtr hdc, ref BITMAPINFOHEADER pbmi, uint usage, out IntPtr ppvBits, IntPtr hSection, uint offset); + + [DllImport("gdi32.dll", ExactSpelling = true)] + public static extern IntPtr SelectObject(IntPtr hdc, IntPtr h); + + [DllImport("gdi32.dll", ExactSpelling = true)] + public static extern int DeleteObject(IntPtr ho); + + [DllImport("gdi32.dll", ExactSpelling = true)] + public static extern int BitBlt(IntPtr hdc, int x, int y, int cx, int cy, IntPtr hdcSrc, int x1, int y1, uint rop); + + [DllImport("shell32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern IntPtr ShellExecuteW(IntPtr hwnd, string lpOperation, string lpFile, string? lpParameters, string? lpDirectory, int nShowCmd); + + [DllImport("shell32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern int SHCreateItemFromParsingName(string pszPath, IntPtr pbc, ref Guid riid, out void* ppv); + + [DllImport("ole32.dll", ExactSpelling = true)] + public static extern int CoInitializeEx(IntPtr pvReserved, uint dwCoInit); + + [DllImport("ole32.dll", ExactSpelling = true)] + public static extern void CoUninitialize(); + + [DllImport("ole32.dll", ExactSpelling = true)] + public static extern int CoCreateInstance(ref Guid rclsid, IntPtr pUnkOuter, uint dwClsContext, ref Guid riid, out void* ppv); + + [DllImport("ole32.dll", ExactSpelling = true)] + public static extern void CoTaskMemFree(void* pv); + + // GDI+ Flat API + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdiplusStartup(out nuint token, ref GdiplusStartupInput input, IntPtr output); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern void GdiplusShutdown(nuint token); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipCreateFromHDC(IntPtr hdc, out IntPtr graphics); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDeleteGraphics(IntPtr graphics); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipSetSmoothingMode(IntPtr graphics, int smoothingMode); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipSetPixelOffsetMode(IntPtr graphics, int pixelOffsetMode); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipSetTextRenderingHint(IntPtr graphics, int mode); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipGraphicsClear(IntPtr graphics, uint color); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipCreateSolidFill(uint color, out IntPtr brush); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDeleteBrush(IntPtr brush); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipCreatePen1(uint color, float width, int unit, out IntPtr pen); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipSetPenLineCap197819(IntPtr pen, int startCap, int endCap, int dashCap); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipSetPenLineJoin(IntPtr pen, int lineJoin); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDeletePen(IntPtr pen); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDrawLine(IntPtr graphics, IntPtr pen, float x1, float y1, float x2, float y2); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipFillRectangle(IntPtr graphics, IntPtr brush, float x, float y, float width, float height); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipCreatePath(int brushMode, out IntPtr path); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDeletePath(IntPtr path); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipAddPathArc(IntPtr path, float x, float y, float width, float height, float startAngle, float sweepAngle); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipClosePathFigure(IntPtr path); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipFillPath(IntPtr graphics, IntPtr brush, IntPtr path); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDrawPath(IntPtr graphics, IntPtr pen, IntPtr path); + + [DllImport("gdiplus.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern int GdipCreateFontFamilyFromName(string name, IntPtr fontCollection, out IntPtr fontFamily); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDeleteFontFamily(IntPtr fontFamily); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipCreateFont(IntPtr fontFamily, float emSize, int style, int unit, out IntPtr font); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDeleteFont(IntPtr font); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipCreateStringFormat(int formatAttributes, int language, out IntPtr format); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDeleteStringFormat(IntPtr format); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipSetStringFormatAlign(IntPtr format, int align); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipSetStringFormatLineAlign(IntPtr format, int align); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipSetStringFormatTrimming(IntPtr format, int trimming); + + [DllImport("gdiplus.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern int GdipDrawString(IntPtr graphics, string str, int length, IntPtr font, ref RectF layoutRect, IntPtr stringFormat, IntPtr brush); + + [DllImport("gdiplus.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern int GdipMeasureString(IntPtr graphics, string str, int length, IntPtr font, ref RectF layoutRect, IntPtr stringFormat, out RectF boundingBox, out int codepointsFitted, out int linesFilled); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipCreateBitmapFromScan0(int width, int height, int stride, int format, IntPtr scan0, out IntPtr bitmap); + + [DllImport("gdiplus.dll", ExactSpelling = true)] + public static extern int GdipDisposeImage(IntPtr image); + + [DllImport("gdiplus.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern int GdipSaveImageToFile(IntPtr image, string filename, ref Guid clsidEncoder, IntPtr encoderParams); + + public static void SetClipboardText(IntPtr hwnd, string text) + { + if (OpenClipboard(hwnd) == 0) return; + try + { + EmptyClipboard(); + nuint bytes = (nuint)((text.Length + 1) * 2); + IntPtr hGlobal = GlobalAlloc(0x0042 /* GHND */, bytes); + if (hGlobal == IntPtr.Zero) return; + IntPtr ptr = GlobalLock(hGlobal); + if (ptr != IntPtr.Zero) + { + fixed (char* src = text) + { + Buffer.MemoryCopy(src, (void*)ptr, bytes, (nuint)(text.Length * 2)); + ((char*)ptr)[text.Length] = '\0'; + } + GlobalUnlock(hGlobal); + } + if (SetClipboardData(13 /* CF_UNICODETEXT */, hGlobal) == IntPtr.Zero) + { + GlobalFree(hGlobal); + } + } + finally + { + CloseClipboard(); + } + } + + // NativeAOT-compatible modern IFileOpenDialog COM wrapper using direct vtable calls + public static string? PickFolderDialog(IntPtr hwndOwner, string initialFolder) + { + Guid clsidFileOpenDialog = new Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7"); + Guid iidFileOpenDialog = new Guid("42f85136-db7e-439c-85f1-e4075d135fc8"); + Guid iidShellItem = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); + + void* pDialog = null; + int hr = CoCreateInstance(ref clsidFileOpenDialog, IntPtr.Zero, 1 /* CLSCTX_INPROC_SERVER */, ref iidFileOpenDialog, out pDialog); + if (hr < 0 || pDialog == null) return null; + + try + { + void** vtbl = *(void***)pDialog; + + // [10] GetOptions, [9] SetOptions + var getOptions = (delegate* unmanaged[Stdcall])vtbl[10]; + var setOptions = (delegate* unmanaged[Stdcall])vtbl[9]; + uint opts = 0; + getOptions(pDialog, &opts); + // FOS_PICKFOLDERS (0x20) | FOS_FORCEFILESYSTEM (0x40) | FOS_PATHMUSTEXIST (0x800) + setOptions(pDialog, opts | 0x00000860u); + + // [17] SetTitle + var setTitle = (delegate* unmanaged[Stdcall])vtbl[17]; + fixed (char* titlePtr = "Select Download Folder for Microsoft 365 Images") + { + setTitle(pDialog, titlePtr); + } + + // [12] SetFolder + if (!string.IsNullOrEmpty(initialFolder) && Directory.Exists(initialFolder)) + { + void* pInitialItem = null; + if (SHCreateItemFromParsingName(initialFolder, IntPtr.Zero, ref iidShellItem, out pInitialItem) >= 0 && pInitialItem != null) + { + var setFolder = (delegate* unmanaged[Stdcall])vtbl[12]; + setFolder(pDialog, pInitialItem); + var releaseInitial = (delegate* unmanaged[Stdcall])(*(void***)pInitialItem)[2]; + releaseInitial(pInitialItem); + } + } + + // [3] Show + var show = (delegate* unmanaged[Stdcall])vtbl[3]; + if (show(pDialog, hwndOwner) < 0) + { + return null; + } + + // [20] GetResult + void* pResultItem = null; + var getResult = (delegate* unmanaged[Stdcall])vtbl[20]; + if (getResult(pDialog, &pResultItem) >= 0 && pResultItem != null) + { + try + { + void** itemVtbl = *(void***)pResultItem; + // [5] GetDisplayName(SIGDN_FILESYSPATH = 0x80058000) + var getDisplayName = (delegate* unmanaged[Stdcall])itemVtbl[5]; + char* pszPath = null; + if (getDisplayName(pResultItem, 0x80058000u, &pszPath) >= 0 && pszPath != null) + { + try + { + return new string(pszPath); + } + finally + { + CoTaskMemFree(pszPath); + } + } + } + finally + { + var releaseItem = (delegate* unmanaged[Stdcall])(*(void***)pResultItem)[2]; + releaseItem(pResultItem); + } + } + } + finally + { + var releaseDlg = (delegate* unmanaged[Stdcall])(*(void***)pDialog)[2]; + releaseDlg(pDialog); + } + return null; + } + } + + internal sealed class Win32SyncContext : SynchronizationContext + { + private readonly IntPtr _hwnd; + private readonly ConcurrentQueue<(SendOrPostCallback Callback, object? State)> _queue = new(); + + public Win32SyncContext(IntPtr hwnd) + { + _hwnd = hwnd; + } + + public override void Post(SendOrPostCallback d, object? state) + { + _queue.Enqueue((d, state)); + Win32Native.PostMessageW(_hwnd, Win32Native.WM_APP_SYNC, 0, 0); + } + + public void Drain() + { + while (_queue.TryDequeue(out var work)) + { + work.Callback(work.State); + } + } + } + + internal enum HitKind + { + CheckAllUpdates, + BrowseFolder, + OpenFolder, + SelectAll, + SelectOutdated, + DownloadSelected, + StopAll, + CardCheckbox, + CardCopyUrl, + CardShowFile, + CardPrimary, + CardCancel + } + + internal struct HitRegion + { + public Win32Native.RectF Bounds; + public HitKind Kind; + public int CardIndex; + public bool Enabled; + } + + internal sealed class AppController + { + public static AppController? Instance; + + private readonly HttpClient _httpClient; + private readonly List _editions; + private readonly string _settingsFilePath; + private readonly List _hitRegions = new(24); + + private IntPtr _hwnd; + private Win32SyncContext? _syncContext; + private IntPtr _fontFamily; + private IntPtr _cursorArrow; + private IntPtr _cursorHand; + + private float _dpiScale = 1.0f; + private int _clientW = 940; + private int _clientH = 680; + private float _mouseX = -1; + private float _mouseY = -1; + private bool _mouseDown; + private bool _trackingMouse; + private int _hoveredRegionIndex = -1; + private int _pressedRegionIndex = -1; + + private string _downloadFolder = string.Empty; + private string _footerStatusText = "Checking Microsoft CDN for latest en-US builds..."; + private bool _isCheckingAll; + private bool _isBatchRunning; + private CancellationTokenSource? _batchCts; + + public AppController() + { + SocketsHttpHandler handler = new SocketsHttpHandler + { + AllowAutoRedirect = true, + AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, + PooledConnectionLifetime = TimeSpan.FromMinutes(10), + MaxConnectionsPerServer = 8 + }; + _httpClient = new HttpClient(handler) + { + Timeout = TimeSpan.FromMinutes(45) + }; + _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("M365IsoDownloader-NativeAOT/1.0 (Windows NT; en-US)"); + + string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + _settingsFilePath = Path.Combine(localAppData, "M365IsoDownloader", "settings.ini"); + + _editions = + [ + new EditionItem( + "Enterprise", + "Microsoft 365 Apps for Enterprise", + "Formerly Office 365 ProPlus • O365ProPlusRetail.img", + "O365ProPlusRetail.img", + selectedByDefault: false), + new EditionItem( + "Business", + "Microsoft 365 Apps for Business", + "Office 365 Business • O365BusinessRetail.img", + "O365BusinessRetail.img", + selectedByDefault: true), + new EditionItem( + "HomePrem", + "Microsoft 365 Personal / Family", + "Home Premium • O365HomePremRetail.img", + "O365HomePremRetail.img", + selectedByDefault: false) + ]; + + LoadSavedFolder(); + } + + private void LoadSavedFolder() + { + Dictionary settings = MetadataStore.ReadKeyValueFile(_settingsFilePath); + if (settings.TryGetValue("DownloadFolder", out string? saved) && !string.IsNullOrWhiteSpace(saved) && Directory.Exists(saved)) + { + _downloadFolder = saved; + return; + } + + string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + string downloads = Path.Combine(userProfile, "Downloads"); + if (!Directory.Exists(downloads)) + { + downloads = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); + } + _downloadFolder = downloads; + } + + private void SaveFolderSetting(string folder) + { + Dictionary dict = new Dictionary { ["DownloadFolder"] = folder }; + MetadataStore.WriteKeyValueFile(_settingsFilePath, dict); + } + + public async Task RunSelfTestAsync(string? screenshotPath) + { + EnsureFontFamily(); + await CheckAllVersionsAsync(); + + foreach (EditionItem item in _editions) + { + Console.WriteLine($"{item.Key}: Status={item.StatusText} | Build={item.RemoteVersionText} | Date={item.RemoteDateText} | Size={item.RemoteSizeText} | Local={item.LocalStatusText}"); + if (item.Status == EditionStatus.Error) return 2; + } + + if (!string.IsNullOrWhiteSpace(screenshotPath)) + { + RenderOffscreenPng(screenshotPath, 960, 680, 1.0f); + Console.WriteLine("Saved UI verification render to: " + screenshotPath); + } + return 0; + } + + private void EnsureFontFamily() + { + if (_fontFamily == IntPtr.Zero) + { + if (Win32Native.GdipCreateFontFamilyFromName("Segoe UI", IntPtr.Zero, out _fontFamily) != 0 || _fontFamily == IntPtr.Zero) + { + Win32Native.GdipCreateFontFamilyFromName("Arial", IntPtr.Zero, out _fontFamily); + } + } + } + + private unsafe void RenderOffscreenPng(string outputPath, int w, int h, float scale) + { + _clientW = w; + _clientH = h; + _dpiScale = scale; + + IntPtr memDc = Win32Native.CreateCompatibleDC(IntPtr.Zero); + Win32Native.BITMAPINFOHEADER bmi = new Win32Native.BITMAPINFOHEADER + { + biSize = (uint)sizeof(Win32Native.BITMAPINFOHEADER), + biWidth = w, + biHeight = -h, // top-down DIB + biPlanes = 1, + biBitCount = 32, + biCompression = 0 + }; + + IntPtr hDib = Win32Native.CreateDIBSection(memDc, ref bmi, 0, out IntPtr bits, IntPtr.Zero, 0); + IntPtr oldBmp = Win32Native.SelectObject(memDc, hDib); + + if (Win32Native.GdipCreateFromHDC(memDc, out IntPtr g) == 0 && g != IntPtr.Zero) + { + PaintScene(g, w, h, scale); + Win32Native.GdipDeleteGraphics(g); + } + + // PixelFormat32bppRGB = 0x00022009, PNG encoder CLSID = {557CF406-1A04-11D3-9A73-0000F81EF32E} + if (Win32Native.GdipCreateBitmapFromScan0(w, h, w * 4, 0x00022009, bits, out IntPtr gdipBmp) == 0 && gdipBmp != IntPtr.Zero) + { + Guid pngEncoder = new Guid("557CF406-1A04-11D3-9A73-0000F81EF32E"); + string? dir = Path.GetDirectoryName(outputPath); + if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) Directory.CreateDirectory(dir); + Win32Native.GdipSaveImageToFile(gdipBmp, outputPath, ref pngEncoder, IntPtr.Zero); + Win32Native.GdipDisposeImage(gdipBmp); + } + + Win32Native.SelectObject(memDc, oldBmp); + Win32Native.DeleteObject(hDib); + Win32Native.DeleteDC(memDc); + } + + private void QueueInitialCheck() + { + _syncContext?.Post(_ => { _ = CheckAllVersionsAsync(); }, null); + } + + public unsafe int RunGui() + { + EnsureFontFamily(); + _cursorArrow = Win32Native.LoadCursorW(IntPtr.Zero, (IntPtr)Win32Native.IDC_ARROW); + _cursorHand = Win32Native.LoadCursorW(IntPtr.Zero, (IntPtr)Win32Native.IDC_HAND); + + IntPtr hInstance = Win32Native.GetModuleHandleW(null); + // Embedded Win32 application icon has resource ID 32512 (IDI_APPLICATION in .NET WinExe) + IntPtr hAppIcon = Win32Native.LoadIconW(hInstance, (IntPtr)32512); + if (hAppIcon == IntPtr.Zero) hAppIcon = Win32Native.LoadIconW(IntPtr.Zero, (IntPtr)32512); + + fixed (char* className = "M365IsoDownloaderNativeWnd") + fixed (char* windowTitle = "Microsoft 365 Offline Image Downloader (en-US)") + { + Win32Native.WNDCLASSEXW wc = new Win32Native.WNDCLASSEXW + { + cbSize = (uint)sizeof(Win32Native.WNDCLASSEXW), + style = Win32Native.CS_HREDRAW | Win32Native.CS_VREDRAW, + lpfnWndProc = &StaticWndProc, + hInstance = hInstance, + hIcon = hAppIcon, + hIconSm = hAppIcon, + hCursor = _cursorArrow, + lpszClassName = className + }; + Win32Native.RegisterClassExW(ref wc); + + int screenW = Win32Native.GetSystemMetrics(0); + int screenH = Win32Native.GetSystemMetrics(1); + int initW = 960; + int initH = 700; + int posX = Math.Max(40, (screenW - initW) / 2); + int posY = Math.Max(40, (screenH - initH) / 2); + + _hwnd = Win32Native.CreateWindowExW( + 0, className, windowTitle, + Win32Native.WS_OVERLAPPEDWINDOW | Win32Native.WS_CLIPCHILDREN, + posX, posY, initW, initH, + IntPtr.Zero, IntPtr.Zero, hInstance, IntPtr.Zero); + + if (_hwnd == IntPtr.Zero) return 1; + + uint dpi = Win32Native.GetDpiForWindow(_hwnd); + if (dpi > 0) _dpiScale = dpi / 96.0f; + if (Math.Abs(_dpiScale - 1.0f) > 0.01f) + { + int scaledW = (int)Math.Round(initW * _dpiScale); + int scaledH = (int)Math.Round(initH * _dpiScale); + int sPosX = Math.Max(20, (screenW - scaledW) / 2); + int sPosY = Math.Max(20, (screenH - scaledH) / 2); + Win32Native.SetWindowPos(_hwnd, IntPtr.Zero, sPosX, sPosY, scaledW, scaledH, 0x0004 /* SWP_NOZORDER */); + } + + // Apply Windows 11 rounded corners & clean white titlebar + int dark = 0; + Win32Native.DwmSetWindowAttribute(_hwnd, 20 /* DWMWA_USE_IMMERSIVE_DARK_MODE */, &dark, sizeof(int)); + int cornerPref = 2; /* DWMWCP_ROUND */ + Win32Native.DwmSetWindowAttribute(_hwnd, 33 /* DWMWA_WINDOW_CORNER_PREFERENCE */, &cornerPref, sizeof(int)); + uint captionColor = 0x00FFFFFF; /* COLORREF BGR white */ + Win32Native.DwmSetWindowAttribute(_hwnd, 35 /* DWMWA_CAPTION_COLOR */, &captionColor, sizeof(uint)); + + _syncContext = new Win32SyncContext(_hwnd); + SynchronizationContext.SetSynchronizationContext(_syncContext); + + Win32Native.ShowWindow(_hwnd, Win32Native.SW_SHOW); + Win32Native.UpdateWindow(_hwnd); + + // Kick off initial CDN version check asynchronously on the UI loop + QueueInitialCheck(); + + while (Win32Native.GetMessageW(out Win32Native.MSG msg, IntPtr.Zero, 0, 0) > 0) + { + Win32Native.TranslateMessage(ref msg); + Win32Native.DispatchMessageW(ref msg); + } + } + + if (_fontFamily != IntPtr.Zero) + { + Win32Native.GdipDeleteFontFamily(_fontFamily); + _fontFamily = IntPtr.Zero; + } + return 0; + } + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])] + private static nint StaticWndProc(IntPtr hwnd, uint msg, nuint wParam, nint lParam) + { + AppController? app = Instance; + if (app != null) + { + return app.HandleMessage(hwnd, msg, wParam, lParam); + } + return Win32Native.DefWindowProcW(hwnd, msg, wParam, lParam); + } + + private unsafe nint HandleMessage(IntPtr hwnd, uint msg, nuint wParam, nint lParam) + { + switch (msg) + { + case Win32Native.WM_APP_SYNC: + _syncContext?.Drain(); + return 0; + + case Win32Native.WM_ERASEBKGND: + return 1; + + case Win32Native.WM_SIZE: + _clientW = (short)(lParam & 0xFFFF); + _clientH = (short)((lParam >> 16) & 0xFFFF); + RequestRepaint(); + return 0; + + case Win32Native.WM_GETMINMAXINFO: + { + Win32Native.MINMAXINFO* mmi = (Win32Native.MINMAXINFO*)lParam; + mmi->ptMinTrackSize.X = (int)Math.Round(820 * _dpiScale); + mmi->ptMinTrackSize.Y = (int)Math.Round(620 * _dpiScale); + return 0; + } + + case Win32Native.WM_DPICHANGED: + { + uint newDpi = (uint)(wParam & 0xFFFF); + if (newDpi > 0) _dpiScale = newDpi / 96.0f; + Win32Native.RECT* suggested = (Win32Native.RECT*)lParam; + Win32Native.SetWindowPos( + hwnd, IntPtr.Zero, + suggested->Left, suggested->Top, + suggested->Right - suggested->Left, + suggested->Bottom - suggested->Top, + 0x0004 | 0x0010 /* SWP_NOZORDER | SWP_NOACTIVATE */); + RequestRepaint(); + return 0; + } + + case Win32Native.WM_SETCURSOR: + if (((int)lParam & 0xFFFF) == 1 /* HTCLIENT */) + { + Win32Native.SetCursor(_hoveredRegionIndex >= 0 ? _cursorHand : _cursorArrow); + return 1; + } + break; + + case Win32Native.WM_MOUSEMOVE: + { + if (!_trackingMouse) + { + Win32Native.TRACKMOUSEEVENT tme = new Win32Native.TRACKMOUSEEVENT + { + cbSize = (uint)sizeof(Win32Native.TRACKMOUSEEVENT), + dwFlags = 0x00000002 /* TME_LEAVE */, + hwndTrack = hwnd + }; + Win32Native.TrackMouseEvent(ref tme); + _trackingMouse = true; + } + _mouseX = (short)(lParam & 0xFFFF); + _mouseY = (short)((lParam >> 16) & 0xFFFF); + int hit = HitTest(_mouseX, _mouseY); + if (hit != _hoveredRegionIndex) + { + _hoveredRegionIndex = hit; + Win32Native.SetCursor(_hoveredRegionIndex >= 0 ? _cursorHand : _cursorArrow); + RequestRepaint(); + } + return 0; + } + + case Win32Native.WM_MOUSELEAVE: + _trackingMouse = false; + _mouseX = -1; + _mouseY = -1; + _mouseDown = false; + _pressedRegionIndex = -1; + if (_hoveredRegionIndex != -1) + { + _hoveredRegionIndex = -1; + RequestRepaint(); + } + return 0; + + case Win32Native.WM_LBUTTONDOWN: + { + _mouseX = (short)(lParam & 0xFFFF); + _mouseY = (short)((lParam >> 16) & 0xFFFF); + _mouseDown = true; + _pressedRegionIndex = HitTest(_mouseX, _mouseY); + if (_pressedRegionIndex >= 0) RequestRepaint(); + return 0; + } + + case Win32Native.WM_LBUTTONUP: + { + _mouseX = (short)(lParam & 0xFFFF); + _mouseY = (short)((lParam >> 16) & 0xFFFF); + int releasedHit = HitTest(_mouseX, _mouseY); + int wasPressed = _pressedRegionIndex; + _mouseDown = false; + _pressedRegionIndex = -1; + RequestRepaint(); + if (releasedHit >= 0 && releasedHit == wasPressed) + { + HitRegion region = _hitRegions[releasedHit]; + OnHitActivated(region); + } + return 0; + } + + case Win32Native.WM_PAINT: + { + IntPtr hdc = Win32Native.BeginPaint(hwnd, out Win32Native.PAINTSTRUCT ps); + Win32Native.GetClientRect(hwnd, out Win32Native.RECT rc); + int w = Math.Max(1, rc.Right - rc.Left); + int h = Math.Max(1, rc.Bottom - rc.Top); + + IntPtr memDc = Win32Native.CreateCompatibleDC(hdc); + Win32Native.BITMAPINFOHEADER bmi = new Win32Native.BITMAPINFOHEADER + { + biSize = (uint)sizeof(Win32Native.BITMAPINFOHEADER), + biWidth = w, + biHeight = -h, + biPlanes = 1, + biBitCount = 32, + biCompression = 0 + }; + IntPtr hDib = Win32Native.CreateDIBSection(memDc, ref bmi, 0, out _, IntPtr.Zero, 0); + IntPtr oldBmp = Win32Native.SelectObject(memDc, hDib); + + if (Win32Native.GdipCreateFromHDC(memDc, out IntPtr g) == 0 && g != IntPtr.Zero) + { + PaintScene(g, w, h, _dpiScale); + Win32Native.GdipDeleteGraphics(g); + } + + Win32Native.BitBlt(hdc, 0, 0, w, h, memDc, 0, 0, Win32Native.SRCCOPY); + Win32Native.SelectObject(memDc, oldBmp); + Win32Native.DeleteObject(hDib); + Win32Native.DeleteDC(memDc); + Win32Native.EndPaint(hwnd, ref ps); + return 0; + } + + case Win32Native.WM_CLOSE: + { + bool anyDownloading = false; + foreach (EditionItem item in _editions) + { + if (item.Status == EditionStatus.Downloading) { anyDownloading = true; break; } + } + if (anyDownloading) + { + int res = Win32Native.MessageBoxW( + hwnd, + "A download is currently in progress.\n\nPause and exit now? Your partial download (.part) will be saved so you can resume later.", + "Download in Progress", + Win32Native.MB_YESNO | Win32Native.MB_ICONQUESTION); + if (res != Win32Native.IDYES) + { + return 0; + } + PauseAllActiveDownloads(); + } + Win32Native.DestroyWindow(hwnd); + return 0; + } + + case Win32Native.WM_DESTROY: + Win32Native.PostQuitMessage(0); + return 0; + } + + return Win32Native.DefWindowProcW(hwnd, msg, wParam, lParam); + } + + private void RequestRepaint() + { + if (_hwnd != IntPtr.Zero) + { + Win32Native.InvalidateRect(_hwnd, IntPtr.Zero, 0); + } + } + + private int HitTest(float x, float y) + { + for (int i = _hitRegions.Count - 1; i >= 0; i--) + { + if (_hitRegions[i].Enabled && _hitRegions[i].Bounds.Contains(x, y)) + { + return i; + } + } + return -1; + } + + private int RegisterHit(Win32Native.RectF rect, HitKind kind, int cardIndex = -1, bool enabled = true) + { + int idx = _hitRegions.Count; + _hitRegions.Add(new HitRegion { Bounds = rect, Kind = kind, CardIndex = cardIndex, Enabled = enabled }); + return idx; + } + + private bool IsHovered(int regionIdx) => regionIdx >= 0 && _hoveredRegionIndex == regionIdx; + private bool IsPressed(int regionIdx) => regionIdx >= 0 && _mouseDown && _pressedRegionIndex == regionIdx && _hoveredRegionIndex == regionIdx; + + // ==================== Fluent GDI+ Renderer ==================== + + private void PaintScene(IntPtr g, int width, int height, float s) + { + _hitRegions.Clear(); + + Win32Native.GdipSetSmoothingMode(g, 4 /* AntiAlias */); + Win32Native.GdipSetPixelOffsetMode(g, 4 /* Half */); + Win32Native.GdipSetTextRenderingHint(g, 5 /* ClearTypeGridFit */); + Win32Native.GdipGraphicsClear(g, 0xFFF3F5F8); + + IntPtr fontTitle = CreateFont(18.5f * s, bold: true); + IntPtr fontSub = CreateFont(12.2f * s, bold: false); + IntPtr fontCardTitle = CreateFont(15.0f * s, bold: true); + IntPtr fontBody = CreateFont(12.5f * s, bold: false); + IntPtr fontSemi = CreateFont(12.5f * s, bold: true); + IntPtr fontMetaLabel = CreateFont(11.8f * s, bold: false); + IntPtr fontMetaVal = CreateFont(11.8f * s, bold: true); + IntPtr fontBadge = CreateFont(11.3f * s, bold: true); + + try + { + float padX = 24f * s; + float headerH = 74f * s; + float footerH = 60f * s; + + // 1. Header Bar + FillRect(g, 0, 0, width, headerH, 0xFFFFFFFF); + DrawLine(g, 0, headerH, width, headerH, 0xFFE2E8F0, 1f * s); + + float iconBox = 42f * s; + float iconY = (headerH - iconBox) * 0.5f; + FillRoundRect(g, new Win32Native.RectF(padX, iconY, iconBox, iconBox), 10f * s, 0xFF0067C0); + DrawDownloadGlyph(g, padX + iconBox * 0.5f, iconY + iconBox * 0.5f, iconBox * 0.48f, 0xFFFFFFFF, 2.2f * s); + + float checkBtnW = 148f * s; + float checkBtnH = 34f * s; + Win32Native.RectF checkRect = new Win32Native.RectF(width - padX - checkBtnW, (headerH - checkBtnH) * 0.5f, checkBtnW, checkBtnH); + int checkHit = RegisterHit(checkRect, HitKind.CheckAllUpdates, enabled: !_isCheckingAll); + DrawButton(g, checkRect, _isCheckingAll ? "Checking..." : "Check for Updates", fontSemi, isPrimary: false, isDanger: false, enabled: !_isCheckingAll, hovered: IsHovered(checkHit), pressed: IsPressed(checkHit), s); + + float titleLeft = padX + iconBox + 14f * s; + float titleW = Math.Max(100f, checkRect.X - titleLeft - 14f * s); + DrawText(g, "Microsoft 365 Offline Image Downloader", fontTitle, new Win32Native.RectF(titleLeft, 15f * s, titleW, 25f * s), 0xFF0F172A, align: 0, vCenter: true); + DrawText(g, "Official Microsoft CDN (.img / ISO) • English (en-US) • 32-bit & 64-bit Offline Installer", fontSub, new Win32Native.RectF(titleLeft, 41f * s, titleW, 20f * s), 0xFF64748B, align: 0, vCenter: true); + + // 2. Save Folder Bar + float folderY = headerH + 14f * s; + float folderCardH = 52f * s; + Win32Native.RectF folderCard = new Win32Native.RectF(padX, folderY, width - 2 * padX, folderCardH); + FillRoundRect(g, folderCard, 8f * s, 0xFFFFFFFF); + StrokeRoundRect(g, folderCard, 8f * s, 0xFFE2E8F0, 1f * s); + + float btnH = 32f * s; + float btnTop = folderY + (folderCardH - btnH) * 0.5f; + float openW = 98f * s; + float browseW = 88f * s; + Win32Native.RectF openRect = new Win32Native.RectF(folderCard.X + folderCard.Width - 12f * s - openW, btnTop, openW, btnH); + Win32Native.RectF browseRect = new Win32Native.RectF(openRect.X - 8f * s - browseW, btnTop, browseW, btnH); + + int browseHit = RegisterHit(browseRect, HitKind.BrowseFolder); + int openHit = RegisterHit(openRect, HitKind.OpenFolder); + DrawButton(g, browseRect, "Browse...", fontSemi, false, false, true, IsHovered(browseHit), IsPressed(browseHit), s); + DrawButton(g, openRect, "Open Folder", fontSemi, false, false, true, IsHovered(openHit), IsPressed(openHit), s); + + float labelW = 82f * s; + DrawText(g, "Save Folder:", fontSemi, new Win32Native.RectF(folderCard.X + 14f * s, folderY, labelW, folderCardH), 0xFF334155, align: 0, vCenter: true); + + float pathBoxX = folderCard.X + 14f * s + labelW; + float pathBoxW = Math.Max(80f, browseRect.X - 10f * s - pathBoxX); + Win32Native.RectF pathBox = new Win32Native.RectF(pathBoxX, btnTop, pathBoxW, btnH); + FillRoundRect(g, pathBox, 6f * s, 0xFFF8FAFC); + StrokeRoundRect(g, pathBox, 6f * s, 0xFFCBD5E1, 1f * s); + DrawText(g, _downloadFolder, fontBody, new Win32Native.RectF(pathBox.X + 10f * s, pathBox.Y, pathBox.Width - 20f * s, pathBox.Height), 0xFF1E293B, align: 0, vCenter: true, pathEllipsis: true); + + // 3. Edition Cards + float cardsStartY = folderY + folderCardH + 14f * s; + float cardsBottomLimit = height - footerH - 10f * s; + float cardGap = 12f * s; + float curY = cardsStartY; + + for (int i = 0; i < _editions.Count; i++) + { + EditionItem item = _editions[i]; + float cardH = (item.ShowProgress ? 142f : 108f) * s; + if (curY + cardH > cardsBottomLimit && !item.ShowProgress) + { + cardH = Math.Max(98f * s, (cardsBottomLimit - cardsStartY - 2 * cardGap) / 3f); + } + + Win32Native.RectF cardRect = new Win32Native.RectF(padX, curY, width - 2 * padX, cardH); + FillRoundRect(g, cardRect, 10f * s, 0xFFFFFFFF); + StrokeRoundRect(g, cardRect, 10f * s, item.IsSelected ? 0xFF93C5FD : 0xFFE2E8F0, 1f * s); + + // Checkbox + float cbSize = 20f * s; + Win32Native.RectF cbRect = new Win32Native.RectF(cardRect.X + 16f * s, cardRect.Y + 18f * s, cbSize, cbSize); + int cbHit = RegisterHit(cbRect, HitKind.CardCheckbox, cardIndex: i); + DrawCheckbox(g, cbRect, item.IsSelected, IsHovered(cbHit), s); + + // Right-side card buttons + float rightEdge = cardRect.X + cardRect.Width - 16f * s; + float cBtnY = cardRect.Y + 15f * s; + float cBtnH = 32f * s; + + if (item.CanCancel) + { + float cancelW = 72f * s; + rightEdge -= cancelW; + Win32Native.RectF cancelRect = new Win32Native.RectF(rightEdge, cBtnY, cancelW, cBtnH); + int cancelHit = RegisterHit(cancelRect, HitKind.CardCancel, cardIndex: i); + DrawButton(g, cancelRect, "Cancel", fontSemi, false, true, true, IsHovered(cancelHit), IsPressed(cancelHit), s); + rightEdge -= 8f * s; + } + + float primaryW = 132f * s; + rightEdge -= primaryW; + Win32Native.RectF primaryRect = new Win32Native.RectF(rightEdge, cBtnY, primaryW, cBtnH); + int primaryHit = RegisterHit(primaryRect, HitKind.CardPrimary, cardIndex: i, enabled: item.CanPrimaryAction); + DrawButton(g, primaryRect, item.PrimaryActionText, fontSemi, true, false, item.CanPrimaryAction, IsHovered(primaryHit), IsPressed(primaryHit), s); + rightEdge -= 8f * s; + + if (item.HasLocalFile) + { + float showW = 82f * s; + rightEdge -= showW; + Win32Native.RectF showRect = new Win32Native.RectF(rightEdge, cBtnY, showW, cBtnH); + int showHit = RegisterHit(showRect, HitKind.CardShowFile, cardIndex: i); + DrawButton(g, showRect, "Show File", fontSemi, false, false, true, IsHovered(showHit), IsPressed(showHit), s); + rightEdge -= 8f * s; + } + + float copyW = 80f * s; + rightEdge -= copyW; + Win32Native.RectF copyRect = new Win32Native.RectF(rightEdge, cBtnY, copyW, cBtnH); + int copyHit = RegisterHit(copyRect, HitKind.CardCopyUrl, cardIndex: i); + DrawButton(g, copyRect, "Copy URL", fontSemi, false, false, true, IsHovered(copyHit), IsPressed(copyHit), s); + + // Card Title + Status Pill + Subtitle + float textLeft = cbRect.X + cbSize + 12f * s; + float maxHeaderW = Math.Max(120f, rightEdge - 12f * s - textLeft); + Win32Native.RectF measuredTitle = MeasureText(g, item.Title, fontCardTitle, maxHeaderW); + float actualTitleW = Math.Min(measuredTitle.Width + 4f * s, maxHeaderW - 110f * s); + DrawText(g, item.Title, fontCardTitle, new Win32Native.RectF(textLeft, cardRect.Y + 13f * s, actualTitleW, 22f * s), 0xFF0F172A, 0, true); + + Win32Native.RectF badgeMeasure = MeasureText(g, item.StatusText, fontBadge, 220f * s); + float badgeW = badgeMeasure.Width + 16f * s; + float badgeH = 21f * s; + Win32Native.RectF badgeRect = new Win32Native.RectF(textLeft + actualTitleW + 8f * s, cardRect.Y + 14f * s, badgeW, badgeH); + FillRoundRect(g, badgeRect, badgeH * 0.5f, item.BadgeBg); + DrawText(g, item.StatusText, fontBadge, badgeRect, item.BadgeFg, align: 1, vCenter: true); + + DrawText(g, item.Subtitle, fontSub, new Win32Native.RectF(textLeft, cardRect.Y + 36f * s, maxHeaderW, 18f * s), 0xFF64748B, 0, true); + + // Metadata Strip + float metaY = cardRect.Y + 62f * s; + float metaH = 31f * s; + Win32Native.RectF metaBar = new Win32Native.RectF(textLeft, metaY, cardRect.X + cardRect.Width - 16f * s - textLeft, metaH); + FillRoundRect(g, metaBar, 6f * s, 0xFFF8FAFC); + + float mx = metaBar.X + 12f * s; + mx = DrawKeyVal(g, "CDN Build: ", item.RemoteVersionText, fontMetaLabel, fontMetaVal, mx, metaY, metaH, s) + 20f * s; + mx = DrawKeyVal(g, "Published: ", item.RemoteDateText, fontMetaLabel, fontMetaVal, mx, metaY, metaH, s) + 20f * s; + mx = DrawKeyVal(g, "Size: ", item.RemoteSizeText, fontMetaLabel, fontMetaVal, mx, metaY, metaH, s) + 16f * s; + + float remMetaW = Math.Max(60f, (metaBar.X + metaBar.Width - 12f * s) - mx); + DrawText(g, "Local: " + item.LocalStatusText, fontMetaVal, new Win32Native.RectF(mx, metaY, remMetaW, metaH), 0xFF334155, align: 2, vCenter: true); + + // Progress Row (when active or paused) + if (item.ShowProgress) + { + float progY = metaY + metaH + 10f * s; + float progH = 8f * s; + Win32Native.RectF trackRect = new Win32Native.RectF(textLeft, progY, metaBar.Width, progH); + FillRoundRect(g, trackRect, progH * 0.5f, 0xFFE2E8F0); + + float fillPct = (float)Math.Clamp(item.ProgressPercent / 100.0, 0.0, 1.0); + if (fillPct > 0.005f) + { + float fillW = Math.Max(progH, trackRect.Width * fillPct); + uint barColor = item.Status == EditionStatus.Error ? 0xFFC42B1C : (item.Status == EditionStatus.Paused ? 0xFFD97706 : 0xFF0067C0); + FillRoundRect(g, new Win32Native.RectF(trackRect.X, trackRect.Y, fillW, progH), progH * 0.5f, barColor); + } + + DrawText(g, item.ProgressDetailsText, fontMetaLabel, new Win32Native.RectF(textLeft, progY + progH + 4f * s, metaBar.Width, 18f * s), 0xFF475569, align: 0, vCenter: true); + } + + curY += cardH + cardGap; + } + + // 4. Bottom Action Bar + float footerY = height - footerH; + FillRect(g, 0, footerY, width, footerH, 0xFFFFFFFF); + DrawLine(g, 0, footerY, width, footerY, 0xFFE2E8F0, 1f * s); + + float fBtnH = 34f * s; + float fBtnY = footerY + (footerH - fBtnH) * 0.5f; + + Win32Native.RectF selAllRect = new Win32Native.RectF(padX, fBtnY, 88f * s, fBtnH); + Win32Native.RectF selOutRect = new Win32Native.RectF(selAllRect.X + selAllRect.Width + 8f * s, fBtnY, 172f * s, fBtnH); + int selAllHit = RegisterHit(selAllRect, HitKind.SelectAll); + int selOutHit = RegisterHit(selOutRect, HitKind.SelectOutdated); + DrawButton(g, selAllRect, "Select All", fontSemi, false, false, true, IsHovered(selAllHit), IsPressed(selAllHit), s); + DrawButton(g, selOutRect, "Select Outdated / Missing", fontSemi, false, false, true, IsHovered(selOutHit), IsPressed(selOutHit), s); + + float dlSelW = 156f * s; + Win32Native.RectF dlSelRect = new Win32Native.RectF(width - padX - dlSelW, fBtnY, dlSelW, fBtnH); + int dlSelHit = RegisterHit(dlSelRect, HitKind.DownloadSelected, enabled: !_isBatchRunning); + DrawButton(g, dlSelRect, "Download Selected", fontSemi, true, false, !_isBatchRunning, IsHovered(dlSelHit), IsPressed(dlSelHit), s); + + float rightFooterLimit = dlSelRect.X - 12f * s; + bool anyActive = HasActiveDownloads(); + if (anyActive) + { + float pauseAllW = 94f * s; + Win32Native.RectF pauseAllRect = new Win32Native.RectF(dlSelRect.X - 10f * s - pauseAllW, fBtnY, pauseAllW, fBtnH); + int pauseAllHit = RegisterHit(pauseAllRect, HitKind.StopAll); + DrawButton(g, pauseAllRect, "Pause All", fontSemi, false, true, true, IsHovered(pauseAllHit), IsPressed(pauseAllHit), s); + rightFooterLimit = pauseAllRect.X - 12f * s; + } + + float statusLeft = selOutRect.X + selOutRect.Width + 16f * s; + float statusW = Math.Max(60f, rightFooterLimit - statusLeft); + DrawText(g, _footerStatusText, fontBody, new Win32Native.RectF(statusLeft, footerY, statusW, footerH), 0xFF475569, align: 0, vCenter: true); + } + finally + { + Win32Native.GdipDeleteFont(fontTitle); + Win32Native.GdipDeleteFont(fontSub); + Win32Native.GdipDeleteFont(fontCardTitle); + Win32Native.GdipDeleteFont(fontBody); + Win32Native.GdipDeleteFont(fontSemi); + Win32Native.GdipDeleteFont(fontMetaLabel); + Win32Native.GdipDeleteFont(fontMetaVal); + Win32Native.GdipDeleteFont(fontBadge); + } + } + + private IntPtr CreateFont(float pxSize, bool bold) + { + Win32Native.GdipCreateFont(_fontFamily, pxSize, bold ? 1 : 0, 2 /* UnitPixel */, out IntPtr font); + return font; + } + + private static void FillRect(IntPtr g, float x, float y, float w, float h, uint argb) + { + if (Win32Native.GdipCreateSolidFill(argb, out IntPtr brush) == 0) + { + Win32Native.GdipFillRectangle(g, brush, x, y, w, h); + Win32Native.GdipDeleteBrush(brush); + } + } + + private static void DrawLine(IntPtr g, float x1, float y1, float x2, float y2, uint argb, float width) + { + if (Win32Native.GdipCreatePen1(argb, width, 2, out IntPtr pen) == 0) + { + Win32Native.GdipDrawLine(g, pen, x1, y1, x2, y2); + Win32Native.GdipDeletePen(pen); + } + } + + private static IntPtr CreateRoundedPath(Win32Native.RectF r, float radius) + { + Win32Native.GdipCreatePath(0, out IntPtr path); + float d = Math.Min(radius * 2f, Math.Min(r.Width, r.Height)); + if (d <= 0.5f) + { + Win32Native.GdipAddPathArc(path, r.X, r.Y, 1f, 1f, 180f, 90f); + Win32Native.GdipAddPathArc(path, r.X + r.Width - 1f, r.Y, 1f, 1f, 270f, 90f); + Win32Native.GdipAddPathArc(path, r.X + r.Width - 1f, r.Y + r.Height - 1f, 1f, 1f, 0f, 90f); + Win32Native.GdipAddPathArc(path, r.X, r.Y + r.Height - 1f, 1f, 1f, 90f, 90f); + } + else + { + Win32Native.GdipAddPathArc(path, r.X, r.Y, d, d, 180f, 90f); + Win32Native.GdipAddPathArc(path, r.X + r.Width - d, r.Y, d, d, 270f, 90f); + Win32Native.GdipAddPathArc(path, r.X + r.Width - d, r.Y + r.Height - d, d, d, 0f, 90f); + Win32Native.GdipAddPathArc(path, r.X, r.Y + r.Height - d, d, d, 90f, 90f); + } + Win32Native.GdipClosePathFigure(path); + return path; + } + + private static void FillRoundRect(IntPtr g, Win32Native.RectF r, float radius, uint argb) + { + IntPtr path = CreateRoundedPath(r, radius); + if (Win32Native.GdipCreateSolidFill(argb, out IntPtr brush) == 0) + { + Win32Native.GdipFillPath(g, brush, path); + Win32Native.GdipDeleteBrush(brush); + } + Win32Native.GdipDeletePath(path); + } + + private static void StrokeRoundRect(IntPtr g, Win32Native.RectF r, float radius, uint argb, float strokeW) + { + IntPtr path = CreateRoundedPath(r, radius); + if (Win32Native.GdipCreatePen1(argb, strokeW, 2, out IntPtr pen) == 0) + { + Win32Native.GdipDrawPath(g, pen, path); + Win32Native.GdipDeletePen(pen); + } + Win32Native.GdipDeletePath(path); + } + + private static void DrawDownloadGlyph(IntPtr g, float cx, float cy, float size, uint argb, float strokeW) + { + if (Win32Native.GdipCreatePen1(argb, strokeW, 2, out IntPtr pen) == 0) + { + Win32Native.GdipSetPenLineCap197819(pen, 2, 2, 2); + Win32Native.GdipSetPenLineJoin(pen, 2); + float half = size * 0.5f; + float topY = cy - half * 0.85f; + float tipY = cy + half * 0.35f; + float wingX = half * 0.58f; + float wingY = cy - half * 0.12f; + float trayY = cy + half * 0.82f; + Win32Native.GdipDrawLine(g, pen, cx, topY, cx, tipY); + Win32Native.GdipDrawLine(g, pen, cx - wingX, wingY, cx, tipY); + Win32Native.GdipDrawLine(g, pen, cx + wingX, wingY, cx, tipY); + Win32Native.GdipDrawLine(g, pen, cx - half * 0.72f, trayY, cx + half * 0.72f, trayY); + Win32Native.GdipDeletePen(pen); + } + } + + private static void DrawCheckbox(IntPtr g, Win32Native.RectF r, bool isChecked, bool hovered, float s) + { + if (isChecked) + { + uint bg = hovered ? 0xFF005A9E : 0xFF0067C0; + FillRoundRect(g, r, 5f * s, bg); + if (Win32Native.GdipCreatePen1(0xFFFFFFFF, 2.0f * s, 2, out IntPtr pen) == 0) + { + Win32Native.GdipSetPenLineCap197819(pen, 2, 2, 2); + Win32Native.GdipSetPenLineJoin(pen, 2); + Win32Native.GdipDrawLine(g, pen, r.X + r.Width * 0.24f, r.Y + r.Height * 0.52f, r.X + r.Width * 0.43f, r.Y + r.Height * 0.72f); + Win32Native.GdipDrawLine(g, pen, r.X + r.Width * 0.43f, r.Y + r.Height * 0.72f, r.X + r.Width * 0.77f, r.Y + r.Height * 0.30f); + Win32Native.GdipDeletePen(pen); + } + } + else + { + FillRoundRect(g, r, 5f * s, hovered ? 0xFFF1F5F9 : 0xFFFFFFFF); + StrokeRoundRect(g, r, 5f * s, hovered ? 0xFF64748B : 0xFF94A3B8, 1.4f * s); + } + } + + private static void DrawButton(IntPtr g, Win32Native.RectF r, string text, IntPtr font, bool isPrimary, bool isDanger, bool enabled, bool hovered, bool pressed, float s) + { + uint bg; + uint fg; + uint border = 0; + + if (isPrimary) + { + if (!enabled) { bg = 0xFFCBD5E1; fg = 0xFF64748B; } + else if (pressed) { bg = 0xFF004578; fg = 0xFFFFFFFF; } + else if (hovered) { bg = 0xFF005A9E; fg = 0xFFFFFFFF; } + else { bg = 0xFF0067C0; fg = 0xFFFFFFFF; } + } + else if (isDanger) + { + bg = pressed ? 0xFFFEE2E2 : (hovered ? 0xFFFEF2F2 : 0xFFFFFFFF); + fg = enabled ? 0xFFC42B1C : 0xFF94A3B8; + border = hovered ? 0xFFEF4444 : 0xFFFECACA; + } + else + { + if (!enabled) { bg = 0xFFF8FAFC; fg = 0xFF94A3B8; border = 0xFFE2E8F0; } + else if (pressed) { bg = 0xFFE2E8F0; fg = 0xFF0F172A; border = 0xFF94A3B8; } + else if (hovered) { bg = 0xFFF8FAFC; fg = 0xFF0F172A; border = 0xFF94A3B8; } + else { bg = 0xFFFFFFFF; fg = 0xFF1E293B; border = 0xFFCBD5E1; } + } + + FillRoundRect(g, r, 6f * s, bg); + if (border != 0) + { + StrokeRoundRect(g, r, 6f * s, border, 1f * s); + } + DrawText(g, text, font, r, fg, align: 1, vCenter: true); + } + + private static Win32Native.RectF MeasureText(IntPtr g, string text, IntPtr font, float maxWidth) + { + Win32Native.GdipCreateStringFormat(0x00001000 /* NoWrap */, 0, out IntPtr fmt); + Win32Native.RectF layout = new Win32Native.RectF(0, 0, maxWidth, 200f); + Win32Native.GdipMeasureString(g, text, text.Length, font, ref layout, fmt, out Win32Native.RectF bbox, out _, out _); + Win32Native.GdipDeleteStringFormat(fmt); + return bbox; + } + + private static float DrawKeyVal(IntPtr g, string key, string val, IntPtr keyFont, IntPtr valFont, float x, float y, float h, float s) + { + Win32Native.RectF km = MeasureText(g, key, keyFont, 300f * s); + DrawText(g, key, keyFont, new Win32Native.RectF(x, y, km.Width + 4f * s, h), 0xFF64748B, 0, true); + float vx = x + km.Width; + Win32Native.RectF vm = MeasureText(g, val, valFont, 300f * s); + DrawText(g, val, valFont, new Win32Native.RectF(vx, y, vm.Width + 6f * s, h), 0xFF1E293B, 0, true); + return vx + vm.Width; + } + + private static void DrawText(IntPtr g, string text, IntPtr font, Win32Native.RectF rect, uint argb, int align, bool vCenter, bool pathEllipsis = false) + { + if (string.IsNullOrEmpty(text)) return; + Win32Native.GdipCreateStringFormat(0x00001000 /* NoWrap */, 0, out IntPtr fmt); + Win32Native.GdipSetStringFormatAlign(fmt, align); + Win32Native.GdipSetStringFormatLineAlign(fmt, vCenter ? 1 : 0); + Win32Native.GdipSetStringFormatTrimming(fmt, pathEllipsis ? 5 /* EllipsisPath */ : 3 /* EllipsisCharacter */); + + if (Win32Native.GdipCreateSolidFill(argb, out IntPtr brush) == 0) + { + Win32Native.GdipDrawString(g, text, text.Length, font, ref rect, fmt, brush); + Win32Native.GdipDeleteBrush(brush); + } + Win32Native.GdipDeleteStringFormat(fmt); + } + + // ==================== User Actions & Download Engine ==================== + + private async void OnHitActivated(HitRegion region) + { + switch (region.Kind) + { + case HitKind.CheckAllUpdates: + await CheckAllVersionsAsync(); + break; + + case HitKind.BrowseFolder: + { + string? picked = Win32Native.PickFolderDialog(_hwnd, _downloadFolder); + if (!string.IsNullOrWhiteSpace(picked)) + { + _downloadFolder = picked; + SaveFolderSetting(picked); + foreach (EditionItem item in _editions) + { + if (!item.IsBusy) EvaluateEditionState(item); + } + UpdateFooterSummary(); + RequestRepaint(); + } + break; + } + + case HitKind.OpenFolder: + try + { + if (!Directory.Exists(_downloadFolder)) Directory.CreateDirectory(_downloadFolder); + Win32Native.ShellExecuteW(_hwnd, "open", _downloadFolder, null, null, Win32Native.SW_SHOW); + } + catch (Exception ex) + { + Win32Native.MessageBoxW(_hwnd, "Could not open folder:\n" + ex.Message, "Folder Error", Win32Native.MB_OK | Win32Native.MB_ICONWARNING); + } + break; + + case HitKind.SelectAll: + { + bool allChecked = true; + foreach (EditionItem item in _editions) if (!item.IsSelected) allChecked = false; + foreach (EditionItem item in _editions) item.IsSelected = !allChecked; + RequestRepaint(); + break; + } + + case HitKind.SelectOutdated: + foreach (EditionItem item in _editions) + { + item.IsSelected = item.Status != EditionStatus.UpToDate; + } + RequestRepaint(); + break; + + case HitKind.DownloadSelected: + await DownloadSelectedAsync(); + break; + + case HitKind.StopAll: + PauseAllActiveDownloads(); + break; + + case HitKind.CardCheckbox: + if (region.CardIndex >= 0 && region.CardIndex < _editions.Count) + { + EditionItem item = _editions[region.CardIndex]; + item.IsSelected = !item.IsSelected; + RequestRepaint(); + } + break; + + case HitKind.CardCopyUrl: + if (region.CardIndex >= 0 && region.CardIndex < _editions.Count) + { + EditionItem item = _editions[region.CardIndex]; + string url = (item.RemoteInfo != null && !string.IsNullOrEmpty(item.RemoteInfo.ActiveUrl)) + ? item.RemoteInfo.ActiveUrl + : item.PrimaryUrl; + Win32Native.SetClipboardText(_hwnd, url); + _footerStatusText = "Copied direct CDN URL for " + item.FileName + " to clipboard."; + RequestRepaint(); + } + break; + + case HitKind.CardShowFile: + if (region.CardIndex >= 0 && region.CardIndex < _editions.Count) + { + EditionItem item = _editions[region.CardIndex]; + string fullPath = Path.Combine(_downloadFolder, item.FileName); + if (File.Exists(fullPath)) + { + Win32Native.ShellExecuteW(_hwnd, "open", "explorer.exe", "/select,\"" + fullPath + "\"", null, Win32Native.SW_SHOW); + } + } + break; + + case HitKind.CardPrimary: + if (region.CardIndex >= 0 && region.CardIndex < _editions.Count) + { + EditionItem item = _editions[region.CardIndex]; + if (item.Status == EditionStatus.Downloading) + { + item.PauseRequested = true; + item.ActiveDownloadCts?.Cancel(); + } + else if (!item.IsBusy) + { + await DownloadEditionAsync(item); + } + } + break; + + case HitKind.CardCancel: + if (region.CardIndex >= 0 && region.CardIndex < _editions.Count) + { + EditionItem item = _editions[region.CardIndex]; + int confirm = Win32Native.MessageBoxW( + _hwnd, + "Cancel download and discard partial .part file for " + item.Title + "?", + "Cancel Download", + Win32Native.MB_YESNO | Win32Native.MB_ICONWARNING); + if (confirm == Win32Native.IDYES) + { + item.PauseRequested = false; + item.ActiveDownloadCts?.Cancel(); + } + } + break; + } + } + + private bool HasActiveDownloads() + { + foreach (EditionItem item in _editions) + { + if (item.Status == EditionStatus.Downloading || item.Status == EditionStatus.Queued) return true; + } + return false; + } + + private void PauseAllActiveDownloads() + { + _batchCts?.Cancel(); + foreach (EditionItem item in _editions) + { + if (item.Status == EditionStatus.Downloading || item.Status == EditionStatus.Queued) + { + item.PauseRequested = true; + item.ActiveDownloadCts?.Cancel(); + } + } + RequestRepaint(); + } + + private async Task CheckAllVersionsAsync() + { + if (_isCheckingAll) return; + _isCheckingAll = true; + _footerStatusText = "Querying Microsoft CDN (officecdn.microsoft.com) for latest en-US images..."; + RequestRepaint(); + + try + { + List tasks = new List(3); + foreach (EditionItem item in _editions) + { + if (!item.IsBusy) + { + tasks.Add(CheckSingleEditionAsync(item)); + } + } + await Task.WhenAll(tasks); + UpdateFooterSummary(); + } + finally + { + _isCheckingAll = false; + RequestRepaint(); + } + } + + private async Task CheckSingleEditionAsync(EditionItem item) + { + item.ApplyStatus(EditionStatus.Checking, "Checking CDN..."); + RequestRepaint(); + + try + { + using CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(25)); + RemoteImageInfo remote = await ImageInspector.QueryCdnAsync(_httpClient, item.PrimaryUrl, item.FallbackUrl, cts.Token); + item.RemoteInfo = remote; + item.RemoteVersionText = !string.IsNullOrEmpty(remote.BuildVersion) ? remote.BuildVersion : "Available"; + item.RemoteDateText = remote.LastModified.HasValue + ? remote.LastModified.Value.ToLocalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + : "—"; + item.RemoteSizeText = FormatBytes(remote.ContentLength); + + await Task.Run(() => InspectLocalFiles(item, _downloadFolder)); + EvaluateEditionState(item); + } + catch (Exception ex) + { + item.ApplyStatus(EditionStatus.Error, "CDN Check Failed"); + item.LocalStatusText = "Error: " + ex.Message; + } + RequestRepaint(); + } + + private static void InspectLocalFiles(EditionItem item, string folder) + { + string imgPath = Path.Combine(folder, item.FileName); + string metaPath = imgPath + ".meta"; + string partPath = imgPath + ".part"; + + item.LocalVersion = string.Empty; + item.LocalLength = 0; + item.PartialLength = 0; + item.StoredETag = string.Empty; + + if (File.Exists(imgPath)) + { + FileInfo fi = new FileInfo(imgPath); + item.LocalLength = fi.Length; + item.LocalVersion = ImageInspector.ReadLocalImageBuild(imgPath); + + Dictionary meta = MetadataStore.ReadKeyValueFile(metaPath); + if (meta.TryGetValue("ETag", out string? savedEtag)) + { + item.StoredETag = savedEtag; + } + if (string.IsNullOrEmpty(item.LocalVersion) && meta.TryGetValue("BuildVersion", out string? savedVer)) + { + item.LocalVersion = savedVer; + } + } + + if (File.Exists(partPath)) + { + item.PartialLength = new FileInfo(partPath).Length; + } + } + + private void EvaluateEditionState(EditionItem item) + { + InspectLocalFiles(item, _downloadFolder); + item.HasLocalFile = item.LocalLength > 0; + + RemoteImageInfo? remote = item.RemoteInfo; + if (item.PartialLength > 0 && remote != null && remote.ContentLength > 0 && item.PartialLength < remote.ContentLength) + { + double pct = item.PartialLength * 100.0 / remote.ContentLength; + item.ProgressPercent = pct; + item.ShowProgress = true; + item.ProgressDetailsText = string.Format(CultureInfo.InvariantCulture, + "Paused at {0} of {1} ({2:0.0}%) — click Resume to continue.", + FormatBytes(item.PartialLength), FormatBytes(remote.ContentLength), pct); + item.LocalStatusText = string.Format(CultureInfo.InvariantCulture, "Partial ({0})", FormatBytes(item.PartialLength)); + item.ApplyStatus(EditionStatus.ResumeAvailable, string.Format(CultureInfo.InvariantCulture, "Resume ({0:0}%)", pct)); + return; + } + + item.ShowProgress = false; + + if (item.LocalLength <= 0) + { + item.LocalStatusText = "Not downloaded"; + item.ApplyStatus(EditionStatus.NotDownloaded, "Not Downloaded"); + return; + } + + if (remote == null) + { + item.LocalStatusText = !string.IsNullOrEmpty(item.LocalVersion) + ? $"{item.LocalVersion} ({FormatBytes(item.LocalLength)})" + : FormatBytes(item.LocalLength); + item.ApplyStatus(EditionStatus.Idle, "Local File Found"); + return; + } + + bool isSame = false; + if (!string.IsNullOrEmpty(remote.BuildVersion) && !string.IsNullOrEmpty(item.LocalVersion)) + { + if (Version.TryParse(remote.BuildVersion, out Version? rVer) && Version.TryParse(item.LocalVersion, out Version? lVer)) + { + isSame = (rVer <= lVer) && (remote.ContentLength <= 0 || item.LocalLength == remote.ContentLength); + } + else + { + isSame = string.Equals(remote.BuildVersion, item.LocalVersion, StringComparison.OrdinalIgnoreCase) + && (remote.ContentLength <= 0 || item.LocalLength == remote.ContentLength); + } + } + else if (!string.IsNullOrEmpty(remote.ETag) && !string.IsNullOrEmpty(item.StoredETag)) + { + isSame = string.Equals(remote.ETag, item.StoredETag, StringComparison.OrdinalIgnoreCase) + && item.LocalLength == remote.ContentLength; + } + else if (remote.ContentLength > 0) + { + isSame = item.LocalLength == remote.ContentLength; + } + + item.LocalStatusText = !string.IsNullOrEmpty(item.LocalVersion) + ? $"{item.LocalVersion} ({FormatBytes(item.LocalLength)})" + : FormatBytes(item.LocalLength); + + item.ApplyStatus(isSame ? EditionStatus.UpToDate : EditionStatus.UpdateAvailable, + isSame ? "Up to Date" : "Update Available"); + } + + private void UpdateFooterSummary() + { + int upToDate = 0, updates = 0, missing = 0, active = 0; + foreach (EditionItem item in _editions) + { + if (item.Status == EditionStatus.UpToDate) upToDate++; + else if (item.Status == EditionStatus.UpdateAvailable) updates++; + else if (item.Status == EditionStatus.Downloading || item.Status == EditionStatus.Queued) active++; + else missing++; + } + + _footerStatusText = active > 0 + ? $"Downloading ({active} active/queued)..." + : $"Checked 3 editions • {upToDate} up to date • {updates} updates • {missing} not downloaded"; + } + + private async Task DownloadSelectedAsync() + { + if (_isBatchRunning) return; + + List queue = new List(); + foreach (EditionItem item in _editions) + { + if (item.IsSelected && !item.IsBusy) queue.Add(item); + } + + if (queue.Count == 0) + { + Win32Native.MessageBoxW(_hwnd, "Please check at least one edition box to download.", "No Editions Selected", Win32Native.MB_OK | Win32Native.MB_ICONINFORMATION); + return; + } + + _isBatchRunning = true; + _batchCts = new CancellationTokenSource(); + + foreach (EditionItem item in queue) + { + item.ApplyStatus(EditionStatus.Queued, "Queued"); + } + UpdateFooterSummary(); + RequestRepaint(); + + try + { + foreach (EditionItem item in queue) + { + if (_batchCts.IsCancellationRequested) + { + if (item.Status == EditionStatus.Queued) EvaluateEditionState(item); + continue; + } + await DownloadEditionAsync(item); + } + } + finally + { + _isBatchRunning = false; + UpdateFooterSummary(); + RequestRepaint(); + } + } + + private async Task DownloadEditionAsync(EditionItem item) + { + if (item.IsBusy) return; + + string folder = _downloadFolder; + try + { + if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); + } + catch (Exception ex) + { + Win32Native.MessageBoxW(_hwnd, "Cannot create target download folder:\n" + ex.Message, "Folder Error", Win32Native.MB_OK | Win32Native.MB_ICONERROR); + return; + } + + item.IsBusy = true; + item.PauseRequested = false; + item.ActiveDownloadCts = new CancellationTokenSource(); + CancellationToken ct = item.ActiveDownloadCts.Token; + + string finalPath = Path.Combine(folder, item.FileName); + string partPath = finalPath + ".part"; + string partMetaPath = partPath + ".meta"; + string finalMetaPath = finalPath + ".meta"; + + try + { + item.ApplyStatus(EditionStatus.Checking, "Preparing..."); + UpdateFooterSummary(); + RequestRepaint(); + + if (item.RemoteInfo == null || item.RemoteInfo.ContentLength <= 0) + { + item.RemoteInfo = await ImageInspector.QueryCdnAsync(_httpClient, item.PrimaryUrl, item.FallbackUrl, ct); + item.RemoteVersionText = !string.IsNullOrEmpty(item.RemoteInfo.BuildVersion) ? item.RemoteInfo.BuildVersion : "Available"; + item.RemoteDateText = item.RemoteInfo.LastModified.HasValue ? item.RemoteInfo.LastModified.Value.ToLocalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) : "—"; + item.RemoteSizeText = FormatBytes(item.RemoteInfo.ContentLength); + } + + RemoteImageInfo remote = item.RemoteInfo; + long existingBytes = 0; + + if (File.Exists(partPath)) + { + Dictionary partMeta = MetadataStore.ReadKeyValueFile(partMetaPath); + partMeta.TryGetValue("ETag", out string? savedEtag); + + long currentLen = new FileInfo(partPath).Length; + bool sameRemote = string.IsNullOrEmpty(savedEtag) + || string.IsNullOrEmpty(remote.ETag) + || string.Equals(savedEtag, remote.ETag, StringComparison.OrdinalIgnoreCase); + + if (sameRemote && currentLen > 0 && currentLen < remote.ContentLength) + { + existingBytes = currentLen; + } + else if (sameRemote && remote.ContentLength > 0 && currentLen == remote.ContentLength) + { + existingBytes = remote.ContentLength; + } + else + { + File.Delete(partPath); + } + } + + long neededBytes = Math.Max(0, remote.ContentLength - existingBytes) + (64L * 1024L * 1024L); + try + { + string? root = Path.GetPathRoot(Path.GetFullPath(folder)); + if (!string.IsNullOrEmpty(root)) + { + DriveInfo drive = new DriveInfo(root); + if (drive.IsReady && drive.AvailableFreeSpace < neededBytes) + { + throw new IOException($"Insufficient disk space on {root}. Need {FormatBytes(neededBytes)}, available {FormatBytes(drive.AvailableFreeSpace)}."); + } + } + } + catch (IOException) + { + throw; + } + catch { } + + MetadataStore.WriteKeyValueFile(partMetaPath, new Dictionary + { + ["ETag"] = remote.ETag, + ["ContentLength"] = remote.ContentLength.ToString(CultureInfo.InvariantCulture), + ["BuildVersion"] = remote.BuildVersion + }); + + item.ShowProgress = true; + item.ApplyStatus(EditionStatus.Downloading, "Downloading"); + UpdateFooterSummary(); + RequestRepaint(); + + string downloadUrl = !string.IsNullOrEmpty(remote.ActiveUrl) ? remote.ActiveUrl : item.PrimaryUrl; + + if (existingBytes < remote.ContentLength || remote.ContentLength <= 0) + { + using HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, downloadUrl); + if (existingBytes > 0) + { + req.Headers.Range = new RangeHeaderValue(existingBytes, null); + } + + using HttpResponseMessage resp = await _httpClient.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, ct); + resp.EnsureSuccessStatusCode(); + + bool isResume = existingBytes > 0 && resp.StatusCode == HttpStatusCode.PartialContent; + if (!isResume) existingBytes = 0; + + long totalBytes = remote.ContentLength > 0 + ? remote.ContentLength + : existingBytes + (resp.Content.Headers.ContentLength ?? 0); + + FileMode mode = isResume ? FileMode.Append : FileMode.Create; + + using Stream netStream = await resp.Content.ReadAsStreamAsync(ct); + using FileStream fileStream = new FileStream(partPath, mode, FileAccess.Write, FileShare.Read, 1048576, FileOptions.Asynchronous | FileOptions.SequentialScan); + + byte[] buffer = new byte[262144]; + long totalTransferred = existingBytes; + long windowStartBytes = existingBytes; + Stopwatch sw = Stopwatch.StartNew(); + long lastUiTick = 0; + double smoothedSpeed = 0; + + int bytesRead; + while ((bytesRead = await netStream.ReadAsync(buffer, ct)) > 0) + { + await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead), ct); + totalTransferred += bytesRead; + + long elapsedMs = sw.ElapsedMilliseconds; + if (elapsedMs - lastUiTick >= 150 || totalTransferred == totalBytes) + { + double dtSec = (elapsedMs - lastUiTick) / 1000.0; + if (dtSec > 0.04) + { + double instantSpeed = (totalTransferred - windowStartBytes) / dtSec; + smoothedSpeed = smoothedSpeed <= 1 ? instantSpeed : (smoothedSpeed * 0.7 + instantSpeed * 0.3); + windowStartBytes = totalTransferred; + lastUiTick = elapsedMs; + } + + double pct = totalBytes > 0 ? (totalTransferred * 100.0 / totalBytes) : 0; + string etaText = "calculating..."; + if (smoothedSpeed > 1024 && totalBytes > totalTransferred) + { + TimeSpan rem = TimeSpan.FromSeconds((totalBytes - totalTransferred) / smoothedSpeed); + etaText = rem.TotalHours >= 1 + ? string.Format(CultureInfo.InvariantCulture, "{0:00}:{1:00}:{2:00}", (int)rem.TotalHours, rem.Minutes, rem.Seconds) + : string.Format(CultureInfo.InvariantCulture, "{0:00}:{1:00}", rem.Minutes, rem.Seconds); + } + + item.ProgressPercent = pct; + item.ProgressDetailsText = string.Format(CultureInfo.InvariantCulture, + "{0} / {1} ({2:0.0}%) • {3}/s • ETA {4}", + FormatBytes(totalTransferred), + FormatBytes(totalBytes), + pct, + FormatBytes((long)smoothedSpeed), + etaText); + RequestRepaint(); + } + } + await fileStream.FlushAsync(ct); + } + + FileInfo completedPart = new FileInfo(partPath); + if (remote.ContentLength > 0 && completedPart.Length != remote.ContentLength) + { + throw new IOException($"Incomplete transfer: expected {remote.ContentLength} bytes, received {completedPart.Length} bytes."); + } + + File.Move(partPath, finalPath, overwrite: true); + if (File.Exists(partMetaPath)) File.Delete(partMetaPath); + + string verifiedBuild = await Task.Run(() => ImageInspector.ReadLocalImageBuild(finalPath)); + if (string.IsNullOrEmpty(verifiedBuild)) verifiedBuild = remote.BuildVersion; + + MetadataStore.WriteKeyValueFile(finalMetaPath, new Dictionary + { + ["ETag"] = remote.ETag, + ["ContentLength"] = completedPart.Length.ToString(CultureInfo.InvariantCulture), + ["BuildVersion"] = verifiedBuild, + ["DownloadedUtc"] = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture) + }); + + EvaluateEditionState(item); + _footerStatusText = "Completed download: " + item.FileName; + } + catch (OperationCanceledException) + { + if (item.PauseRequested) + { + EvaluateEditionState(item); + if (item.PartialLength > 0) item.ApplyStatus(EditionStatus.Paused, "Paused"); + _footerStatusText = "Paused download: " + item.FileName; + } + else + { + try { if (File.Exists(partPath)) File.Delete(partPath); } catch { } + try { if (File.Exists(partMetaPath)) File.Delete(partMetaPath); } catch { } + EvaluateEditionState(item); + _footerStatusText = "Cancelled download: " + item.FileName; + } + } + catch (Exception ex) + { + item.ApplyStatus(EditionStatus.Error, "Download Error"); + item.ShowProgress = true; + item.ProgressDetailsText = "Error: " + ex.Message + " (Partial progress preserved — click Retry to resume)"; + _footerStatusText = "Error downloading " + item.FileName + ": " + ex.Message; + } + finally + { + item.ActiveDownloadCts?.Dispose(); + item.ActiveDownloadCts = null; + item.IsBusy = false; + UpdateFooterSummary(); + RequestRepaint(); + } + } + + private static string FormatBytes(long bytes) + { + if (bytes <= 0) return "0 B"; + string[] units = ["B", "KB", "MB", "GB", "TB"]; + double val = bytes; + int idx = 0; + while (val >= 1024.0 && idx < units.Length - 1) + { + val /= 1024.0; + idx++; + } + return idx >= 3 + ? string.Format(CultureInfo.InvariantCulture, "{0:0.00} {1}", val, units[idx]) + : string.Format(CultureInfo.InvariantCulture, "{0:0.0} {1}", val, units[idx]); + } + } + + public static class Program + { + public static int Main(string[] args) + { + Win32Native.CoInitializeEx(IntPtr.Zero, 2 /* COINIT_APARTMENTTHREADED */); + + Win32Native.GdiplusStartupInput gdipInput = new Win32Native.GdiplusStartupInput { GdiplusVersion = 1 }; + Win32Native.GdiplusStartup(out nuint gdipToken, ref gdipInput, IntPtr.Zero); + + try + { + AppController controller = new AppController(); + AppController.Instance = controller; + + if (args.Length >= 1 && string.Equals(args[0], "--self-test", StringComparison.OrdinalIgnoreCase)) + { + string? outPng = args.Length >= 2 ? args[1] : null; + return controller.RunSelfTestAsync(outPng).GetAwaiter().GetResult(); + } + + return controller.RunGui(); + } + finally + { + AppController.Instance = null; + if (gdipToken != 0) Win32Native.GdiplusShutdown(gdipToken); + Win32Native.CoUninitialize(); + } + } + } +} diff --git a/src/app.ico b/src/app.ico new file mode 100644 index 0000000..8a6433c Binary files /dev/null and b/src/app.ico differ diff --git a/src/app.manifest b/src/app.manifest new file mode 100644 index 0000000..e59557f --- /dev/null +++ b/src/app.manifest @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + true/pm + PerMonitorV2, PerMonitor + + +