diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 946f8e9..564631a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -36,38 +36,73 @@ jobs: with: dotnet-version: '10.0.x' - - name: Install the Native AOT toolchain + - name: Install NativeAOT build dependencies if: runner.os == 'Linux' run: sudo apt-get update && sudo apt-get install -y clang zlib1g-dev - # Linux: Native AOT. Windows: single-file, self-contained, ReadyToRun (set in the .csproj). - - name: Publish release build - run: dotnet publish VISaveManager.csproj -c Release -r ${{ matrix.rid }} -o dist/publish + - name: Publish NativeAOT build + run: dotnet publish VISaveManager.csproj -c Release -r ${{ matrix.rid }} -p:PublishAot=true -p:TreatWarningsAsErrors=true -o dist/publish - name: Verify published files shell: pwsh run: | $required = @('${{ matrix.executable }}', 'ui/index.html', 'ui/app.js', 'team-saves/Start/about.txt') + if ($IsWindows) { + $required += @('libSkiaSharp.dll', 'libHarfBuzzSharp.dll') + } foreach ($path in $required) { if (!(Test-Path -LiteralPath "dist/publish/$path" -PathType Leaf)) { throw "Missing published file $path" } } + foreach ($managedRuntimeFile in @('VISaveManager.dll', 'coreclr.dll', 'libcoreclr.so', 'clrjit.dll', 'libclrjit.so')) { + if (Test-Path -LiteralPath "dist/publish/$managedRuntimeFile") { + throw "Unexpected managed build file $managedRuntimeFile" + } + } + - name: Package Linux build if: runner.os == 'Linux' run: | test -x dist/publish/VISaveManager dist/publish/VISaveManager --help - tar -czf dist/VISaveManager-linux-x64.tar.gz -C dist/publish . + tar --exclude='./VISaveManager.dbg' -czf dist/VISaveManager-linux-x64.tar.gz -C dist/publish . - name: Package Windows build if: runner.os == 'Windows' shell: pwsh - run: Compress-Archive -Path 'dist/publish/*' -DestinationPath 'dist/VISaveManager-win-x64.zip' + run: | + $files = Get-ChildItem -LiteralPath dist/publish | Where-Object Extension -ne '.pdb' + Compress-Archive -LiteralPath $files.FullName -DestinationPath 'dist/VISaveManager-win-x64.zip' - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 with: name: VISaveManager-${{ matrix.rid }} path: dist/VISaveManager-${{ matrix.rid }}.${{ matrix.extension }} if-no-files-found: error + + - name: Check the Windows WebView2 Runtime + if: runner.os == 'Windows' + shell: pwsh + run: | + $clientId = '{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' + $keys = @("HKLM:\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\$clientId", + "HKCU:\Software\Microsoft\EdgeUpdate\Clients\$clientId") + $versions = @(Get-ItemPropertyValue -Path $keys -Name pv -ErrorAction SilentlyContinue) + if (!$versions.Where({ $_ -as [version] -gt [version]'0.0.0.0' })) { + $installer = Join-Path $env:RUNNER_TEMP 'MicrosoftEdgeWebview2Setup.exe' + Invoke-WebRequest 'https://go.microsoft.com/fwlink/p/?LinkId=2124703' -OutFile $installer + if ((Get-AuthenticodeSignature $installer).Status -ne 'Valid') { + throw 'WebView2 bootstrapper signature validation failed' + } + $installation = Start-Process -FilePath $installer -ArgumentList '/silent', '/install' -Wait -PassThru + if ($installation.ExitCode) { throw "WebView2 bootstrapper returned $($installation.ExitCode)" } + $versions = @(Get-ItemPropertyValue -Path $keys -Name pv -ErrorAction SilentlyContinue) + } + Write-Host "WebView2 runtime versions: $versions" + + - name: Test Windows WebView2 save load + if: runner.os == 'Windows' + timeout-minutes: 3 + run: node tests/windows-nativeaot-smoke.mjs dist/publish diff --git a/LinuxHost.cs b/LinuxHost.cs index a3afe20..676624e 100644 --- a/LinuxHost.cs +++ b/LinuxHost.cs @@ -63,7 +63,7 @@ public int Run() return 0; } - void Connect(IntPtr instance, string signal, Delegate handler) + void Connect(IntPtr instance, string signal, TDelegate handler) where TDelegate : Delegate { signalHandlers.Add(handler); g_signal_connect_data(instance, signal, Marshal.GetFunctionPointerForDelegate(handler), IntPtr.Zero, IntPtr.Zero, 0); diff --git a/NativeWindowsHost.cs b/NativeWindowsHost.cs new file mode 100644 index 0000000..50c4ac7 --- /dev/null +++ b/NativeWindowsHost.cs @@ -0,0 +1,132 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using Avalonia.Controls; +using Avalonia.Platform; +using Avalonia.Threading; +using Majorsilence.Forms; +using Majorsilence.Forms.Backends; + +namespace VISM; + +// The compatibility form and its Skia-rendered chrome use the Avalonia backend; +// WebView2 owns the content surface inside the form. +sealed class NativeWindowsHost : Form, IDesktopHost +{ + readonly Uri page = new(Path.Combine(AppContext.BaseDirectory, "ui", "index.html")); + readonly NativeWebView view = new(); + readonly SaveManager controller; + bool closing; + bool handlingMessage; + + NativeWindowsHost(bool test) + { + controller = new SaveManager(this, test, null); + Directory.CreateDirectory(controller.ProfileDirectory); + + Text = test ? "VI Save Manager (test profile)" : "VI Save Manager"; + ClientSize = new(980, 820); + MinimumSize = new(720, 560); + StartPosition = FormStartPosition.CenterScreen; + + view.EnvironmentRequested += (_, e) => + { + e.EnableDevTools = test; + if (e is WindowsWebView2EnvironmentRequestedEventArgs webView) + { + webView.UserDataFolder = controller.ProfileDirectory; + if (test) webView.AdditionalBrowserArguments = Environment.GetEnvironmentVariable("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS"); + } + if (test) Console.Error.WriteLine("WebView environment: " + e.GetType().Name); + }; + view.NavigationStarted += (_, e) => + { + e.Cancel = e.Request != page; + if (test) Console.Error.WriteLine($"WebView navigation: {e.Request} (cancelled: {e.Cancel})"); + }; + view.NewWindowRequested += (_, e) => e.Handled = true; + view.NavigationCompleted += (_, e) => + { + if (test) Console.Error.WriteLine($"WebView navigation complete: {e.Request} (success: {e.IsSuccess})"); + if (e.IsSuccess && e.Request == page) PostCurrentSaves(); + }; + view.WebMessageReceived += (_, e) => Dispatcher.UIThread.Post(() => Receive(e.Body)); + Controls.Add(new Majorsilence.Forms.NativeControlHost { Dock = DockStyle.Fill, NativeControl = view }); + view.Source = page; + if (test) + { + Shown += (_, _) => Console.Error.WriteLine("Compatibility form shown"); + view.AdapterCreated += (_, _) => Console.Error.WriteLine("WebView adapter created"); + } + FormClosed += (_, _) => closing = true; + } + + public static int Start(bool test) + { + try + { + if (test) Console.Error.WriteLine("Starting the compatibility host"); + Platform.Backend = new AvaloniaPlatformBackend(); + Platform.Backend.Initialize(); + if (!WebViewAdapterInfo.GetAdapterInfo(WebViewAdapterType.WebView2).IsSupported) + throw new InvalidOperationException("Install the Microsoft Edge WebView2 Runtime to start VI Save Manager."); + using var host = new NativeWindowsHost(test); + Majorsilence.Forms.Application.Run(host); + return 0; + } + catch (Exception error) + { + Console.Error.WriteLine(error); + if (!test) MessageBoxW(IntPtr.Zero, error.Message, "VI Save Manager", 0x10); + return 1; + } + } + + void PostCurrentSaves() => Dispatcher.UIThread.Post(() => Receive("""{"cmd":"list"}""")); + + void Receive(string? json) + { + if (closing || handlingMessage || view.Source != page || json is null) return; + handlingMessage = true; + try { controller.OnMessage(json); } + catch (Exception error) { Console.Error.WriteLine(error.Message); } + finally { handlingMessage = false; } + } + + public void Post(string json) => Dispatcher.UIThread.Post(async () => + { + if (closing || view.Source != page) return; + try { await view.InvokeScript($"window.vismReceive?.({json});"); } + catch (Exception error) { Console.Error.WriteLine(error.Message); } + }); + + public string? ChooseSaveFolder(string? current) => null; + + public string? ChooseExport(string filename) + { + using var dialog = new SaveFileDialog + { + Title = "Share this save as a zip", Filter = "GTA VI save (*.zip)|*.zip", + FileName = filename, DefaultExt = "zip", + InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + }; + return dialog.ShowDialog(this) == DialogResult.OK ? dialog.FileName : null; + } + + public string[] ChooseImports() + { + using var dialog = new OpenFileDialog + { + Title = "Import GTA VI saves", Filter = "Save zips (*.zip)|*.zip", Multiselect = true, + }; + return dialog.ShowDialog(this) == DialogResult.OK ? dialog.FileNames : []; + } + + public void RevealExport(string path) + { + try { Process.Start("explorer.exe", $"/select,\"{path}\""); } + catch (System.ComponentModel.Win32Exception) { } + } + + [DllImport("user32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] + static extern int MessageBoxW(IntPtr window, string text, string caption, uint type); +} diff --git a/Program.cs b/Program.cs index 804849a..c2db835 100644 --- a/Program.cs +++ b/Program.cs @@ -15,7 +15,9 @@ static class Program static int Main(string[] args) { bool test = args.Contains("--test", StringComparer.OrdinalIgnoreCase); -#if WINDOWS +#if VISM_NATIVE_WINDOWS + return NativeWindowsHost.Start(test); +#elif WINDOWS ApplicationConfiguration.Initialize(); Application.Run(new WindowsHost(test)); return 0; diff --git a/README.md b/README.md index 45d7d83..6db487d 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ sudo dnf install gtk3 webkit2gtk4.1 # Nobara / Fedora sudo apt install libgtk-3-0 libwebkit2gtk-4.1-0 # Debian / Ubuntu ``` -Build with the .NET 8 SDK or newer, then launch from the output directory. The default build uses the installed .NET runtime. For a shareable archive, use `./build.sh --release`: it compiles with **Native AOT** into one native `VISaveManager` executable that needs no .NET install (needs `clang` and the zlib headers: `sudo dnf install clang zlib-devel` or `sudo apt install clang zlib1g-dev`). Extract that archive into its own folder and run `./VISaveManager`. +Build with the .NET 8 SDK or newer, then launch from the output directory. The default build uses the installed .NET runtime. For a NativeAOT archive, install the .NET 10 SDK, Clang, and the zlib development headers (`clang zlib-devel` on Fedora or `clang zlib1g-dev` on Ubuntu), then run `./build.sh --release`. Extract the archive into its own folder and run `./VISaveManager`. ```sh ./build.sh @@ -39,7 +39,9 @@ Kept saves and backups are in `~/.local/share/VISaveManager/saves` (or under `$X ## Windows -Download the Windows zip from **Releases**, extract it, and run `VISaveManager.exe`. The game folder is `%LOCALAPPDATA%\victory\data\7952987A\saves`. Kept saves and backups are in `%LOCALAPPDATA%\VISaveManager\saves`. +Download the Windows zip from **Releases**, extract it, and run `VISaveManager.exe`. Windows 10 or later and the Microsoft Edge WebView2 Runtime are required. The game folder is `%LOCALAPPDATA%\victory\data\7952987A\saves`. Kept saves and backups are in `%LOCALAPPDATA%\VISaveManager\saves`. + +To build a Windows NativeAOT ZIP from source, install the .NET 10 SDK and Visual Studio Build Tools with **Desktop development with C++**. Run `release.ps1` on Windows x64. The NativeAOT build uses the Majorsilence.Forms compatibility layer with its Avalonia backend and ships the Windows x64 SkiaSharp and HarfBuzzSharp libraries alongside the EXE. ```powershell powershell -ExecutionPolicy Bypass -File build.ps1 # build and add shortcuts @@ -48,11 +50,11 @@ powershell -ExecutionPolicy Bypass -File release.ps1 # make the zip to share ## Choosing the build target -`dotnet build -c Release` defaults to the host OS. You can also target Linux or Windows explicitly with the same checkout. Cross publishing requires the matching SDK/runtime packs, which `dotnet publish` restores from NuGet: +`dotnet build -c Release` defaults to the host OS. You can cross-publish a self-contained build from the same checkout. NativeAOT releases use a native build host for each operating system. Self-contained cross publishing requires the matching SDK/runtime packs, which `dotnet publish` restores from NuGet: ```sh -dotnet publish VISaveManager.csproj -c Release -r linux-x64 -o dist/linux-x64 # Native AOT -dotnet publish VISaveManager.csproj -c Release -r win-x64 -o dist/win-x64 # single-file, self-contained, ReadyToRun +dotnet publish VISaveManager.csproj -c Release -r linux-x64 --self-contained true -p:PublishAot=false -o dist/linux-x64-self-contained +dotnet publish VISaveManager.csproj -c Release -r win-x64 --self-contained true -p:PublishAot=false -o dist/win-x64-self-contained ``` ## Automated builds @@ -62,9 +64,4 @@ The **Build VISM** workflow compiles both platforms on pull requests into `main` - `VISaveManager-linux-x64` contains `VISaveManager-linux-x64.tar.gz`. Extract it to a folder and run `./VISaveManager`. GTK3 and WebKitGTK are required. - `VISaveManager-win-x64` contains `VISaveManager-win-x64.zip`. Extract it to a folder and run `VISaveManager.exe`. The WebView2 Runtime is required. -Both archives include .NET, the application interface, and the bundled team saves. - -Release builds: Linux is compiled with Native AOT (one native executable, no .NET needed). Windows -can't use Native AOT because WinForms and WebView2 don't support it, so it ships as one -self-contained, ReadyToRun-compiled `VISaveManager.exe` instead (no .NET needed either). Both keep -the `ui` and `team-saves` folders next to the executable. +Both archives contain a NativeAOT executable, the application interface, and the bundled team saves. An installed .NET runtime is unnecessary. diff --git a/VISaveManager.csproj b/VISaveManager.csproj index 30f15e8..4670bac 100644 --- a/VISaveManager.csproj +++ b/VISaveManager.csproj @@ -1,6 +1,11 @@ - net8.0-windows + true + true + net10.0 + net8.0-windows net8.0 Exe enable @@ -18,26 +23,30 @@ vism.ico PerMonitorV2 - - - true - true - true - - - true - true - true - true - true - + + $(DefineConstants);VISM_NATIVE_WINDOWS + WinExe + vism.ico + vism.manifest + + + + + + + + + + + + + diff --git a/build.sh b/build.sh index 22f98b0..e9f7957 100755 --- a/build.sh +++ b/build.sh @@ -13,11 +13,10 @@ if [[ $# == 0 ]]; then dotnet publish VISaveManager.csproj -c Release -r "$rid" --self-contained false -p:PublishAot=false -o "$output" printf 'Launch with ./%s/VISaveManager\n' "$output" elif [[ $# == 1 && $1 == --release ]]; then - # Native AOT: needs clang and zlib headers (Fedora: clang zlib-devel, Debian/Ubuntu: clang zlib1g-dev) - output="dist/$rid-native" - dotnet publish VISaveManager.csproj -c Release -r "$rid" -o "$output" + output="dist/$rid-nativeaot" + dotnet publish VISaveManager.csproj -c Release -r "$rid" -p:PublishAot=true -o "$output" archive="dist/VISaveManager-$rid.tar.gz" - tar -czf "$archive" -C "$output" . + tar --exclude='./VISaveManager.dbg' -czf "$archive" -C "$output" . printf 'Built %s\n' "$archive" else printf 'Usage: %s [--release]\n' "$0" >&2 diff --git a/release.ps1 b/release.ps1 index 3293035..141be46 100644 --- a/release.ps1 +++ b/release.ps1 @@ -1,15 +1,16 @@ -# The zip to send to the team: one self-contained, ReadyToRun-compiled VISaveManager.exe (no .NET install needed), +# The zip to send to the team: a NativeAOT build (no .NET install needed on their PC), # saved as dist\VISaveManager-.zip. Unzip anywhere and run VISaveManager.exe. # Run: powershell -ExecutionPolicy Bypass -File release.ps1 $ErrorActionPreference = 'Stop' Set-Location -LiteralPath $PSScriptRoot $version = ([xml](Get-Content VISaveManager.csproj)).Project.PropertyGroup.Version | Where-Object { $_ } | Select-Object -First 1 -$out = Join-Path $PSScriptRoot 'dist\VISaveManager' +$out = Join-Path $PSScriptRoot 'dist\win-x64-nativeaot' if (Test-Path $out) { Remove-Item $out -Recurse -Force } -dotnet publish -c Release -r win-x64 -o $out # single-file, self-contained, ReadyToRun (see the .csproj) +dotnet publish -c Release -r win-x64 -p:PublishAot=true -o $out if ($LASTEXITCODE -ne 0) { throw "Build failed (exit code $LASTEXITCODE)" } $zip = Join-Path $PSScriptRoot "dist\VISaveManager-$version.zip" if (Test-Path $zip) { Remove-Item $zip -Force } -Compress-Archive -Path "$out\*" -DestinationPath $zip +$files = Get-ChildItem -LiteralPath $out | Where-Object Extension -ne '.pdb' +Compress-Archive -LiteralPath $files.FullName -DestinationPath $zip Write-Host "Zip to share: $zip" -ForegroundColor Green explorer.exe "/select,`"$zip`"" diff --git a/tests/windows-nativeaot-smoke.mjs b/tests/windows-nativeaot-smoke.mjs new file mode 100644 index 0000000..14eae05 --- /dev/null +++ b/tests/windows-nativeaot-smoke.mjs @@ -0,0 +1,93 @@ +import assert from 'node:assert/strict'; +import { execFileSync, spawn } from 'node:child_process'; +import { readdir, readFile } from 'node:fs/promises'; +import { join, relative, resolve } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; + +const publish = resolve(process.argv[2]); +const app = spawn(join(publish, 'VISaveManager.exe'), ['--test'], { + stdio: 'inherit', + env: { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: '--remote-debugging-port=9315' }, +}); +let socket; + +async function waitFor(action, description) { + const deadline = Date.now() + 60_000; + while (Date.now() < deadline && app.exitCode === null) { + const result = await action(); + if (result) return result; + await delay(250); + } + throw new Error(`Timed out waiting for ${description}; application exit code ${app.exitCode}`); +} + +try { + let lastTargets; + const url = await waitFor(async () => { + const response = await fetch('http://127.0.0.1:9315/json/list', { + signal: AbortSignal.timeout(1000), + }).catch(() => null); + if (!response?.ok) return null; + const pages = await response.json(); + const targets = pages.map(page => page.url).join(', '); + if (targets !== lastTargets) console.log('WebView2 targets:', targets); + lastTargets = targets; + return pages.find(page => page.url.startsWith('file:') && page.url.endsWith('/ui/index.html'))?.webSocketDebuggerUrl; + }, 'the bundled WebView2 page'); + + socket = new WebSocket(url); + await new Promise((opened, failed) => { + socket.addEventListener('open', opened, { once: true }); + socket.addEventListener('error', failed, { once: true }); + }); + let sequence = 0; + + function evaluate(expression) { + return new Promise((response, failed) => { + const id = ++sequence; + const timer = setTimeout(() => { + socket.removeEventListener('message', onMessage); + failed(new Error(`WebView2 did not complete: ${expression}`)); + }, 5000); + + function onMessage(event) { + const reply = JSON.parse(event.data); + if (reply.id !== id) return; + clearTimeout(timer); + socket.removeEventListener('message', onMessage); + if (reply.error || reply.result.exceptionDetails) { + failed(new Error(JSON.stringify(reply))); + return; + } + response(reply.result.result.value); + } + + socket.addEventListener('message', onMessage); + socket.send(JSON.stringify({ id, method: 'Runtime.evaluate', params: { expression, returnByValue: true } })); + }); + } + + const loadButton = `document.querySelector('[data-sv="load"][data-kind="team"][data-name="Boat"]')`; + await waitFor(() => evaluate(`Boolean(${loadButton}) && !document.querySelector('#testTag').hidden`), 'the test save list'); + await evaluate(`${loadButton}.click(); ${loadButton}.click();`); + await waitFor(() => evaluate(`document.querySelector('#svNow').textContent.includes('Current game save')`), 'the loaded test save'); + + const fixture = join(publish, 'team-saves', 'Boat'); + const destination = join(process.env.LOCALAPPDATA, 'VISaveManager-test', 'victory-data', '7952987A', 'saves'); + const files = (await readdir(fixture, { recursive: true, withFileTypes: true })) + .filter(entry => entry.isFile() && entry.name !== 'about.txt'); + assert.ok(files.length > 0); + for (const file of files) { + const path = join(relative(fixture, file.parentPath), file.name); + assert.deepEqual(await readFile(join(destination, path)), await readFile(join(fixture, path))); + } + console.log('Windows NativeAOT loaded the bundled page and restored the test save byte-for-byte.'); +} catch (error) { + execFileSync('pwsh', ['-NoProfile', '-Command', + "Get-Process VISaveManager,msedgewebview2 -ErrorAction SilentlyContinue | Format-Table Id,SessionId,MainWindowTitle,ProcessName", + ], { stdio: 'inherit', timeout: 5000 }); + throw error; +} finally { + socket?.close(); + if (app.exitCode === null) app.kill(); +} diff --git a/ui/app.js b/ui/app.js index b14d5eb..61abc33 100644 --- a/ui/app.js +++ b/ui/app.js @@ -2,7 +2,8 @@ const $ = (s) => document.querySelector(s); const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]); const send = (m) => { - if (window.chrome?.webview) window.chrome.webview.postMessage(m); + if (typeof window.invokeCSharpAction === 'function') window.invokeCSharpAction(JSON.stringify(m)); + else if (window.chrome?.webview) window.chrome.webview.postMessage(m); else window.webkit.messageHandlers.vism.postMessage(JSON.stringify(m)); }; const fmtSize = (b) => b >= 1048576 ? (b / 1048576).toFixed(1) + ' MB' : Math.max(1, Math.round(b / 1024)) + ' KB'; diff --git a/vism.manifest b/vism.manifest new file mode 100644 index 0000000..44371f7 --- /dev/null +++ b/vism.manifest @@ -0,0 +1,8 @@ + + + + + + + +