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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

## Unreleased

## 1.0.0-beta.1.3.2

- Classic shortcuts now work with games that start through a loader (a small `.exe` that creates the real game, e.g. `main.bin`, and exits). VNAR stays in the background while the game runs and gives the game's windows the shortcut's AppUserModelID, relaunch command, name and icon, so the game groups with its pinned shortcut instead of showing a second taskbar button, and the running game can be pinned (it pins a VNAR shortcut, not the loader's `.bin`).
- Classic launches of games that run as administrator (marked in VNAR, `requireAdministrator`/`highestAvailable` in the executable's manifest, or Windows' "Run as administrator" compatibility setting) start an elevated VNAR first, so it can set the identity on the game's elevated windows. There is still a single UAC prompt: the elevated VNAR starts Locale Emulator, which does not ask again. The elevated copy receives the data folder and the shortcut's icon as arguments, so it also works when UAC runs it as another user. Cancelling UAC cancels the launch, as before.
- Games started from the library window (Play or double-click) go through the same path in a separate VNAR process: their windows get the game's AppUserModelID, so they group with a pinned classic shortcut instead of showing a second button, and they are marked as not pinnable, so pinning a running game can no longer pin its executable without Locale Emulator. Pinning stays a deliberate choice made with a classic shortcut. Administrator games get the same single-UAC elevation, and the launch keeps being watched if the library window is closed.
- `VNAR.ShellTests` checks that a window owned by another process in the game folder receives that identity (pinnable for shortcut launches, not pinnable for library launches), and that windows from other folders are left alone. `VNAR.CoreTests` covers which games are treated as running as administrator.

## 1.0.0-beta.1.3.1

- Fix classic (`.lnk`) shortcuts for games whose executable, folder or name has Japanese (or other non-ANSI) characters. They were written through `WScript.Shell`, which turned those characters into `?`, so the icon pointed to a file that does not exist and Windows showed VNAR's icon instead of the game's, making the shortcut look like a modern one. Classic shortcuts are now written with the Unicode Shell Link API. Shortcuts created with Beta 1.3 for those games need to be created again.
Expand Down
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
GitHub release tag all derive from this value.
-->
<PropertyGroup>
<Version>1.0.0-beta.1.3.1</Version>
<Version>1.0.0-beta.1.3.2</Version>
<!-- Keep ProductVersion exactly equal to <Version> (no "+commit" suffix). -->
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
</PropertyGroup>
Expand Down
83 changes: 81 additions & 2 deletions LocaleGameHub/App.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Text;
using System.Windows;
using System.Windows.Threading;
using LocaleGameHub.Models;
using LocaleGameHub.Services;

namespace LocaleGameHub;
Expand All @@ -16,6 +17,17 @@ protected override void OnStartup(StartupEventArgs e)

try
{
// An elevated copy started for a classic launch gets the data folder of the
// VNAR that started it (UAC may run it as another user). This must happen
// before anything reads AppDataPaths.
var isElevatedRelaunch = false;
var dataDir = ElevationService.GetArgument(e.Args, ElevationService.DataDirArgument);
if (!string.IsNullOrWhiteSpace(dataDir) && Directory.Exists(dataDir))
{
Environment.SetEnvironmentVariable(AppDataPaths.DataDirOverrideVariable, dataDir);
isElevatedRelaunch = true;
}

var launch = ParseLaunchRequest(e.Args, out var gameId);
var isGameLaunch = launch != LaunchRequest.None;

Expand Down Expand Up @@ -50,7 +62,37 @@ protected override void OnStartup(StartupEventArgs e)

if (isGameLaunch)
{
LaunchFromShortcut(preferences, gameId);
var game = FindGame(preferences, gameId);
if (launch == LaunchRequest.Classic)
{
var fromLibrary = ElevationService.HasFlag(e.Args, ElevationService.FromLibraryArgument);
var relaunchIcon = ElevationService.GetArgument(e.Args, ElevationService.RelaunchIconArgument)
?? GameWindowIdentityService.ResolveRelaunchIcon(game);

// A game that runs as administrator needs an elevated VNAR to set
// its windows' identity. Hand the launch to an elevated copy: the
// user still gets a single UAC prompt (instead of Locale Emulator's).
if (!isElevatedRelaunch && !ElevationService.IsCurrentProcessElevated() &&
ElevationService.GameRunsElevated(game))
{
var result = ElevationService.RelaunchElevated(ShortcutService.ResolveVnarExecutable(), game.Id, relaunchIcon, fromLibrary);
if (result != ElevationService.RelaunchResult.Failed)
{
Shutdown(0); // started, or the user said no to UAC
return;
}
// Elevation is not available: launch as before.
}

// The library window already recorded the launch.
LaunchGame(preferences, game, recordLaunch: !fromLibrary);
// Stay in the background while the game runs, giving its windows
// the shortcut's identity (see GameWindowIdentityService).
WatchGameWindows(game, relaunchIcon, preventPinning: fromLibrary);
return;
}

LaunchGame(preferences, game);
Shutdown(0);
return;
}
Expand Down Expand Up @@ -99,7 +141,7 @@ private static LaunchRequest ParseLaunchRequest(string[] args, out Guid gameId)
return LaunchRequest.None;
}

private static void LaunchFromShortcut(LibraryService library, Guid gameId)
private static GameEntry FindGame(LibraryService library, Guid gameId)
{
var game = library.Games.FirstOrDefault(g => g.Id == gameId);
if (game is null)
Expand All @@ -114,13 +156,50 @@ private static void LaunchFromShortcut(LibraryService library, Guid gameId)
throw new InvalidOperationException(message);
}

return game;
}

