Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 41 additions & 6 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion LinuxHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public int Run()
return 0;
}

void Connect(IntPtr instance, string signal, Delegate handler)
void Connect<TDelegate>(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);
Expand Down
132 changes: 132 additions & 0 deletions NativeWindowsHost.cs
Original file line number Diff line number Diff line change
@@ -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);
}
4 changes: 3 additions & 1 deletion Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
19 changes: 8 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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.
43 changes: 26 additions & 17 deletions VISaveManager.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework Condition="$(RuntimeIdentifier.StartsWith('win-')) or ('$(RuntimeIdentifier)' == '' and $([MSBuild]::IsOSPlatform('Windows')))">net8.0-windows</TargetFramework>
<VismWindows Condition="$(RuntimeIdentifier.StartsWith('win-')) or ('$(RuntimeIdentifier)' == '' and $([MSBuild]::IsOSPlatform('Windows')))">true</VismWindows>
<PublishAot Condition="'$(PublishAot)' == '' and '$(Configuration)' == 'Release' and
(('$(RuntimeIdentifier)' == 'win-x64' and $([MSBuild]::IsOSPlatform('Windows'))) or
($(RuntimeIdentifier.StartsWith('linux-')) and $([MSBuild]::IsOSPlatform('Linux'))))">true</PublishAot>
<TargetFramework Condition="'$(PublishAot)' == 'true'">net10.0</TargetFramework>
<TargetFramework Condition="'$(TargetFramework)' == '' and '$(VismWindows)' == 'true'">net8.0-windows</TargetFramework>
<TargetFramework Condition="'$(TargetFramework)' == ''">net8.0</TargetFramework>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
Expand All @@ -18,26 +23,30 @@
<ApplicationIcon>vism.ico</ApplicationIcon>
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
</PropertyGroup>
<!-- Release packages (dotnet publish -c Release -r <rid>):
Linux: Native AOT, one native executable, no .NET needed.
Windows: WinForms and WebView2 can't do Native AOT, so one self-contained,
ReadyToRun-compiled executable instead. The ui and team-saves folders sit beside it. -->
<PropertyGroup Condition="'$(Configuration)' == 'Release' and '$(RuntimeIdentifier)' != '' and '$(TargetFramework)' == 'net8.0'">
<PublishAot>true</PublishAot>
<InvariantGlobalization>true</InvariantGlobalization>
<StripSymbols>true</StripSymbols>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release' and '$(RuntimeIdentifier)' != '' and '$(TargetFramework)' == 'net8.0-windows'">
<SelfContained>true</SelfContained>
<PublishSingleFile>true</PublishSingleFile>
<PublishReadyToRun>true</PublishReadyToRun>
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
<EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net8.0-windows'">
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2903.40" />
<Compile Remove="LinuxHost.cs" />
</ItemGroup>
<PropertyGroup Condition="'$(VismWindows)' == 'true' and '$(PublishAot)' == 'true'">
<DefineConstants>$(DefineConstants);VISM_NATIVE_WINDOWS</DefineConstants>
<OutputType>WinExe</OutputType>
<ApplicationIcon>vism.ico</ApplicationIcon>
<ApplicationManifest>vism.manifest</ApplicationManifest>
</PropertyGroup>
<ItemGroup Condition="'$(VismWindows)' == 'true' and '$(PublishAot)' == 'true'">
<Compile Remove="LinuxHost.cs" />
<PackageReference Include="Majorsilence.Forms.Avalonia" Version="26.11.19" />
<PackageReference Include="SkiaSharp.NativeAssets.Win32" Version="3.119.4" GeneratePathProperty="true" />
<PackageReference Include="SkiaSharp.HarfBuzz" Version="3.119.4" />
<PackageReference Include="HarfBuzzSharp.NativeAssets.Win32" Version="8.3.1.5" GeneratePathProperty="true" />
<None Include="$(PkgSkiaSharp_NativeAssets_Win32)/LICENSE.txt;$(PkgSkiaSharp_NativeAssets_Win32)/THIRD-PARTY-NOTICES.txt"
Link="THIRD-PARTY/SkiaSharp-%(Filename)%(Extension)" CopyToPublishDirectory="PreserveNewest" />
<None Include="$(PkgHarfBuzzSharp_NativeAssets_Win32)/LICENSE.txt;$(PkgHarfBuzzSharp_NativeAssets_Win32)/THIRD-PARTY-NOTICES.txt"
Link="THIRD-PARTY/HarfBuzzSharp-%(Filename)%(Extension)" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup Condition="'$(VismWindows)' != 'true' or '$(PublishAot)' != 'true'">
<Compile Remove="NativeWindowsHost.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' != 'net8.0-windows'">
<Compile Remove="WindowsHost.cs" />
</ItemGroup>
Expand Down
7 changes: 3 additions & 4 deletions build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading