From bbe8f3cf83d71f0404f375d850029bbe8e80b0d0 Mon Sep 17 00:00:00 2001 From: Code-Leafy <186628927+Code-Leafy@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:30:40 +0330 Subject: [PATCH] Repair install state for games that are already on disk Steam treats a game as installed purely on the appmanifest being there. When it is missing, or present but blanked to StateFlags 1538 with an empty InstalledDepots, the payload is unreachable: the library entry is dead and Install re-downloads everything over files that are already complete. GetInstallDir could only report that state back, because it resolves the folder from the appmanifest and nothing ever writes one. The folder is found from appinfo instead (installdir + launch exe, matched on the normalized name and required to contain that exe), and the appmanifest is written against it under whatever name it actually has, so a renamed or unpacked folder does not have to be renamed back first. Guards for the ways this could otherwise bite: the app is skipped when a manifest already carries FullyInstalled, an existing manifest is backed up before being replaced, and an orphaned staging folder is cleared so Steam reconfigures instead of resuming a dead download. A shared depot the lua references is registered on the app that owns it, since a missing one aborts the depot dependency build with Invalid content configuration. Steam is stopped for the write and restarted after, the same way appinfo edits are applied. Two new strings are English-only for now and listed in PENDING_TRANSLATION. --- scripts/check-i18n.py | 5 +- src/LuaToolsGui/App.xaml.cs | 1 + src/LuaToolsGui/Resources/Strings.Designer.cs | 2 + src/LuaToolsGui/Resources/Strings.resx | 2 + src/LuaToolsGui/Services/InstallDirMatcher.cs | 102 +++++ .../Services/InstallStateRepairService.cs | 369 ++++++++++++++++++ .../Services/SteamLibraryService.cs | 69 +++- src/LuaToolsGui/Services/SteamService.cs | 7 + src/LuaToolsGui/ViewModels/FixesViewModel.cs | 17 +- .../InstallDirMatcherTests.cs | 126 ++++++ .../LuaToolsGui.Tests/InstallStateAcfTests.cs | 102 +++++ .../InstallStateRepairRoundTripTests.cs | 213 ++++++++++ 12 files changed, 1012 insertions(+), 3 deletions(-) create mode 100644 src/LuaToolsGui/Services/InstallDirMatcher.cs create mode 100644 src/LuaToolsGui/Services/InstallStateRepairService.cs create mode 100644 tests/LuaToolsGui.Tests/InstallDirMatcherTests.cs create mode 100644 tests/LuaToolsGui.Tests/InstallStateAcfTests.cs create mode 100644 tests/LuaToolsGui.Tests/InstallStateRepairRoundTripTests.cs diff --git a/scripts/check-i18n.py b/scripts/check-i18n.py index 48d649f6..6a6dc1f6 100644 --- a/scripts/check-i18n.py +++ b/scripts/check-i18n.py @@ -28,7 +28,10 @@ # This list IS the handoff to the translation pass. When a feature's UI is final: translate its keys # across every Strings..resx, clear them from here, and this check goes back to demanding full # parity. Anything left here is untranslated in all 29 languages. -PENDING_TRANSLATION: set[str] = set() +PENDING_TRANSLATION: set[str] = { + "Fixes_Toast_Installed", + "Fixes_Toast_Installed_Body", +} # Empty on purpose: every key is translated in all 29 languages, so the parity check above is # unconditional. Add a key here ONLY while its feature's UI is still moving, and clear it again # as soon as the translations land. Anything listed is English-only for every user. diff --git a/src/LuaToolsGui/App.xaml.cs b/src/LuaToolsGui/App.xaml.cs index 792698fc..15b6a1b4 100644 --- a/src/LuaToolsGui/App.xaml.cs +++ b/src/LuaToolsGui/App.xaml.cs @@ -35,6 +35,7 @@ public App() services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/LuaToolsGui/Resources/Strings.Designer.cs b/src/LuaToolsGui/Resources/Strings.Designer.cs index a67f0f8c..87be5b9d 100644 --- a/src/LuaToolsGui/Resources/Strings.Designer.cs +++ b/src/LuaToolsGui/Resources/Strings.Designer.cs @@ -296,6 +296,8 @@ public static class Strings public static string Fixes_Toast_FixInstalled_Body => Get(nameof(Fixes_Toast_FixInstalled_Body)); public static string Fixes_Toast_GameNotFound => Get(nameof(Fixes_Toast_GameNotFound)); public static string Fixes_Toast_GameNotFound_Body => Get(nameof(Fixes_Toast_GameNotFound_Body)); + public static string Fixes_Toast_Installed => Get(nameof(Fixes_Toast_Installed)); + public static string Fixes_Toast_Installed_Body => Get(nameof(Fixes_Toast_Installed_Body)); public static string Fixes_Toast_PartiallyApplied => Get(nameof(Fixes_Toast_PartiallyApplied)); public static string Fixes_Toast_PartiallyApplied_Body => Get(nameof(Fixes_Toast_PartiallyApplied_Body)); public static string Fixes_Toast_FixApplied => Get(nameof(Fixes_Toast_FixApplied)); diff --git a/src/LuaToolsGui/Resources/Strings.resx b/src/LuaToolsGui/Resources/Strings.resx index 3799bb6d..51a61642 100644 --- a/src/LuaToolsGui/Resources/Strings.resx +++ b/src/LuaToolsGui/Resources/Strings.resx @@ -346,6 +346,8 @@ This deletes the .lua files from Steam\config\stplug-in. Fix installed {0} manifest installed. Game not found + Install repaired + Steam could not find {0} where it expected it. It points at your existing folder now, so nothing gets downloaded again. Install {0} in Steam first, then apply the fix. Fix partially applied {0} file(s) couldn't be written. Close the game and try again. diff --git a/src/LuaToolsGui/Services/InstallDirMatcher.cs b/src/LuaToolsGui/Services/InstallDirMatcher.cs new file mode 100644 index 00000000..f3ea1fb9 --- /dev/null +++ b/src/LuaToolsGui/Services/InstallDirMatcher.cs @@ -0,0 +1,102 @@ +using System.IO; + +namespace LuaToolsGui.Services; + +/// +/// Picks the folder a game is really installed in when nothing in Steam points at it. +/// +/// +/// +/// installdir is an appinfo value, and can only +/// follow what an appmanifest states. A folder that was renamed by hand, unpacked out of a repack, or +/// copied in from another drive never matches it, so the payload sits on disk unreachable: no install +/// row, and Steam re-downloads what is already there. +/// +/// +/// Matching is deliberately conservative — normalized-name equality only, plus a requirement that the +/// app's own launch executable is inside. That keeps sibling folders such as Steamworks Shared +/// from ever being mistaken for a game. No fuzzy distance, no "contains": with a fixed, small +/// candidate list, a wrong match is much more expensive than no match. +/// +/// +public static class InstallDirMatcher +{ + /// + /// Best candidate folder under for , or + /// null. is the appinfo launch executable, relative to the install root + /// (it can contain subfolders); when null, any executable will do. + /// + public static string? Match(string? installDir, string? launchExe, IEnumerable? candidates) + { + if (candidates is null || string.IsNullOrWhiteSpace(installDir)) return null; + + string wanted = Normalize(installDir); + if (wanted.Length == 0) return null; + + string? best = null; + int bestScore = 0; + + foreach (string candidate in candidates) + { + string name = Path.GetFileName(candidate.TrimEnd(Path.DirectorySeparatorChar)); + if (name.Length == 0) continue; + + int score = string.Equals(name, installDir.Trim(), StringComparison.OrdinalIgnoreCase) + ? 2 + : string.Equals(Normalize(name), wanted, StringComparison.Ordinal) ? 1 : 0; + if (score == 0 || score < bestScore) continue; + + if (!HasLaunchExe(candidate, launchExe)) continue; + + // Equal score: keep the first, so the result does not depend on enumeration order beyond it. + if (score > bestScore) { best = candidate; bestScore = score; } + } + + return best; + } + + /// + /// Lowercase, single-spaced, minus the decoration people add when they copy a game around: a + /// trailing s ("Astroneer" vs "Astroneers"), version tails ("v1.2.3", "(1.0)"), and + /// "copy"/"backup" suffixes. Applied to both sides, so it never makes two different games equal. + /// + internal static string Normalize(string value) + { + string s = value.Trim().ToLowerInvariant(); + s = string.Join(' ', s.Split(' ', StringSplitOptions.RemoveEmptyEntries)); + + while (true) + { + int space = s.LastIndexOf(' '); + if (space <= 0) break; + + string tail = s[(space + 1)..]; + bool drop = + tail is "copy" or "kopie" or "copia" or "backup" || + VersionTail.IsMatch(tail); + if (!drop) break; + + s = s[..space].TrimEnd(); + } + + s = s.TrimEnd(' ', '.', '-', '_', '(', ')', '[', ']', ','); + if (s.Length > 4 && s.EndsWith('s')) s = s[..^1]; + return s; + } + + /// "v1.2.3", "(1.0)", "1.0.0.1" — the shapes a version suffix takes in a folder name. + private static readonly System.Text.RegularExpressions.Regex VersionTail = + new(@"^\(?v?[0-9]+(\.[0-9]+)+\)?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase); + + private static bool HasLaunchExe(string dir, string? launchExe) + { + try + { + if (!string.IsNullOrWhiteSpace(launchExe)) + return File.Exists(Path.Combine(dir, launchExe.Replace('/', '\\'))); + + return Directory.EnumerateFiles(dir, "*.exe", SearchOption.TopDirectoryOnly).Any(); + } + catch { return false; } + } +} diff --git a/src/LuaToolsGui/Services/InstallStateRepairService.cs b/src/LuaToolsGui/Services/InstallStateRepairService.cs new file mode 100644 index 00000000..03ec6941 --- /dev/null +++ b/src/LuaToolsGui/Services/InstallStateRepairService.cs @@ -0,0 +1,369 @@ +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using LuaToolsGui.Services.AppInfo; +using Microsoft.Extensions.Logging; + +namespace LuaToolsGui.Services; + +/// What a repair pass did. +/// An appmanifest was written; the game is now installed as far as Steam knows. +/// Why not, when is false. Logged, not shown. +/// The folder Steam is now pointed at, when repaired. +public readonly record struct InstallStateRepairResult(bool Repaired, string Reason, string? InstallDir) +{ + public static InstallStateRepairResult Fail(string reason) => new(false, reason, null); +} + +/// +/// Writes the appmanifest Steam needs for a game whose files are already on disk. +/// +/// +/// +/// Steam derives "installed" from steamapps\appmanifest_<appid>.acf alone. With the file +/// missing, or present but blanked to StateFlags 1538 (Update Required | Update Paused | Update +/// Started) with an empty InstalledDepots, there is no install row: the library entry is dead, +/// and "Install" downloads everything again over files that are already complete. Nothing in Steam +/// repairs that, and can only report it. +/// +/// +/// The folder is located through appinfo (never guessed), and it is written into the manifest as +/// installdir with its real name, so a ragged folder name is not something the user has to +/// rename away first. Depot ids, gids and sizes come from the pinned lua, which is the only honest +/// source for them; a depot with no gid is left out rather than invented. +/// +/// +/// Steam holds appmanifests in memory and rewrites them on exit, so the write only sticks with Steam +/// shut — the same reason stops it for appinfo edits. It is restarted +/// afterwards if the caller had it open. +/// +/// +public class InstallStateRepairService( + SteamService steam, SteamLibraryService library, ILogger log) +{ + /// Depot ids Steam never asks to install, mapped to the app that really owns them. + private static readonly Regex SharedOwner = new(@"[Ss]hared from [Aa]pp (\d+)"); + + /// Build number in the lua header (-- Build: 24816905), when the source writes one. + private static readonly Regex HeaderBuild = new(@"^\s*--\s*Build:\s*(\d+)", RegexOptions.Multiline); + + /// Steam's state bitfield in an appmanifest. 4 is FullyInstalled. + + /// + /// Locate the game on disk, then write the appmanifest for it. Never throws; every failure is a + /// reason. + /// + public async Task RepairAsync(long appId, CancellationToken ct = default) + { + bool wasRunning = SteamService.IsSteamRunning(); + if (wasRunning) steam.StopSteam(); + try { return await Task.Run(() => Repair(appId, ct), ct); } + finally { if (wasRunning) steam.StartSteam(); } + } + + /// The pass with Steam assumed closed. + public InstallStateRepairResult Repair(long appId, CancellationToken ct = default) + { + try + { + if (steam.EffectivePath is not { } steamRoot) return InstallStateRepairResult.Fail("steam-not-found"); + if (steam.AppInfoPath is not { } appInfoPath || !File.Exists(appInfoPath)) + return InstallStateRepairResult.Fail("no-appinfo"); + + string? installDir; + string name; + string launchExe; + using (var appInfo = new AppInfoFile(appInfoPath)) + { + var body = appInfo.ReadAppBody((int)appId); + if (body is null) return InstallStateRepairResult.Fail("no-appinfo"); + installDir = body.GetTable("config")?.GetText("installdir"); + name = body.GetText("common") is var _ && body.GetTable("common")?.GetText("name") is { } n + ? n : appId.ToString(); + launchExe = LaunchOption.ReadAll(body) + .FirstOrDefault(l => l.OsList is "" or "windows")?.Executable ?? ""; + } + + if (string.IsNullOrWhiteSpace(installDir)) return InstallStateRepairResult.Fail("no-installdir"); + + return RepairCore(appId, installDir, launchExe, name); + } + catch (Exception ex) + { + log.LogWarning(ex, "Install state repair for {AppId} failed", appId); + return InstallStateRepairResult.Fail("write-failed"); + } + } + + /// + /// The pass with the appinfo values already in hand, so it can run without an appinfo.vdf to read. + /// + internal InstallStateRepairResult RepairCore(long appId, string? installDir, string? launchExe, string name) + { + try + { + if (steam.EffectivePath is not { } steamRoot) return InstallStateRepairResult.Fail("steam-not-found"); + + // Already installed? Then this is not our problem to solve. An appmanifest existing is not + // enough: the shape being repaired is one that IS there but blanked to StateFlags 1538 + // (update required, empty InstalledDepots), so only a FullyInstalled bit counts. + foreach (string root in SteamLibraryService.GetLibraryRoots(steamRoot)) + { + string existing = Path.Combine(root, "steamapps", $"appmanifest_{appId}.acf"); + if (File.Exists(existing) && IsFullyInstalled(existing)) + return InstallStateRepairResult.Fail("already-installed"); + } + + if (library.FindAdoptable(installDir, launchExe) is not { } candidate) + return InstallStateRepairResult.Fail("no-candidate"); + + string acf = Path.Combine(candidate.SteamAppsDir, $"appmanifest_{appId}.acf"); + + var (depots, shared, buildId) = ReadLua(appId); + long size = DirectorySize(candidate.FullPath); + if (File.Exists(acf)) + File.Copy(acf, $"{acf}.bak-{DateTime.UtcNow:yyyyMMddHHmmss}", overwrite: true); + + string folderName = Path.GetFileName(candidate.FullPath); + File.WriteAllText( + acf, + BuildAcf(appId, name, folderName, depots, shared, size, buildId), + new UTF8Encoding(false)); + + EnsureLibraryIndexEntry(candidate.SteamAppsDir, appId, size); + EnsureSharedDepotsInstalled(candidate.SteamAppsDir, shared, depots); + WriteSteamAppId(candidate.FullPath, appId); + ClearStaging(candidate.SteamAppsDir, appId); + + log.LogInformation( + "Repaired install state for {AppId}: {Dir} ({Size} bytes, {Depots} depots, {Shared} shared)", + appId, candidate.FullPath, size, depots.Count, shared.Count); + + + return new InstallStateRepairResult(true, "ok", candidate.FullPath); + } + catch (Exception ex) + { + log.LogWarning(ex, "Install state repair for {AppId} failed", appId); + return InstallStateRepairResult.Fail("write-failed"); + } + } + + /// True when the manifest carries Steam's FullyInstalled bit (4). + private static bool IsFullyInstalled(string acfPath) + { + try + { + // Split on quotes: the token after "StateFlags" is its value. + string[] parts = File.ReadAllText(acfPath).Split('"'); + for (int i = 0; i < parts.Length - 1; i++) + { + if (!string.Equals(parts[i], "StateFlags", StringComparison.OrdinalIgnoreCase)) continue; + for (int j = i + 1; j < parts.Length; j++) + { + if (string.IsNullOrWhiteSpace(parts[j])) continue; + return int.TryParse(parts[j].Trim(), out int flags) && (flags & 4) != 0; + } + } + return false; + } + catch { return false; } + } + + /// + /// Depot ids, gids and sizes out of the pinned lua, plus the app that owns any shared depot. Gid and + /// size are needed per depot for the manifest; a depot with neither a live nor a commented pin + /// resolves to whatever Steam ships, so there is no honest gid to write and it is skipped. + /// + private (List<(long Id, string Gid, long Size)> Depots, + Dictionary Shared, + long BuildId) ReadLua(long appId) + { + var depots = new List<(long, string, long)>(); + var shared = new Dictionary(); + long buildId = 0; + + if (steam.StPlugInDir is not { } dir) return (depots, shared, buildId); + string path = Path.Combine(dir, $"{appId}.lua"); + if (!File.Exists(path)) return (depots, shared, buildId); + + string text; + try { text = File.ReadAllText(path); } catch { return (depots, shared, buildId); } + + var build = HeaderBuild.Match(text); + if (build.Success) long.TryParse(build.Groups[1].Value, out buildId); + + if (LuaFileParser.Parse(path, appId) is not { } lua) return (depots, shared, buildId); + + foreach (LuaEntry entry in lua.Entries) + { + if (!entry.HasKey || entry.Id == appId) continue; + + string? gid = lua.ActivePins.GetValueOrDefault(entry.Id) + ?? lua.CommentedPins.GetValueOrDefault(entry.Id); + if (gid is null) continue; + + depots.Add((entry.Id, gid, entry.SizeOnDisk ?? 0)); + + if (entry.Comment is { } comment && SharedOwner.Match(comment) is { Success: true } m + && long.TryParse(m.Groups[1].Value, out long owner) && owner != appId) + { + shared[entry.Id] = owner; + } + } + + return (depots, shared, buildId); + } + + /// + /// The appmanifest itself. Field order follows what Steam writes, so a diff against a real one only + /// ever shows the values. AutoUpdateBehavior 1 (only update on launch) is deliberate: the lua + /// describes one build, and letting the scheduler chase another the moment the entry appears would + /// undo the adoption. + /// + internal static string BuildAcf( + long appId, string name, string installDir, + IEnumerable<(long Id, string Gid, long Size)> depots, + IReadOnlyDictionary shared, + long sizeOnDisk, long buildId) + { + var sb = new StringBuilder(); + sb.Append("\"AppState\"\n{\n"); + Line(sb, "appid", appId.ToString()); + Line(sb, "Universe", "1"); + Line(sb, "name", name); + Line(sb, "StateFlags", "4"); // FullyInstalled + Line(sb, "installdir", installDir); + Line(sb, "SizeOnDisk", sizeOnDisk.ToString()); + Line(sb, "StagingSize", "0"); + Line(sb, "buildid", buildId.ToString()); + Line(sb, "UpdateResult", "0"); + foreach (string field in (string[])["BytesToDownload", "BytesDownloaded", "BytesToStage", "BytesStaged"]) + Line(sb, field, "0"); + Line(sb, "TargetBuildID", buildId.ToString()); + Line(sb, "AutoUpdateBehavior", "1"); + Line(sb, "AllowOtherDownloadsWhileRunning", "0"); + Line(sb, "ScheduledAutoUpdate", "0"); + + sb.Append("\t\"InstalledDepots\"\n\t{\n"); + foreach (var (id, gid, size) in depots) + { + sb.Append($"\t\t\"{id}\"\n\t\t{{\n"); + Line(sb, "manifest", gid, 3); + Line(sb, "size", size.ToString(), 3); + sb.Append("\t\t}\n"); + } + sb.Append("\t}\n"); + + sb.Append("\t\"SharedDepots\"\n\t{\n"); + foreach (var (id, owner) in shared) + Line(sb, id.ToString(), owner.ToString(), 2); + sb.Append("\t}\n"); + + sb.Append("\t\"UserConfig\"\n\t{\n"); + Line(sb, "language", "english", 2); + sb.Append("\t}\n\t\"MountedConfig\"\n\t{\n\t}\n}\n"); + return sb.ToString(); + + static void Line(StringBuilder sb, string key, string value, int depth = 2) => + sb.Append(new string('\t', depth)).Append('"').Append(key).Append("\"\t\t\"") + .Append(Escape(value)).Append("\"\n"); + } + + /// VDF escapes backslashes and quotes inside a value. + private static string Escape(string value) => value.Replace(@"\", @"\\").Replace("\"", "\\\""); + + private static long DirectorySize(string dir) + { + long total = 0; + try + { + foreach (string file in Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories)) + { + try { total += new FileInfo(file).Length; } catch { } + } + } + catch { } + return total; + } + + /// + /// Add the app to its library's libraryfolders.vdf apps block. Steam rebuilds this on + /// its own, but only for apps it already knows about; an app it has never seen needs the entry to be + /// offered as installed at all. + /// + private void EnsureLibraryIndexEntry(string steamappsDir, long appId, long size) + { + string vdf = Path.Combine(steamappsDir, "libraryfolders.vdf"); + if (!File.Exists(vdf)) return; + + string text; + try { text = File.ReadAllText(vdf); } catch { return; } + if (text.Contains($"\"{appId}\"")) return; + + // Insert into the apps block of the folder entry that contains this steamapps dir. + string library = Path.GetDirectoryName(steamappsDir)!; + int at = text.IndexOf(Escape(library), StringComparison.OrdinalIgnoreCase); + if (at < 0) return; + + int apps = text.IndexOf("\"apps\"", at, StringComparison.OrdinalIgnoreCase); + if (apps < 0) return; + + int brace = text.IndexOf('{', apps); + if (brace < 0) return; + + string insert = $"\n\t\t\t\"{appId}\"\t\t\"{size}\""; + + try { File.WriteAllText(vdf, text.Insert(brace + 1, insert), new UTF8Encoding(false)); } + catch { } + } + + /// + /// A shared depot (VC runtime, DirectX) only resolves if the app that OWNS it lists it as installed. + /// When it does not, the depot dependency build aborts with "Invalid content configuration" and the + /// whole app update dies before it starts, which is exactly the state this repair exists to leave. + /// + private void EnsureSharedDepotsInstalled( + string steamappsDir, Dictionary shared, List<(long Id, string Gid, long Size)> depots) + { + foreach (var (depotId, owner) in shared) + { + string ownerAcf = Path.Combine(steamappsDir, $"appmanifest_{owner}.acf"); + if (!File.Exists(ownerAcf)) continue; + + string text; + try { text = File.ReadAllText(ownerAcf); } catch { continue; } + if (text.Contains($"\"{depotId}\"")) continue; + + int at = text.IndexOf("\"InstalledDepots\"", StringComparison.OrdinalIgnoreCase); + int brace = at < 0 ? -1 : text.IndexOf('{', at); + if (brace < 0) continue; + + var entry = depots.FirstOrDefault(d => d.Id == depotId); + string gid = entry.Gid ?? "0"; + string insert = + $"\n\t\t\"{depotId}\"\n\t\t{{\n\t\t\t\"manifest\"\t\t\"{gid}\"\n\t\t\t\"size\"\t\t\"{entry.Size}\"\n\t\t}}"; + + try { File.WriteAllText(ownerAcf, text.Insert(brace + 1, insert), new UTF8Encoding(false)); } + catch { } + } + } + + /// Games launched from the exe (not the library) resolve their appid from this file. + private void WriteSteamAppId(string installDir, long appId) + { + try { File.WriteAllText(Path.Combine(installDir, "steam_appid.txt"), appId.ToString()); } + catch { } + } + + /// + /// An orphaned staging folder makes Steam resume a half-finished download instead of reconfiguring + /// against the files that are there. + /// + private void ClearStaging(string steamappsDir, long appId) + { + string staging = Path.Combine(steamappsDir, "downloading", appId.ToString()); + try { if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true); } + catch { } + } +} diff --git a/src/LuaToolsGui/Services/SteamLibraryService.cs b/src/LuaToolsGui/Services/SteamLibraryService.cs index a2143ce2..c511b6d7 100644 --- a/src/LuaToolsGui/Services/SteamLibraryService.cs +++ b/src/LuaToolsGui/Services/SteamLibraryService.cs @@ -1,5 +1,6 @@ using System.IO; using System.Text.RegularExpressions; +using LuaToolsGui.Services.AppInfo; namespace LuaToolsGui.Services; @@ -33,6 +34,11 @@ public record InstalledGame(long AppId, string Name, string InstallDir); /// Full path to the game's install folder (…\steamapps\common\<installdir>) if it exists on /// disk, else null (game not installed / Steam not found / unreadable). /// + /// + /// Follows the appmanifest first. When none describes the game it falls back to + /// : a copied or unpacked folder is on disk whether or not Steam + /// was ever told about it, and callers care about the files, not the paperwork. + /// public string? GetInstallDir(long appId) { try @@ -52,6 +58,10 @@ public record InstalledGame(long AppId, string Name, string InstallDir); string full = Path.Combine(library, "steamapps", "common", installDir); if (Directory.Exists(full)) return full; } + + // No appmanifest described it. Before giving up, look for the folder itself: the files being + // on disk under a name nobody recorded is not the same as the game being absent. + return GetInstallDirFallback(appId); } catch { /* unreadable VDF/ACF or odd path. Treat as not found */ } return null; @@ -108,7 +118,7 @@ public IEnumerable EnumerateInstalled() } /// Every Steam library root (the main install plus any added libraries). - private static IEnumerable GetLibraryRoots(string steamRoot) + public static IEnumerable GetLibraryRoots(string steamRoot) { // The main install is always a library. yield return steamRoot; @@ -128,6 +138,63 @@ private static IEnumerable GetLibraryRoots(string steamRoot) } } + /// A game folder that Steam has no install row for, but which is plainly the game. + /// The library's steamapps folder, where an appmanifest would go. + /// The install folder itself. + public sealed record AdoptCandidate(string SteamAppsDir, string FullPath); + + /// + /// The folder this app is sitting in with no appmanifest pointing at it, if there is one. + /// + /// + /// Only reached when the manifest walk found nothing, which is the copy/repack case: the files are + /// there under a name an installdir does not agree with. The matching rule lives in + /// ; this only supplies the candidates. + /// + public AdoptCandidate? FindAdoptable(string? installDir, string? launchExe) + { + if (steam.EffectivePath is not { } steamRoot) return null; + + foreach (string library in GetLibraryRoots(steamRoot)) + { + string steamapps = Path.Combine(library, "steamapps"); + string common = Path.Combine(steamapps, "common"); + + string[] dirs; + try + { + if (!Directory.Exists(common)) continue; + dirs = Directory.GetDirectories(common); + } + catch { continue; } + + if (InstallDirMatcher.Match(installDir, launchExe, dirs) is { } match) + return new AdoptCandidate(steamapps, match); + } + + return null; + } + + /// + /// The install folder if it exists on disk. Falls back to the appinfo installdir when no appmanifest + /// describes the game, so a folder Steam has not been told about yet still resolves. + /// + public string? GetInstallDirFallback(long appId) + { + try + { + if (steam.AppInfoPath is not { } appInfoPath || !File.Exists(appInfoPath)) return null; + + using var appInfo = new AppInfoFile(appInfoPath); + return appInfo.ReadAppBody((int)appId) is { } body + ? FindAdoptable( + body.GetTable("config")?.GetText("installdir"), + LaunchOption.ReadAll(body).FirstOrDefault()?.Executable)?.FullPath + : null; + } + catch { return null; } + } + /// VDF strings escape backslashes as "\\"; collapse to a real path. private static string Unescape(string s) => s.Replace(@"\\", @"\"); } diff --git a/src/LuaToolsGui/Services/SteamService.cs b/src/LuaToolsGui/Services/SteamService.cs index 26c940b5..8cbbcdac 100644 --- a/src/LuaToolsGui/Services/SteamService.cs +++ b/src/LuaToolsGui/Services/SteamService.cs @@ -102,6 +102,13 @@ public static string? SteamLanguage public string? LegacyDepotCacheDir => EffectivePath is { } p ? Path.Combine(p, "config", "depotcache") : null; + /// + /// Full path to appcache\appinfo.vdf, or null if Steam isn't located. Every app's install metadata + /// lives here, including config.installdir and the launch executables. + /// + public string? AppInfoPath => + EffectivePath is { } p ? Path.Combine(p, "appcache", "appinfo.vdf") : null; + /// Open a store/steam URL or file path with the shell (browser, Steam client, Explorer). public static void OpenUrl(string url) => Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); diff --git a/src/LuaToolsGui/ViewModels/FixesViewModel.cs b/src/LuaToolsGui/ViewModels/FixesViewModel.cs index 6decfa39..9083ffe4 100644 --- a/src/LuaToolsGui/ViewModels/FixesViewModel.cs +++ b/src/LuaToolsGui/ViewModels/FixesViewModel.cs @@ -119,11 +119,12 @@ public partial class FixesViewModel : PagedListViewModel private readonly ManifestJobFactory jobs; private readonly SteamLibraryService library; private readonly SteamService steam; + private readonly InstallStateRepairService repair; public FixesViewModel( LuaToolsApiClient api, AuthService auth, CoverCache covers, ToastService toast, SettingsService settings, DownloadQueue queue, ManifestJobFactory jobs, - SteamLibraryService library, SteamService steam) + SteamLibraryService library, SteamService steam, InstallStateRepairService repair) { this.api = api; this.auth = auth; @@ -134,6 +135,7 @@ public FixesViewModel( this.jobs = jobs; this.library = library; this.steam = steam; + this.repair = repair; InitPageSize(settings.FixesPageSize); } @@ -373,6 +375,19 @@ private async Task OpenGame(FixGameCardVm game) string? installDir = long.TryParse(game.AppId, out long gameAppId) ? await Task.Run(() => library.GetInstallDir(gameAppId)) : null; + + // Files can be sitting on disk with no install row pointing at them, which is what a + // copied or unpacked folder looks like. Fix that once here, instead of having every fix + // row below report "not installed" for a game the user is plainly looking at. + // Best-effort: if it fails, the old behaviour is untouched. + if (installDir is null && long.TryParse(game.AppId, out long repairAppId) + && await repair.RepairAsync(repairAppId) is { Repaired: true } repaired) + { + installDir = repaired.InstallDir; + toast.Show(Resources.Strings.Fixes_Toast_Installed, + string.Format(Resources.Strings.Fixes_Toast_Installed_Body, game.Name)); + } + foreach (var f in _allFixes) { f.GameInstalled = installDir is not null; diff --git a/tests/LuaToolsGui.Tests/InstallDirMatcherTests.cs b/tests/LuaToolsGui.Tests/InstallDirMatcherTests.cs new file mode 100644 index 00000000..c937efe8 --- /dev/null +++ b/tests/LuaToolsGui.Tests/InstallDirMatcherTests.cs @@ -0,0 +1,126 @@ +using System.IO; +using LuaToolsGui.Services; +using Xunit; + +namespace LuaToolsGui.Tests; + +/// +/// Choosing the folder a game is actually in, for games Steam has no install row for. +/// +/// +/// This decides which directory gets an appmanifest written against it, so a wrong answer is not +/// cosmetic: it points Steam at the wrong folder and the entry has to be repaired again by hand. The +/// tests below are mostly about what the matcher REFUSES — a shared redist folder, a sibling game whose +/// name merely starts the same, a folder with no executable in it. +/// +public class InstallDirMatcherTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "lt-adopt-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + try { Directory.Delete(_root, recursive: true); } catch { } + GC.SuppressFinalize(this); + } + + /// Create a candidate folder, optionally with an exe at a relative path. + private string Dir(string name, string? exe = "game.exe") + { + string full = Path.Combine(_root, name); + Directory.CreateDirectory(full); + if (exe is not null) + { + string target = Path.Combine(full, exe); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + File.WriteAllText(target, "MZ"); + } + return full; + } + + private string? Match(string? installDir, string? exe, params string[] dirs) => + InstallDirMatcher.Match(installDir, exe, dirs); + + [Fact] + public void ExactName_Wins() + { + string wanted = Dir("ASTRONEER"); + Dir("ASTRONEERs", "other.exe"); + + Assert.Equal(wanted, Match("ASTRONEER", "game.exe", Directory.GetDirectories(_root))); + } + + /// The actual reported shape: a trailing s on the folder, neither side sanitized for it. + [Fact] + public void TrailingS_StillMatches() + { + string wanted = Dir("ASTRONEERs"); + + Assert.Equal(wanted, Match("ASTRONEER", "game.exe", Directory.GetDirectories(_root))); + } + + [Fact] + public void ExeInSubfolder_Matches() + { + string wanted = Dir("Astro", Path.Combine("Binaries", "Win64", "Astro-Win64-Shipping.exe")); + + Assert.Equal(wanted, Match("Astro", "Binaries/Win64/Astro-Win64-Shipping.exe", Directory.GetDirectories(_root))); + } + + [Fact] + public void VersionSuffixAndCopyTail_AreIgnored() + { + string wanted = Dir("Elden Ring v1.10.1"); + + Assert.Equal(wanted, Match("Elden Ring", "game.exe", Directory.GetDirectories(_root))); + } + + /// Sibling redistributables sit right next to the games and must never be adopted. + [Fact] + public void UnrelatedFolder_DoesNotMatch() + { + Dir("Steamworks Shared"); + + Assert.Null(Match("ASTRONEER", "game.exe", Directory.GetDirectories(_root))); + } + + [Fact] + public void MatchingNameButNoExe_DoesNotMatch() + { + Dir("ASTRONEER", exe: null); + + Assert.Null(Match("ASTRONEER", "game.exe", Directory.GetDirectories(_root))); + } + + [Fact] + public void MissingLaunchExe_StillRequiresSomeExe() + { + string wanted = Dir("ASTRONEER"); + Dir("ASTRONEER copies", exe: null); + + Assert.Equal(wanted, Match("ASTRONEER", null, Directory.GetDirectories(_root))); + } + + [Fact] + public void NoInstallDir_DoesNotMatch() + { + Dir("ASTRONEER"); + + Assert.Null(Match(null, "game.exe", Directory.GetDirectories(_root))); + Assert.Null(Match(" ", "game.exe", Directory.GetDirectories(_root))); + } + + [Fact] + public void EmptyCandidateList_DoesNotMatch() + { + Assert.Null(Match("ASTRONEER", "game.exe", [])); + } + + [Theory] + [InlineData("ASTRONEERs", "astroneer")] + [InlineData(" ELDEN Ring ", "elden ring")] + [InlineData("Elden Ring (1.0)", "elden ring")] + [InlineData("Elden Ring - copy", "elden ring")] + [InlineData("Astroneer", "astroneer")] + public void Normalize_FoldsDecoration(string input, string expected) => + Assert.Equal(expected, InstallDirMatcher.Normalize(input)); +} diff --git a/tests/LuaToolsGui.Tests/InstallStateAcfTests.cs b/tests/LuaToolsGui.Tests/InstallStateAcfTests.cs new file mode 100644 index 00000000..7ac55c1e --- /dev/null +++ b/tests/LuaToolsGui.Tests/InstallStateAcfTests.cs @@ -0,0 +1,102 @@ +using LuaToolsGui.Services; +using Xunit; + +namespace LuaToolsGui.Tests; + +/// +/// The appmanifest a repair pass writes. +/// +/// +/// Steam reads these fields literally and silently misbehaves on the ones that matter: no +/// FullyInstalled bit means the entry stays an update, and without +/// AutoUpdateBehavior 1 the scheduler immediately chases a build the pinned lua was never +/// describing. So the assertions here are about the values being exactly the intended ones, and about +/// the escaping holding for the folder names people actually have. +/// +public class InstallStateAcfTests +{ + private static readonly (long Id, string Gid, long Size)[] Depots = [(1, "111", 10), (2, "222", 20)]; + + private static string Build( + string installDir = "ASTRONEER", + IReadOnlyDictionary? shared = null, + long buildId = 12345) => + InstallStateRepairService.BuildAcf( + 99, "ASTRONEER", installDir, Depots, shared ?? new Dictionary(), 4096, buildId); + + [Fact] + public void WritesFullyInstalled_WithNothingLeftToFetch() + { + string acf = Build(); + + Assert.Contains("\"StateFlags\"\t\t\"4\"", acf); + Assert.Contains("\"UpdateResult\"\t\t\"0\"", acf); + Assert.Contains("\"BytesToDownload\"\t\t\"0\"", acf); + Assert.Contains("\"StagingSize\"\t\t\"0\"", acf); + } + + [Fact] + public void PinsAutoUpdateToLaunchTime_SoTheAdoptedBuildIsNotImmediatelyReplaced() + { + Assert.Contains("\"AutoUpdateBehavior\"\t\t\"1\"", Build()); + } + + [Fact] + public void WritesEveryDepotWithItsGidAndSize() + { + string acf = Build(); + + Assert.Contains("\"1\"", acf); + Assert.Contains("\"manifest\"\t\t\"111\"", acf); + Assert.Contains("\"size\"\t\t\"10\"", acf); + Assert.Contains("\"manifest\"\t\t\"222\"", acf); + } + + [Fact] + public void RecordsTheInstallFolderAsItIs_NotARenamedOne() + { + Assert.Contains("\"installdir\"\t\t\"Stronghold Crusader Definitive Editions\"", Build("Stronghold Crusader Definitive Editions")); + } + + /// A quote or backslash in a folder name would otherwise end the value early. + [Fact] + public void EscapesTheInstallDir() + { + string acf = Build(@"Weird \ ""Game"""); + + Assert.Contains("Weird \\\\ \\\"Game\\\"", acf); + } + + [Fact] + public void WritesSharedDepotsWithTheirOwner() + { + string acf = Build(shared: new Dictionary { [228988] = 228980 }); + + Assert.Contains("\"SharedDepots\"", acf); + Assert.Contains("\"228988\"\t\t\"228980\"", acf); + } + + [Fact] + public void KeepsTheBuildIdFromTheLua() + { + Assert.Contains("\"buildid\"\t\t\"12345\"", Build(buildId: 12345)); + Assert.Contains("\"TargetBuildID\"\t\t\"12345\"", Build(buildId: 12345)); + } + + [Fact] + public void WritesTheRealSize() + { + Assert.Contains("\"SizeOnDisk\"\t\t\"4096\"", Build()); + } + + [Fact] + public void NoDepots_StillProducesAValidManifest() + { + string acf = InstallStateRepairService.BuildAcf( + 99, "X", "X", [], new Dictionary(), 0, 0); + + Assert.Contains("\"InstalledDepots\"", acf); + Assert.Contains("\"StateFlags\"\t\t\"4\"", acf); + Assert.EndsWith("}\n", acf); + } +} diff --git a/tests/LuaToolsGui.Tests/InstallStateRepairRoundTripTests.cs b/tests/LuaToolsGui.Tests/InstallStateRepairRoundTripTests.cs new file mode 100644 index 00000000..800c25ee --- /dev/null +++ b/tests/LuaToolsGui.Tests/InstallStateRepairRoundTripTests.cs @@ -0,0 +1,213 @@ +using System.IO; +using LuaToolsGui.Services; +using Microsoft.Extensions.Logging.Abstractions; +using Xunit; + +namespace LuaToolsGui.Tests; + +/// +/// The repair pass end to end, against a throwaway Steam install. +/// +/// +/// This writes files into a user's library, so the parts worth pinning down are the ones that leave +/// something behind: it must not silently overwrite an appmanifest without a backup, must not touch a +/// game Steam already knows, and must not invent an entry for a folder it only thinks is the game. +/// +public class InstallStateRepairTests : IDisposable +{ + private const long AppId = 424242; + private const string InstallDir = "Some Game"; + + private readonly string _root = Path.Combine(Path.GetTempPath(), "lt-repair-" + Guid.NewGuid().ToString("N")); + private readonly SettingsService _settings = new(); + private readonly string? _originalOverride; + + private readonly SteamService _steam; + private readonly SteamLibraryService _library; + private readonly InstallStateRepairService _repair; + + private string SteamDir => Path.Combine(_root, "steam"); + private string SteamApps => Path.Combine(SteamDir, "steamapps"); + private string Common => Path.Combine(SteamApps, "common"); + private string Acf => Path.Combine(SteamApps, $"appmanifest_{AppId}.acf"); + + public InstallStateRepairTests() + { + _originalOverride = _settings.SteamPathOverride; + + Directory.CreateDirectory(Path.Combine(SteamDir, "config", "stplug-in")); + Directory.CreateDirectory(Common); + File.WriteAllText(Path.Combine(SteamApps, "libraryfolders.vdf"), + "\"libraryfolders\"\n{\n\t\"0\"\n\t{\n\t\t\"path\"\t\t\"" + SteamDir.Replace(@"\", @"\\") + + "\"\n\t\t\"apps\"\n\t\t{\n\t\t}\n\t}\n}\n"); + + _settings.SteamPathOverride = SteamDir; + _steam = new SteamService(_settings); + _library = new SteamLibraryService(_steam); + _repair = new InstallStateRepairService(_steam, _library, NullLogger.Instance); + } + + public void Dispose() + { + _settings.SteamPathOverride = _originalOverride; + try { Directory.Delete(_root, recursive: true); } catch { } + GC.SuppressFinalize(this); + } + + /// A game folder under the name Steam has no record of, with its exe in place. + private string GameFolder(string name = InstallDir + "s") + { + string dir = Path.Combine(Common, name); + Directory.CreateDirectory(dir); + File.WriteAllText(Path.Combine(dir, "game.exe"), "MZ"); + File.WriteAllText(Path.Combine(dir, "data.pak"), new string('x', 512)); + return dir; + } + + private InstallStateRepairResult Run() => _repair.RepairCore(AppId, InstallDir, "game.exe", "Some Game"); + + [Fact] + public void AdoptsTheFolderUnderItsRealName() + { + GameFolder(); + + var result = Run(); + + Assert.True(result.Repaired); + Assert.True(File.Exists(Acf)); + Assert.Contains("\"installdir\"\t\t\"Some Games\"", File.ReadAllText(Acf)); + Assert.Contains("\"StateFlags\"\t\t\"4\"", File.ReadAllText(Acf)); + } + + [Fact] + public void TheResolvedFolderIsReturned() + { + string dir = GameFolder(); + + Assert.Equal(dir, Run().InstallDir); + } + + [Fact] + public void SizesTheRealFolder() + { + GameFolder(); + + Run(); + + // 512 bytes of pak plus the 2-byte exe. + Assert.Contains("\"SizeOnDisk\"\t\t\"514\"", File.ReadAllText(Acf)); + } + + [Fact] + public void AddsTheAppToTheLibraryIndex() + { + GameFolder(); + + Run(); + + string vdf = File.ReadAllText(Path.Combine(SteamApps, "libraryfolders.vdf")); + Assert.Contains($"\"{AppId}\"", vdf); + } + + [Fact] + public void WritesTheAppIdForLaunchesOutsideSteam() + { + string dir = GameFolder(); + + Run(); + + Assert.Equal(AppId.ToString(), File.ReadAllText(Path.Combine(dir, "steam_appid.txt"))); + } + + /// An orphaned staging folder makes Steam resume a download instead of reconfiguring. + [Fact] + public void ClearsOrphanedStaging() + { + GameFolder(); + string staging = Path.Combine(SteamApps, "downloading", AppId.ToString()); + Directory.CreateDirectory(staging); + File.WriteAllText(Path.Combine(staging, "half.bin"), "x"); + + Run(); + + Assert.False(Directory.Exists(staging)); + } + + [Fact] + public void BacksUpAnExistingManifestBeforeReplacingIt() + { + GameFolder(); + File.WriteAllText(Acf, "\"AppState\"\n{\n\t\"StateFlags\"\t\t\"1538\"\n}\n"); + + var result = Run(); + Assert.True(result.Repaired, result.Reason); + + Assert.NotEmpty(Directory.GetFiles(SteamApps, "*.bak-*")); + Assert.Contains("\"StateFlags\"\t\t\"4\"", File.ReadAllText(Acf)); + } + + [Fact] + public void LeavesAnAlreadyInstalledGameAlone() + { + GameFolder(); + File.WriteAllText(Acf, "\"AppState\"\n{\n\t\"StateFlags\"\t\t\"4\"\n\t\"installdir\"\t\t\"Some Games\"\n}\n"); + + var result = Run(); + + Assert.False(result.Repaired); + Assert.Equal("already-installed", result.Reason); + Assert.Single(Directory.GetFiles(SteamApps, "appmanifest_*.acf")); // no backup either + } + + [Fact] + public void ReportsWhenThereIsNoFolderToAdopt() + { + var result = Run(); + + Assert.False(result.Repaired); + Assert.Equal("no-candidate", result.Reason); + Assert.False(File.Exists(Acf)); + } + + [Fact] + public void ReportsWhenTheFolderHasNoGameInIt() + { + Directory.CreateDirectory(Path.Combine(Common, InstallDir + "s")); // name matches, exe absent + + Assert.Equal("no-candidate", Run().Reason); + } + + /// + /// A shared depot only resolves when the app that owns it lists it. Without this the depot + /// dependency build aborts and the entry never leaves "update". + /// + [Fact] + public void RegistersAReferencedSharedDepotOnItsOwner() + { + GameFolder(); + string ownerAcf = Path.Combine(SteamApps, "appmanifest_228980.acf"); + File.WriteAllText(ownerAcf, + "\"AppState\"\n{\n\t\"appid\"\t\t\"228980\"\n\t\"InstalledDepots\"\n\t{\n\t}\n}\n"); + File.WriteAllText(Path.Combine(SteamDir, "config", "stplug-in", $"{AppId}.lua"), + $"-- Build: 777\naddappid({AppId}, 1, \"aaa\")\naddappid(228988, 1, \"bbb\") -- VC 2019 Redist (Shared from App 228980)\n-- setManifestid(228988, \"6645201662696499616\", 29212173)\n"); + + Run(); + + Assert.Contains("\"228988\"", File.ReadAllText(ownerAcf)); + Assert.Contains("6645201662696499616", File.ReadAllText(ownerAcf)); + } + + [Fact] + public void ReadsDepotsAndBuildFromTheLua() + { + GameFolder(); + File.WriteAllText(Path.Combine(SteamDir, "config", "stplug-in", $"{AppId}.lua"), + $"-- Build: 777\naddappid({AppId}, 1, \"aaa\")\naddappid({AppId + 1}, 1, \"bbb\")\n-- setManifestid({AppId + 1}, \"555666\", 1024)\n"); + + Run(); + + string acf = File.ReadAllText(Acf); + Assert.Contains("\"manifest\"\t\t\"555666\"", acf); + Assert.Contains("\"buildid\"\t\t\"777\"", acf); + } +}