private static void LaunchGame(LibraryService library, GameEntry game, bool recordLaunch = true)
{
var locale = new LocaleEmulatorService(library);
locale.Launch(game);
if (!recordLaunch) return;
// Re-reads the library under the shared lock so edits made meanwhile in the
// library window are not overwritten by this process's startup snapshot.
library.RecordLaunch(game.Id, DateTime.UtcNow);
}

private void WatchGameWindows(GameEntry game, string relaunchIcon, bool preventPinning)
{
var thread = new Thread(() =>
{
try
{
var watcher = new GameWindowIdentityService(
game,
ShortcutService.ResolveVnarExecutable(),
relaunchIcon,
preventPinning);
watcher.Watch();
}
catch (Exception ex)
{
// The game is already running; only the taskbar grouping is lost.
WriteCrashLog("GameWindowIdentity", ex);
}
finally
{
Dispatcher.BeginInvoke(new Action(() => Shutdown(0)));
}
})
{
IsBackground = true,
Name = "VNAR game window identity"
};
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}

private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
WriteCrashLog("DispatcherUnhandledException", e.Exception);
Expand Down
27 changes: 26 additions & 1 deletion LocaleGameHub/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -665,7 +665,13 @@ private void LaunchGame(GameEntry game)
{
try
{
_locale.Launch(game);
// Validate here (missing LEProc opens Settings below), then hand the launch
// to a separate VNAR process, like a classic shortcut: it gives the game's
// windows their identity so they group with a pinned shortcut, and it keeps
// working if this window is closed while playing.
var start = _locale.BuildStartInfo(game);
if (!TryLaunchThroughVnar(game))
System.Diagnostics.Process.Start(start);
game.LastPlayedUtc = DateTime.UtcNow;
_library.SaveGames();
}
Expand All @@ -691,6 +697,25 @@ private void LaunchGame(GameEntry game)
}
}

private static bool TryLaunchThroughVnar(GameEntry game)
{
try
{
var vnarExe = ShortcutService.ResolveVnarExecutable();
using var process = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(
vnarExe, $"--launch {game.Id:D} {ElevationService.FromLibraryArgument}")
{
UseShellExecute = false,
WorkingDirectory = Path.GetDirectoryName(vnarExe) ?? AppContext.BaseDirectory
});
return process is not null;
}
catch
{
return false;
}
}

private void GameCard_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
if (sender is not FrameworkElement { Tag: GameEntry game } card) return;
Expand Down
60 changes: 60 additions & 0 deletions LocaleGameHub/Services/ElevationRules.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System.Text.RegularExpressions;

namespace LocaleGameHub.Services;

/// <summary>
/// Decides whether a game will run as administrator. Pure logic, so it can be tested
/// on any OS; <see cref="ElevationService"/> gathers the inputs on Windows.
/// </summary>
public static class ElevationRules
{
public const string RequireAdministrator = "requireAdministrator";
public const string HighestAvailable = "highestAvailable";
public const string AsInvoker = "asInvoker";

private static readonly Regex LevelPattern = new(
"requestedExecutionLevel[^>]*?\\blevel\\s*=\\s*[\"']([A-Za-z]+)[\"']",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

/// <summary>The requestedExecutionLevel of an application manifest, or null if it has none.</summary>
public static string? ManifestLevel(string? manifestXml)
{
if (string.IsNullOrWhiteSpace(manifestXml)) return null;
var match = LevelPattern.Match(manifestXml);
if (!match.Success) return null;

var level = match.Groups[1].Value;
foreach (var known in new[] { RequireAdministrator, HighestAvailable, AsInvoker })
if (level.Equals(known, StringComparison.OrdinalIgnoreCase)) return known;
return null;
}

/// <summary>
/// Reads Windows' compatibility layers for an executable (the "Run this program as
/// an administrator" checkbox stores RUNASADMIN; RUNASHIGHEST also exists).
/// Returns the matching manifest-style level, or null.
/// </summary>
public static string? CompatibilityLevel(string? layers)
{
if (string.IsNullOrWhiteSpace(layers)) return null;
var flags = layers.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (flags.Any(f => f.Equals("RUNASADMIN", StringComparison.OrdinalIgnoreCase))) return RequireAdministrator;
if (flags.Any(f => f.Equals("RUNASHIGHEST", StringComparison.OrdinalIgnoreCase))) return HighestAvailable;
return null;
}

/// <param name="markedAdmin">The game uses VNAR's administrator Locale Emulator profile.</param>
/// <param name="manifestLevel">From the exe's manifest (see <see cref="ManifestLevel"/>).</param>
/// <param name="compatibilityLevel">From Windows' compatibility settings (see <see cref="CompatibilityLevel"/>).</param>
/// <param name="userCanElevateSilently">
/// The user is an administrator running with a filtered token: "highestAvailable"
/// elevates for them, while for a standard user it runs as invoker.
/// </param>
public static bool GameRunsElevated(bool markedAdmin, string? manifestLevel, string? compatibilityLevel, bool userCanElevateSilently)
{
if (markedAdmin) return true;
if (manifestLevel == RequireAdministrator || compatibilityLevel == RequireAdministrator) return true;
if (manifestLevel == HighestAvailable || compatibilityLevel == HighestAvailable) return userCanElevateSilently;
return false;
}
}
Loading
Loading