From a5532c1be39708a5f141d0263632b88cb7f051fe Mon Sep 17 00:00:00 2001 From: Mashrien Date: Wed, 25 Nov 2026 23:14:45 -0600 Subject: [PATCH 1/5] Use a native Win32 WebView2 host for Windows NativeAOT --- .github/workflows/build.yml | 27 ++- LinuxHost.cs | 2 +- NativeWindowsHost.cs | 90 ++++++++++ Program.cs | 4 +- README.md | 19 +-- VISaveManager.csproj | 48 ++++-- build.sh | 7 +- native/build-windows.cmd | 18 ++ native/windows-host.cpp | 275 ++++++++++++++++++++++++++++++ release.ps1 | 9 +- tests/windows-nativeaot-smoke.mjs | 83 +++++++++ 11 files changed, 538 insertions(+), 44 deletions(-) create mode 100644 NativeWindowsHost.cs create mode 100644 native/build-windows.cmd create mode 100644 native/windows-host.cpp create mode 100644 tests/windows-nativeaot-smoke.mjs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 946f8e9..0d62767 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -36,35 +36,50 @@ 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 += @('VISM.WindowsHost.dll', 'WebView2Loader.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: Test Windows WebView2 save load + if: runner.os == 'Windows' + timeout-minutes: 3 + run: node tests/windows-nativeaot-smoke.mjs dist/publish + - 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: 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..3cdc721 --- /dev/null +++ b/NativeWindowsHost.cs @@ -0,0 +1,90 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace VISM; + +sealed class NativeWindowsHost : IDesktopHost +{ + const string HostLibrary = "VISM.WindowsHost.dll"; + readonly SaveManager controller; + readonly ReceiveMessage receive; + + NativeWindowsHost(bool test) + { + controller = new SaveManager(this, test, null); + receive = Receive; + } + + public static int Start(bool test) + { + try + { + var host = new NativeWindowsHost(test); + Directory.CreateDirectory(host.controller.ProfileDirectory); + string root = AppContext.BaseDirectory; + int result = vism_run(host.receive, host.controller.ProfileDirectory, Path.Combine(root, "ui"), + test ? "VI Save Manager (test profile)" : "VI Save Manager", Path.Combine(root, "vism.ico")); + GC.KeepAlive(host); + return result; + } + catch (Exception error) + { + MessageBoxW(IntPtr.Zero, error.Message, "VI Save Manager", 0x10); + return 1; + } + } + + void Receive(IntPtr message) + { + try + { + if (Marshal.PtrToStringUni(message) is string json) controller.OnMessage(json); + } + catch (Exception error) { Console.Error.WriteLine(error.Message); } + } + + public void Post(string json) => vism_post(json); + public string? ChooseSaveFolder(string? current) => null; + + public string? ChooseExport(string filename) => ChooseFiles(true, filename, + Environment.GetFolderPath(Environment.SpecialFolder.Desktop)).FirstOrDefault(); + + public string[] ChooseImports() => ChooseFiles(false, "", null); + + public void RevealExport(string path) + { + try { Process.Start("explorer.exe", $"/select,\"{path}\""); } + catch (System.ComponentModel.Win32Exception) { } + } + + static unsafe string[] ChooseFiles(bool save, string filename, string? initial) + { + var buffer = new char[32_768]; + filename.AsSpan().CopyTo(buffer); + fixed (char* address = buffer) + if (vism_choose_files(save ? 1 : 0, address, (uint)buffer.Length, initial) == 0) return []; + var files = new List(); + int offset = 0; + while (offset < buffer.Length && buffer[offset] != '\0') + { + int end = Array.IndexOf(buffer, '\0', offset); + if (end < 0) return []; + files.Add(new string(buffer, offset, end - offset)); + offset = end + 1; + } + return files.Count > 1 ? files.Skip(1).Select(file => Path.Combine(files[0], file)).ToArray() : files.ToArray(); + } + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void ReceiveMessage(IntPtr message); + [DefaultDllImportSearchPaths(DllImportSearchPath.ApplicationDirectory | DllImportSearchPath.System32)] + [DllImport(HostLibrary, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode, ExactSpelling = true)] + static extern int vism_run(ReceiveMessage receive, string userData, string uiFolder, string title, string iconPath); + [DefaultDllImportSearchPaths(DllImportSearchPath.ApplicationDirectory | DllImportSearchPath.System32)] + [DllImport(HostLibrary, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode, ExactSpelling = true)] + static extern void vism_post(string json); + [DefaultDllImportSearchPaths(DllImportSearchPath.ApplicationDirectory | DllImportSearchPath.System32)] + [DllImport(HostLibrary, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode, ExactSpelling = true)] + static extern unsafe int vism_choose_files(int save, char* buffer, uint capacity, string? initial); + [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..5fc0650 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. ```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..56894c5 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,30 +23,39 @@ vism.ico PerMonitorV2 - - - true - true - true - - - true - true - true - true - true - + + $(DefineConstants);VISM_NATIVE_WINDOWS + WinExe + vism.ico + true + + + + + + + + + + + + $([MSBuild]::NormalizePath('$(MSBuildProjectDirectory)', '$(IntermediateOutputPath)', 'vism-host')) + + + + + + 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/native/build-windows.cmd b/native/build-windows.cmd new file mode 100644 index 0000000..b9bd52e --- /dev/null +++ b/native/build-windows.cmd @@ -0,0 +1,18 @@ +@echo off +setlocal +set "webview=%~1\build\native" +set "output=%~2" + +set "vswhere=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" +for /f "usebackq delims=" %%i in (`"%vswhere%" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set "visualStudio=%%i" +if not defined visualStudio ( + echo Install Visual Studio Build Tools with the Desktop development with C++ workload. 1>&2 + exit /b 1 +) +call "%visualStudio%\VC\Auxiliary\Build\vcvars64.bat" > nul +if errorlevel 1 exit /b 1 +if not exist "%output%\." mkdir "%output%" +cl.exe /nologo /std:c++17 /EHsc /O2 /MT /LD /I"%webview%\include" "%~dp0windows-host.cpp" /Fo"%output%\windows-host.obj" /Fe"%output%\VISM.WindowsHost.dll" /link /IMPLIB:"%output%\VISM.WindowsHost.lib" user32.lib ole32.lib comdlg32.lib uuid.lib +if errorlevel 1 exit /b 1 +copy /y "%webview%\x64\WebView2Loader.dll" "%output%\WebView2Loader.dll" > nul +exit /b %errorlevel% diff --git a/native/windows-host.cpp b/native/windows-host.cpp new file mode 100644 index 0000000..264544f --- /dev/null +++ b/native/windows-host.cpp @@ -0,0 +1,275 @@ +#define WIN32_LEAN_AND_MEAN +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +using ReceiveMessage = void (__cdecl *)(const wchar_t*); +using CreateEnvironment = HRESULT (STDAPICALLTYPE *)(PCWSTR, PCWSTR, ICoreWebView2EnvironmentOptions*, + ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*); + +namespace { +constexpr wchar_t windowClass[] = L"VISM.NativeHost"; +constexpr wchar_t page[] = L"https://app.vism/index.html"; +constexpr wchar_t origin[] = L"https://app.vism/"; +constexpr UINT deliverMessages = WM_APP + 1; +constexpr UINT handleRequests = WM_APP + 2; +std::atomic window; +ReceiveMessage receive; +std::wstring uiFolder; +ComPtr controller; +ComPtr view; +std::mutex messagesLock; +std::vector queuedMessages; +std::vector queuedRequests; +bool startupFailed = false; +bool dispatchingRequest = false; + +template +class Callback final : public Interface { + std::atomic references{1}; + std::function function; +public: + explicit Callback(std::function fn) : function(std::move(fn)) {} + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (iid != IID_IUnknown && iid != __uuidof(Interface)) return E_NOINTERFACE; + *out = static_cast(this); + AddRef(); + return S_OK; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++references; } + ULONG STDMETHODCALLTYPE Release() override { + const auto left = --references; + if (left == 0) delete this; + return left; + } + HRESULT STDMETHODCALLTYPE Invoke(First first, Second second) override { + try { return function(first, second); } + catch (...) { return E_FAIL; } + } +}; + +template +ComPtr MakeCallback(Function function) { + ComPtr value; + value.Attach(new Callback(std::move(function))); + return value; +} + +void ResizeView(HWND hwnd) { + if (controller) { + RECT bounds{}; + GetClientRect(hwnd, &bounds); + controller->put_Bounds(bounds); + } +} + +void StartupError(const wchar_t* message) { + startupFailed = true; + if (const auto hwnd = window.load()) { + MessageBoxW(hwnd, message, L"VI Save Manager", MB_OK | MB_ICONERROR); + DestroyWindow(hwnd); + } +} + +LRESULT CALLBACK WindowProcess(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { + switch (message) { + case WM_SIZE: + ResizeView(hwnd); + return 0; + case WM_GETMINMAXINFO: { + auto sizes = reinterpret_cast(lParam); + sizes->ptMinTrackSize = {740, 600}; + return 0; + } + case WM_DPICHANGED: { + const auto rect = reinterpret_cast(lParam); + SetWindowPos(hwnd, nullptr, rect->left, rect->top, rect->right - rect->left, + rect->bottom - rect->top, SWP_NOACTIVATE | SWP_NOZORDER); + return 0; + } + case deliverMessages: { + std::vector messages; + { + std::lock_guard lock(messagesLock); + messages.swap(queuedMessages); + } + if (view) for (const auto& item : messages) view->PostWebMessageAsJson(item.c_str()); + return 0; + } + case handleRequests: { + if (dispatchingRequest) return 0; + std::vector requests; + requests.swap(queuedRequests); + dispatchingRequest = true; + for (const auto& request : requests) { + if (!window.load()) break; + receive(request.c_str()); + } + dispatchingRequest = false; + if (!queuedRequests.empty() && window.load()) PostMessageW(hwnd, handleRequests, 0, 0); + return 0; + } + case WM_DESTROY: + window.store(nullptr); + if (controller) controller->Close(); + view.Reset(); + controller.Reset(); + PostQuitMessage(0); + return 0; + } + return DefWindowProcW(hwnd, message, wParam, lParam); +} + +HRESULT InitializeView(ICoreWebView2Controller* webController) { + controller = webController; + HRESULT hr = controller->get_CoreWebView2(&view); + if (FAILED(hr)) return hr; + ComPtr webView; + hr = view.As(&webView); + if (FAILED(hr)) return hr; + hr = webView->SetVirtualHostNameToFolderMapping(L"app.vism", uiFolder.c_str(), COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND_DENY_CORS); + if (FAILED(hr)) return hr; + + ComPtr colorController; + if (SUCCEEDED(controller.As(&colorController))) + colorController->put_DefaultBackgroundColor({255, 0x12, 0x0b, 0x1f}); + + ComPtr settings; + if (SUCCEEDED(view->get_Settings(&settings))) { + settings->put_AreDefaultContextMenusEnabled(FALSE); + settings->put_IsStatusBarEnabled(FALSE); + settings->put_AreDevToolsEnabled(FALSE); + } + auto navigation = MakeCallback( + [](ICoreWebView2*, ICoreWebView2NavigationStartingEventArgs* args) { + LPWSTR uri = nullptr; + args->get_Uri(&uri); + if (!uri || std::wstring_view(uri).substr(0, std::size(origin) - 1) != origin) args->put_Cancel(TRUE); + CoTaskMemFree(uri); + return S_OK; + }); + auto newWindow = MakeCallback( + [](ICoreWebView2*, ICoreWebView2NewWindowRequestedEventArgs* args) { return args->put_Handled(TRUE); }); + auto webMessage = MakeCallback( + [](ICoreWebView2*, ICoreWebView2WebMessageReceivedEventArgs* args) { + LPWSTR source = nullptr; + args->get_Source(&source); + const bool trusted = source && std::wstring_view(source) == page; + CoTaskMemFree(source); + if (!trusted) return S_OK; + LPWSTR json = nullptr; + const auto hr = args->get_WebMessageAsJson(&json); + if (FAILED(hr) || !json) return hr; + try { queuedRequests.emplace_back(json); } + catch (...) { CoTaskMemFree(json); return E_OUTOFMEMORY; } + CoTaskMemFree(json); + // Dispatch after WebView2 returns so a file dialog can run its modal loop. + PostMessageW(window.load(), handleRequests, 0, 0); + return S_OK; + }); + EventRegistrationToken token{}; + if (FAILED(hr = view->add_NavigationStarting(navigation.Get(), &token))) return hr; + if (FAILED(hr = view->add_NewWindowRequested(newWindow.Get(), &token))) return hr; + if (FAILED(hr = view->add_WebMessageReceived(webMessage.Get(), &token))) return hr; + ResizeView(window.load()); + return view->Navigate(page); +} +} + +extern "C" __declspec(dllexport) int __cdecl vism_run(ReceiveMessage callback, const wchar_t* userData, + const wchar_t* assets, const wchar_t* title, const wchar_t* iconPath) { + SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); + if (FAILED(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED))) return 1; + receive = callback; + uiFolder = assets; + const auto instance = GetModuleHandleW(nullptr); + auto icon = static_cast(LoadImageW(nullptr, iconPath, IMAGE_ICON, 0, 0, LR_LOADFROMFILE | LR_DEFAULTSIZE)); + WNDCLASSW settings{}; + settings.lpfnWndProc = WindowProcess; + settings.hInstance = instance; + settings.hIcon = icon; + settings.hCursor = LoadCursorW(nullptr, MAKEINTRESOURCEW(32512)); + settings.hbrBackground = reinterpret_cast(COLOR_WINDOW + 1); + settings.lpszClassName = windowClass; + RegisterClassW(&settings); + const auto hwnd = CreateWindowExW(0, windowClass, title, WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, CW_USEDEFAULT, 996, 860, nullptr, nullptr, instance, nullptr); + if (!hwnd) { CoUninitialize(); return 1; } + window.store(hwnd); + ShowWindow(hwnd, SW_SHOW); + + HMODULE loader = LoadLibraryExW(L"WebView2Loader.dll", nullptr, LOAD_LIBRARY_SEARCH_APPLICATION_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); + auto create = loader ? reinterpret_cast(GetProcAddress(loader, "CreateCoreWebView2EnvironmentWithOptions")) : nullptr; + auto onEnvironment = MakeCallback( + [](HRESULT result, ICoreWebView2Environment* environment) { + const auto hwnd = window.load(); + if (!hwnd) return S_OK; + if (FAILED(result) || !environment) { + StartupError(L"Microsoft Edge WebView2 Runtime is required to start VI Save Manager."); + return S_OK; + } + auto onController = MakeCallback( + [](HRESULT result, ICoreWebView2Controller* webController) { + if (!window.load()) return S_OK; + if (FAILED(result) || !webController || FAILED(InitializeView(webController))) + StartupError(L"VI Save Manager could not initialize the WebView2 window."); + return S_OK; + }); + if (FAILED(environment->CreateCoreWebView2Controller(hwnd, onController.Get()))) + StartupError(L"VI Save Manager could not create its WebView2 window."); + return S_OK; + }); + if (!create || FAILED(create(nullptr, userData, nullptr, onEnvironment.Get()))) + StartupError(L"VI Save Manager could not load WebView2. Install or repair the Microsoft Edge WebView2 Runtime."); + + MSG message{}; + BOOL result; + while ((result = GetMessageW(&message, nullptr, 0, 0)) > 0) { + TranslateMessage(&message); + DispatchMessageW(&message); + } + CoUninitialize(); + if (icon) DestroyIcon(icon); + return startupFailed || result < 0 ? 1 : 0; +} + +extern "C" __declspec(dllexport) void __cdecl vism_post(const wchar_t* json) { + try { + std::lock_guard lock(messagesLock); + if (const auto hwnd = window.load()) { + queuedMessages.emplace_back(json); + PostMessageW(hwnd, deliverMessages, 0, 0); + } + } catch (...) {} +} + +extern "C" __declspec(dllexport) int __cdecl vism_choose_files(int save, wchar_t* buffer, DWORD capacity, const wchar_t* initial) { + OPENFILENAMEW dialog{}; + dialog.lStructSize = sizeof(dialog); + dialog.hwndOwner = window.load(); + dialog.lpstrFilter = L"Save archives (*.zip)\0*.zip\0\0"; + dialog.lpstrFile = buffer; + dialog.nMaxFile = capacity; + dialog.lpstrInitialDir = initial; + dialog.lpstrDefExt = L"zip"; + dialog.lpstrTitle = save ? L"Share this save as a zip" : L"Import GTA VI saves"; + dialog.Flags = OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST; + if (save) { + dialog.Flags |= OFN_OVERWRITEPROMPT; + return GetSaveFileNameW(&dialog); + } + dialog.Flags |= OFN_ALLOWMULTISELECT | OFN_FILEMUSTEXIST; + return GetOpenFileNameW(&dialog); +} 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..81e96e5 --- /dev/null +++ b/tests/windows-nativeaot-smoke.mjs @@ -0,0 +1,83 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { readdir, readFile } from 'node:fs/promises'; +import { join, 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'], { + 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 { + 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(); + return pages.find(page => page.url === 'https://app.vism/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 relative = join(file.parentPath.slice(fixture.length), file.name); + assert.deepEqual(await readFile(join(destination, relative)), await readFile(join(fixture, relative))); + } + console.log('Windows NativeAOT loaded the bundled page and restored the test save byte-for-byte.'); +} finally { + socket?.close(); + if (app.exitCode === null) app.kill(); +} From 2effc568e20efbbb06ad543cb99eef7ca9379cd3 Mon Sep 17 00:00:00 2001 From: Mashrien Date: Wed, 25 Nov 2026 23:18:59 -0600 Subject: [PATCH 2/5] Host Windows NativeAOT UI with Majorsilence.Forms --- .github/workflows/build.yml | 2 +- NativeWindowsHost.cs | 121 +++++++------ README.md | 2 +- VISaveManager.csproj | 22 +-- native/build-windows.cmd | 18 -- native/windows-host.cpp | 275 ------------------------------ tests/windows-nativeaot-smoke.mjs | 9 +- ui/app.js | 3 +- vism.manifest | 8 + 9 files changed, 98 insertions(+), 362 deletions(-) delete mode 100644 native/build-windows.cmd delete mode 100644 native/windows-host.cpp create mode 100644 vism.manifest diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0d62767..5d80113 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -48,7 +48,7 @@ jobs: run: | $required = @('${{ matrix.executable }}', 'ui/index.html', 'ui/app.js', 'team-saves/Start/about.txt') if ($IsWindows) { - $required += @('VISM.WindowsHost.dll', 'WebView2Loader.dll') + $required += @('libSkiaSharp.dll', 'libHarfBuzzSharp.dll') } foreach ($path in $required) { if (!(Test-Path -LiteralPath "dist/publish/$path" -PathType Leaf)) { diff --git a/NativeWindowsHost.cs b/NativeWindowsHost.cs index 3cdc721..66022eb 100644 --- a/NativeWindowsHost.cs +++ b/NativeWindowsHost.cs @@ -1,31 +1,61 @@ 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; -sealed class NativeWindowsHost : IDesktopHost +// 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 { - const string HostLibrary = "VISM.WindowsHost.dll"; + readonly Uri page = new(Path.Combine(AppContext.BaseDirectory, "ui", "index.html")); + readonly NativeWebView view = new(); readonly SaveManager controller; - readonly ReceiveMessage receive; + bool closing; + bool handlingMessage; NativeWindowsHost(bool test) { controller = new SaveManager(this, test, null); - receive = Receive; + 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) => + { + if (e is WindowsWebView2EnvironmentRequestedEventArgs webView) + webView.UserDataFolder = controller.ProfileDirectory; + }; + view.NavigationStarted += (_, e) => e.Cancel = e.Request != page; + view.NewWindowRequested += (_, e) => e.Handled = true; + view.NavigationCompleted += (_, e) => + { + 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; + FormClosed += (_, _) => closing = true; } public static int Start(bool test) { try { - var host = new NativeWindowsHost(test); - Directory.CreateDirectory(host.controller.ProfileDirectory); - string root = AppContext.BaseDirectory; - int result = vism_run(host.receive, host.controller.ProfileDirectory, Path.Combine(root, "ui"), - test ? "VI Save Manager (test profile)" : "VI Save Manager", Path.Combine(root, "vism.ico")); - GC.KeepAlive(host); - return result; + 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) { @@ -34,22 +64,45 @@ public static int Start(bool test) } } - void Receive(IntPtr message) + void PostCurrentSaves() => Dispatcher.UIThread.Post(() => Receive("""{"cmd":"list"}""")); + + void Receive(string? json) { - try - { - if (Marshal.PtrToStringUni(message) is string json) controller.OnMessage(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) => vism_post(json); + 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) => ChooseFiles(true, filename, - Environment.GetFolderPath(Environment.SpecialFolder.Desktop)).FirstOrDefault(); + 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() => ChooseFiles(false, "", 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) { @@ -57,34 +110,6 @@ public void RevealExport(string path) catch (System.ComponentModel.Win32Exception) { } } - static unsafe string[] ChooseFiles(bool save, string filename, string? initial) - { - var buffer = new char[32_768]; - filename.AsSpan().CopyTo(buffer); - fixed (char* address = buffer) - if (vism_choose_files(save ? 1 : 0, address, (uint)buffer.Length, initial) == 0) return []; - var files = new List(); - int offset = 0; - while (offset < buffer.Length && buffer[offset] != '\0') - { - int end = Array.IndexOf(buffer, '\0', offset); - if (end < 0) return []; - files.Add(new string(buffer, offset, end - offset)); - offset = end + 1; - } - return files.Count > 1 ? files.Skip(1).Select(file => Path.Combine(files[0], file)).ToArray() : files.ToArray(); - } - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void ReceiveMessage(IntPtr message); - [DefaultDllImportSearchPaths(DllImportSearchPath.ApplicationDirectory | DllImportSearchPath.System32)] - [DllImport(HostLibrary, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode, ExactSpelling = true)] - static extern int vism_run(ReceiveMessage receive, string userData, string uiFolder, string title, string iconPath); - [DefaultDllImportSearchPaths(DllImportSearchPath.ApplicationDirectory | DllImportSearchPath.System32)] - [DllImport(HostLibrary, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode, ExactSpelling = true)] - static extern void vism_post(string json); - [DefaultDllImportSearchPaths(DllImportSearchPath.ApplicationDirectory | DllImportSearchPath.System32)] - [DllImport(HostLibrary, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode, ExactSpelling = true)] - static extern unsafe int vism_choose_files(int save, char* buffer, uint capacity, string? initial); [DllImport("user32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] static extern int MessageBoxW(IntPtr window, string text, string caption, uint type); } diff --git a/README.md b/README.md index 5fc0650..6db487d 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ Kept saves and backups are in `~/.local/share/VISaveManager/saves` (or under `$X 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. +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 diff --git a/VISaveManager.csproj b/VISaveManager.csproj index 56894c5..5dff721 100644 --- a/VISaveManager.csproj +++ b/VISaveManager.csproj @@ -31,11 +31,17 @@ $(DefineConstants);VISM_NATIVE_WINDOWS WinExe vism.ico - true + vism.manifest - + + + + + @@ -46,16 +52,4 @@ - - - - $([MSBuild]::NormalizePath('$(MSBuildProjectDirectory)', '$(IntermediateOutputPath)', 'vism-host')) - - - - - - diff --git a/native/build-windows.cmd b/native/build-windows.cmd deleted file mode 100644 index b9bd52e..0000000 --- a/native/build-windows.cmd +++ /dev/null @@ -1,18 +0,0 @@ -@echo off -setlocal -set "webview=%~1\build\native" -set "output=%~2" - -set "vswhere=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -for /f "usebackq delims=" %%i in (`"%vswhere%" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set "visualStudio=%%i" -if not defined visualStudio ( - echo Install Visual Studio Build Tools with the Desktop development with C++ workload. 1>&2 - exit /b 1 -) -call "%visualStudio%\VC\Auxiliary\Build\vcvars64.bat" > nul -if errorlevel 1 exit /b 1 -if not exist "%output%\." mkdir "%output%" -cl.exe /nologo /std:c++17 /EHsc /O2 /MT /LD /I"%webview%\include" "%~dp0windows-host.cpp" /Fo"%output%\windows-host.obj" /Fe"%output%\VISM.WindowsHost.dll" /link /IMPLIB:"%output%\VISM.WindowsHost.lib" user32.lib ole32.lib comdlg32.lib uuid.lib -if errorlevel 1 exit /b 1 -copy /y "%webview%\x64\WebView2Loader.dll" "%output%\WebView2Loader.dll" > nul -exit /b %errorlevel% diff --git a/native/windows-host.cpp b/native/windows-host.cpp deleted file mode 100644 index 264544f..0000000 --- a/native/windows-host.cpp +++ /dev/null @@ -1,275 +0,0 @@ -#define WIN32_LEAN_AND_MEAN -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using Microsoft::WRL::ComPtr; -using ReceiveMessage = void (__cdecl *)(const wchar_t*); -using CreateEnvironment = HRESULT (STDAPICALLTYPE *)(PCWSTR, PCWSTR, ICoreWebView2EnvironmentOptions*, - ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*); - -namespace { -constexpr wchar_t windowClass[] = L"VISM.NativeHost"; -constexpr wchar_t page[] = L"https://app.vism/index.html"; -constexpr wchar_t origin[] = L"https://app.vism/"; -constexpr UINT deliverMessages = WM_APP + 1; -constexpr UINT handleRequests = WM_APP + 2; -std::atomic window; -ReceiveMessage receive; -std::wstring uiFolder; -ComPtr controller; -ComPtr view; -std::mutex messagesLock; -std::vector queuedMessages; -std::vector queuedRequests; -bool startupFailed = false; -bool dispatchingRequest = false; - -template -class Callback final : public Interface { - std::atomic references{1}; - std::function function; -public: - explicit Callback(std::function fn) : function(std::move(fn)) {} - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (iid != IID_IUnknown && iid != __uuidof(Interface)) return E_NOINTERFACE; - *out = static_cast(this); - AddRef(); - return S_OK; - } - ULONG STDMETHODCALLTYPE AddRef() override { return ++references; } - ULONG STDMETHODCALLTYPE Release() override { - const auto left = --references; - if (left == 0) delete this; - return left; - } - HRESULT STDMETHODCALLTYPE Invoke(First first, Second second) override { - try { return function(first, second); } - catch (...) { return E_FAIL; } - } -}; - -template -ComPtr MakeCallback(Function function) { - ComPtr value; - value.Attach(new Callback(std::move(function))); - return value; -} - -void ResizeView(HWND hwnd) { - if (controller) { - RECT bounds{}; - GetClientRect(hwnd, &bounds); - controller->put_Bounds(bounds); - } -} - -void StartupError(const wchar_t* message) { - startupFailed = true; - if (const auto hwnd = window.load()) { - MessageBoxW(hwnd, message, L"VI Save Manager", MB_OK | MB_ICONERROR); - DestroyWindow(hwnd); - } -} - -LRESULT CALLBACK WindowProcess(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { - switch (message) { - case WM_SIZE: - ResizeView(hwnd); - return 0; - case WM_GETMINMAXINFO: { - auto sizes = reinterpret_cast(lParam); - sizes->ptMinTrackSize = {740, 600}; - return 0; - } - case WM_DPICHANGED: { - const auto rect = reinterpret_cast(lParam); - SetWindowPos(hwnd, nullptr, rect->left, rect->top, rect->right - rect->left, - rect->bottom - rect->top, SWP_NOACTIVATE | SWP_NOZORDER); - return 0; - } - case deliverMessages: { - std::vector messages; - { - std::lock_guard lock(messagesLock); - messages.swap(queuedMessages); - } - if (view) for (const auto& item : messages) view->PostWebMessageAsJson(item.c_str()); - return 0; - } - case handleRequests: { - if (dispatchingRequest) return 0; - std::vector requests; - requests.swap(queuedRequests); - dispatchingRequest = true; - for (const auto& request : requests) { - if (!window.load()) break; - receive(request.c_str()); - } - dispatchingRequest = false; - if (!queuedRequests.empty() && window.load()) PostMessageW(hwnd, handleRequests, 0, 0); - return 0; - } - case WM_DESTROY: - window.store(nullptr); - if (controller) controller->Close(); - view.Reset(); - controller.Reset(); - PostQuitMessage(0); - return 0; - } - return DefWindowProcW(hwnd, message, wParam, lParam); -} - -HRESULT InitializeView(ICoreWebView2Controller* webController) { - controller = webController; - HRESULT hr = controller->get_CoreWebView2(&view); - if (FAILED(hr)) return hr; - ComPtr webView; - hr = view.As(&webView); - if (FAILED(hr)) return hr; - hr = webView->SetVirtualHostNameToFolderMapping(L"app.vism", uiFolder.c_str(), COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND_DENY_CORS); - if (FAILED(hr)) return hr; - - ComPtr colorController; - if (SUCCEEDED(controller.As(&colorController))) - colorController->put_DefaultBackgroundColor({255, 0x12, 0x0b, 0x1f}); - - ComPtr settings; - if (SUCCEEDED(view->get_Settings(&settings))) { - settings->put_AreDefaultContextMenusEnabled(FALSE); - settings->put_IsStatusBarEnabled(FALSE); - settings->put_AreDevToolsEnabled(FALSE); - } - auto navigation = MakeCallback( - [](ICoreWebView2*, ICoreWebView2NavigationStartingEventArgs* args) { - LPWSTR uri = nullptr; - args->get_Uri(&uri); - if (!uri || std::wstring_view(uri).substr(0, std::size(origin) - 1) != origin) args->put_Cancel(TRUE); - CoTaskMemFree(uri); - return S_OK; - }); - auto newWindow = MakeCallback( - [](ICoreWebView2*, ICoreWebView2NewWindowRequestedEventArgs* args) { return args->put_Handled(TRUE); }); - auto webMessage = MakeCallback( - [](ICoreWebView2*, ICoreWebView2WebMessageReceivedEventArgs* args) { - LPWSTR source = nullptr; - args->get_Source(&source); - const bool trusted = source && std::wstring_view(source) == page; - CoTaskMemFree(source); - if (!trusted) return S_OK; - LPWSTR json = nullptr; - const auto hr = args->get_WebMessageAsJson(&json); - if (FAILED(hr) || !json) return hr; - try { queuedRequests.emplace_back(json); } - catch (...) { CoTaskMemFree(json); return E_OUTOFMEMORY; } - CoTaskMemFree(json); - // Dispatch after WebView2 returns so a file dialog can run its modal loop. - PostMessageW(window.load(), handleRequests, 0, 0); - return S_OK; - }); - EventRegistrationToken token{}; - if (FAILED(hr = view->add_NavigationStarting(navigation.Get(), &token))) return hr; - if (FAILED(hr = view->add_NewWindowRequested(newWindow.Get(), &token))) return hr; - if (FAILED(hr = view->add_WebMessageReceived(webMessage.Get(), &token))) return hr; - ResizeView(window.load()); - return view->Navigate(page); -} -} - -extern "C" __declspec(dllexport) int __cdecl vism_run(ReceiveMessage callback, const wchar_t* userData, - const wchar_t* assets, const wchar_t* title, const wchar_t* iconPath) { - SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); - if (FAILED(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED))) return 1; - receive = callback; - uiFolder = assets; - const auto instance = GetModuleHandleW(nullptr); - auto icon = static_cast(LoadImageW(nullptr, iconPath, IMAGE_ICON, 0, 0, LR_LOADFROMFILE | LR_DEFAULTSIZE)); - WNDCLASSW settings{}; - settings.lpfnWndProc = WindowProcess; - settings.hInstance = instance; - settings.hIcon = icon; - settings.hCursor = LoadCursorW(nullptr, MAKEINTRESOURCEW(32512)); - settings.hbrBackground = reinterpret_cast(COLOR_WINDOW + 1); - settings.lpszClassName = windowClass; - RegisterClassW(&settings); - const auto hwnd = CreateWindowExW(0, windowClass, title, WS_OVERLAPPEDWINDOW, - CW_USEDEFAULT, CW_USEDEFAULT, 996, 860, nullptr, nullptr, instance, nullptr); - if (!hwnd) { CoUninitialize(); return 1; } - window.store(hwnd); - ShowWindow(hwnd, SW_SHOW); - - HMODULE loader = LoadLibraryExW(L"WebView2Loader.dll", nullptr, LOAD_LIBRARY_SEARCH_APPLICATION_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); - auto create = loader ? reinterpret_cast(GetProcAddress(loader, "CreateCoreWebView2EnvironmentWithOptions")) : nullptr; - auto onEnvironment = MakeCallback( - [](HRESULT result, ICoreWebView2Environment* environment) { - const auto hwnd = window.load(); - if (!hwnd) return S_OK; - if (FAILED(result) || !environment) { - StartupError(L"Microsoft Edge WebView2 Runtime is required to start VI Save Manager."); - return S_OK; - } - auto onController = MakeCallback( - [](HRESULT result, ICoreWebView2Controller* webController) { - if (!window.load()) return S_OK; - if (FAILED(result) || !webController || FAILED(InitializeView(webController))) - StartupError(L"VI Save Manager could not initialize the WebView2 window."); - return S_OK; - }); - if (FAILED(environment->CreateCoreWebView2Controller(hwnd, onController.Get()))) - StartupError(L"VI Save Manager could not create its WebView2 window."); - return S_OK; - }); - if (!create || FAILED(create(nullptr, userData, nullptr, onEnvironment.Get()))) - StartupError(L"VI Save Manager could not load WebView2. Install or repair the Microsoft Edge WebView2 Runtime."); - - MSG message{}; - BOOL result; - while ((result = GetMessageW(&message, nullptr, 0, 0)) > 0) { - TranslateMessage(&message); - DispatchMessageW(&message); - } - CoUninitialize(); - if (icon) DestroyIcon(icon); - return startupFailed || result < 0 ? 1 : 0; -} - -extern "C" __declspec(dllexport) void __cdecl vism_post(const wchar_t* json) { - try { - std::lock_guard lock(messagesLock); - if (const auto hwnd = window.load()) { - queuedMessages.emplace_back(json); - PostMessageW(hwnd, deliverMessages, 0, 0); - } - } catch (...) {} -} - -extern "C" __declspec(dllexport) int __cdecl vism_choose_files(int save, wchar_t* buffer, DWORD capacity, const wchar_t* initial) { - OPENFILENAMEW dialog{}; - dialog.lStructSize = sizeof(dialog); - dialog.hwndOwner = window.load(); - dialog.lpstrFilter = L"Save archives (*.zip)\0*.zip\0\0"; - dialog.lpstrFile = buffer; - dialog.nMaxFile = capacity; - dialog.lpstrInitialDir = initial; - dialog.lpstrDefExt = L"zip"; - dialog.lpstrTitle = save ? L"Share this save as a zip" : L"Import GTA VI saves"; - dialog.Flags = OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST; - if (save) { - dialog.Flags |= OFN_OVERWRITEPROMPT; - return GetSaveFileNameW(&dialog); - } - dialog.Flags |= OFN_ALLOWMULTISELECT | OFN_FILEMUSTEXIST; - return GetOpenFileNameW(&dialog); -} diff --git a/tests/windows-nativeaot-smoke.mjs b/tests/windows-nativeaot-smoke.mjs index 81e96e5..245de48 100644 --- a/tests/windows-nativeaot-smoke.mjs +++ b/tests/windows-nativeaot-smoke.mjs @@ -1,11 +1,12 @@ import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import { readdir, readFile } from 'node:fs/promises'; -import { join, resolve } from 'node:path'; +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; @@ -27,7 +28,7 @@ try { }).catch(() => null); if (!response?.ok) return null; const pages = await response.json(); - return pages.find(page => page.url === 'https://app.vism/index.html')?.webSocketDebuggerUrl; + return pages.find(page => page.url.startsWith('file:') && page.url.endsWith('/ui/index.html'))?.webSocketDebuggerUrl; }, 'the bundled WebView2 page'); socket = new WebSocket(url); @@ -73,8 +74,8 @@ try { .filter(entry => entry.isFile() && entry.name !== 'about.txt'); assert.ok(files.length > 0); for (const file of files) { - const relative = join(file.parentPath.slice(fixture.length), file.name); - assert.deepEqual(await readFile(join(destination, relative)), await readFile(join(fixture, relative))); + 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.'); } finally { 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 @@ + + + + + + + + From 9b82e81e013bfd141bc01095f53255b3b100a483 Mon Sep 17 00:00:00 2001 From: Mashrien Date: Wed, 25 Nov 2026 23:20:44 -0600 Subject: [PATCH 3/5] Align Windows SkiaSharp and HarfBuzz dependencies --- VISaveManager.csproj | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/VISaveManager.csproj b/VISaveManager.csproj index 5dff721..4670bac 100644 --- a/VISaveManager.csproj +++ b/VISaveManager.csproj @@ -37,7 +37,8 @@ - + + Date: Wed, 25 Nov 2026 23:22:40 -0600 Subject: [PATCH 4/5] Provision WebView2 for the Windows NativeAOT smoke test --- .github/workflows/build.yml | 30 +++++++++++++++++++++++++----- NativeWindowsHost.cs | 4 +++- tests/windows-nativeaot-smoke.mjs | 4 ++++ 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5d80113..564631a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -62,11 +62,6 @@ jobs: } } - - name: Test Windows WebView2 save load - if: runner.os == 'Windows' - timeout-minutes: 3 - run: node tests/windows-nativeaot-smoke.mjs dist/publish - - name: Package Linux build if: runner.os == 'Linux' run: | @@ -86,3 +81,28 @@ jobs: 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/NativeWindowsHost.cs b/NativeWindowsHost.cs index 66022eb..b6a1f9a 100644 --- a/NativeWindowsHost.cs +++ b/NativeWindowsHost.cs @@ -30,6 +30,7 @@ sealed class NativeWindowsHost : Form, IDesktopHost view.EnvironmentRequested += (_, e) => { + e.EnableDevTools = test; if (e is WindowsWebView2EnvironmentRequestedEventArgs webView) webView.UserDataFolder = controller.ProfileDirectory; }; @@ -59,7 +60,8 @@ public static int Start(bool test) } catch (Exception error) { - MessageBoxW(IntPtr.Zero, error.Message, "VI Save Manager", 0x10); + Console.Error.WriteLine(error); + if (!test) MessageBoxW(IntPtr.Zero, error.Message, "VI Save Manager", 0x10); return 1; } } diff --git a/tests/windows-nativeaot-smoke.mjs b/tests/windows-nativeaot-smoke.mjs index 245de48..4277e67 100644 --- a/tests/windows-nativeaot-smoke.mjs +++ b/tests/windows-nativeaot-smoke.mjs @@ -22,12 +22,16 @@ async function waitFor(action, description) { } 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'); From 1fb6a7f5acc78945078389e7bd860b2d9857b5c8 Mon Sep 17 00:00:00 2001 From: Mashrien Date: Wed, 25 Nov 2026 23:26:19 -0600 Subject: [PATCH 5/5] Trace Windows WebView2 startup in the test profile --- NativeWindowsHost.cs | 17 ++++++++++++++++- tests/windows-nativeaot-smoke.mjs | 7 ++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/NativeWindowsHost.cs b/NativeWindowsHost.cs index b6a1f9a..50c4ac7 100644 --- a/NativeWindowsHost.cs +++ b/NativeWindowsHost.cs @@ -32,17 +32,31 @@ sealed class NativeWindowsHost : Form, IDesktopHost { 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.NavigationStarted += (_, e) => e.Cancel = e.Request != page; 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; } @@ -50,6 +64,7 @@ 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) diff --git a/tests/windows-nativeaot-smoke.mjs b/tests/windows-nativeaot-smoke.mjs index 4277e67..14eae05 100644 --- a/tests/windows-nativeaot-smoke.mjs +++ b/tests/windows-nativeaot-smoke.mjs @@ -1,5 +1,5 @@ import assert from 'node:assert/strict'; -import { spawn } from 'node:child_process'; +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'; @@ -82,6 +82,11 @@ try { 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();