mirror of
https://git.triforceproject.com/triforce/source
synced 2026-11-20 08:39:58 -04:00
Triforce v0.5.2
The new launcher (Windows and Linux: the game's own look, music and settings, saves and mods pages, smaller updates in parts), benchmark mode (Find my best settings: the game tours four places by itself and writes its results), Quit and Restart in the pause menu under Mods, Squadala! in the Mods menu, battle music above 60 fps, menu text, the controller in the menus with the game in the background, the whole GameBanana list, RX 580 and RX 5000/6000 shader fixes, the pipeline cache kept through an update, async present black flashes, and faster builds.
This commit is contained in:
407
launcher/Logic/Benchmark.cs
Normal file
407
launcher/Logic/Benchmark.cs
Normal file
@@ -0,0 +1,407 @@
|
||||
// "Find my best settings" (DESIGN 12): the game visits four places by itself, twice (the player's settings uncapped, then with
|
||||
// an upscaler), the frame rates are read from its log, and a small rule table says what to change.
|
||||
//
|
||||
// Safety, in this order:
|
||||
// * the saves: the game runs on a COPY of the game folder's user\ (--user <copy>), so whatever it writes goes there and the
|
||||
// player's own saves are never touched (no switch in the game needed: the host takes --user, as the lab scripts use it);
|
||||
// * the options file: triforce_options.ini (beside the game's exe, where the game reads it) is copied aside first and put
|
||||
// back afterwards whatever happens; a "restore.txt" marker in the work folder lets the next launcher start put it back if
|
||||
// this one was killed in the middle (RestoreIfLeft);
|
||||
// * the game: refused while the player's game runs; the benchmark's own game is closed at the end, and on Stop.
|
||||
// The game's switches it uses are its own test hooks: HOS_OOT_CHEATS=1 (the teleports, "!cheat 1000+n" through
|
||||
// HOS_INPUT_LIVE, host/hos_main.c oot_destinations), HOS_OOT_PROTECT_HEARTS=1, HOS_INPUT_LIVE (presses: title, Continue, Load).
|
||||
// The log lines read: "vi: N frames presented (X fps over the last 5.0 s, ...)", "vi: 1% low X fps over the last ..." (added
|
||||
// with this, host/nn_vi.c; a game built before it gives the slowest 5 s window instead), "presents, X fps; a frame: N draws".
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
public sealed record BenchmarkRequest(string GameFolder, bool TryUpscaler = true, TimeSpan? PerPlace = null);
|
||||
|
||||
/// <summary>Where it is: Phase "boot" | "next" | "place" | "done"; Fraction of the whole run.</summary>
|
||||
public sealed record BenchmarkProgress(string Phase, string Place, int Pass, int Passes, double? Fps, double Fraction, string Text);
|
||||
|
||||
/// <summary>One place's measurement: average fps and the 1 % low (LowIsWindow: the game had no 1 % line, so it is the slowest
|
||||
/// 5 s average).</summary>
|
||||
public sealed record PlaceResult(string Place, double AverageFps, double OnePercentLow, bool LowIsWindow = false)
|
||||
{
|
||||
public double Low01 { get; init; }
|
||||
public IReadOnlyList<double> FrameTimes { get; init; } = Array.Empty<double>();
|
||||
}
|
||||
|
||||
/// <summary>One benchmark run as the game wrote it.</summary>
|
||||
public sealed record BenchRun(IReadOnlyList<PlaceResult> Scenes, string? Gpu, bool Stopped, string? Error, TimeSpan Took);
|
||||
|
||||
/// <summary>A setting the benchmark would change: its triforce_options.ini key, the menu's row name, the value now and the
|
||||
/// recommended one (the App shows them with the menu's own labels).</summary>
|
||||
public sealed record SettingChange(string Key, string Label, int From, int To)
|
||||
{
|
||||
public bool Changes => From != To;
|
||||
}
|
||||
|
||||
public sealed record BenchmarkResult(IReadOnlyList<PlaceResult> Pass1, IReadOnlyList<PlaceResult>? Pass2, string? Pass2Name,
|
||||
IReadOnlyList<SettingChange> Recommended, string Summary, TimeSpan Took);
|
||||
|
||||
public interface IBenchmarkRunner
|
||||
{
|
||||
Task<BenchmarkResult> RunBenchmarkAsync(BenchmarkRequest request, IProgress<BenchmarkProgress>? progress, CancellationToken token);
|
||||
void Apply(string gameFolder, IReadOnlyList<SettingChange> changes);
|
||||
}
|
||||
|
||||
public sealed record BenchPlace(string Name, int Teleport);
|
||||
|
||||
public sealed class Benchmark : IBenchmarkRunner
|
||||
{
|
||||
readonly TriforceContext ctx;
|
||||
public Benchmark(TriforceContext ctx) { this.ctx = ctx; }
|
||||
|
||||
/// <summary>The tour (host/hos_main.c oot_destinations: 0 Kokiri Forest, 1 Hyrule Field, 3 Market, 7 Lake Hylia): open
|
||||
/// field, a crowd, foliage, water.</summary>
|
||||
public static readonly IReadOnlyList<BenchPlace> Places = new BenchPlace[]
|
||||
{
|
||||
new("Hyrule Field", 1001), new("Castle Town Market", 1003), new("Kokiri Forest", 1000), new("Lake Hylia", 1007),
|
||||
};
|
||||
|
||||
// the options file's keys (gpu/vk/vk_menu.cpp ini_key; values gpu/vk/vk_menu.h, upscaler_rows.h, fps_cap.h)
|
||||
public const string KCap = "frame_rate_cap", KVsync = "vsync", KSteady = "steady_frame_rate", KUpscaler = "dlss",
|
||||
KResolution = "resolution", KPreset = "quality_preset", KFrameGen = "frame_generation";
|
||||
// frame_rate_cap: 0 60, 1 90, 2 120, 3 144, 4 165, 5 240, 6 the monitor's. dlss (the Upscaler row): 0 the game's, 1 DLSS,
|
||||
// 3 FSR 3.1, 4 FSR 4. resolution: 3 = 67 % (Quality), 5 = 58 % (Balanced), 4 = 50 % (Performance). quality_preset 0 Custom.
|
||||
static readonly (int value, int fps)[] Caps = { (0, 60), (2, 120), (3, 144), (5, 240) };
|
||||
public const int UpGame = 0, UpDlss = 1, UpFsr3 = 3, ResQuality = 3, ResBalanced = 5, CapUncapped = 5;
|
||||
|
||||
public string WorkFolder => Path.Combine(ctx.WorkFolder, "benchmark");
|
||||
string Marker => Path.Combine(WorkFolder, "restore.txt");
|
||||
static string OptionsOf(string game) => Path.Combine(game, "triforce_options.ini");
|
||||
|
||||
/// <summary>Puts a player's options file back when a benchmark was cut off (the launcher killed in the middle). Call at start.</summary>
|
||||
public void RestoreIfLeft()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(Marker)) return;
|
||||
var lines = File.ReadAllLines(Marker);
|
||||
var target = lines.ElementAtOrDefault(0);
|
||||
var backup = lines.ElementAtOrDefault(1);
|
||||
if (target != null && ctx.AllowedForGame(target))
|
||||
{
|
||||
if (backup == "none") File.Delete(target);
|
||||
else if (backup != null && File.Exists(backup)) File.Copy(backup, target, true);
|
||||
ctx.Log.Write("benchmark: the options file put back after a cut-off run: " + target);
|
||||
}
|
||||
File.Delete(Marker);
|
||||
}
|
||||
catch (Exception e) { ctx.Log.Write("benchmark: putting the options back: " + e.Message); }
|
||||
}
|
||||
|
||||
/// <summary>What the second pass would use on this PC, or null (DLSS when the game was built with it on an NVIDIA card,
|
||||
/// else AMD FSR 3.1, which runs everywhere; none when the player already uses an upscaler).</summary>
|
||||
public (int upscaler, string name)? SecondPass(string game, IReadOnlyDictionary<string, int> now)
|
||||
{
|
||||
if (now.TryGetValue(KUpscaler, out var u) && u != UpGame) return null;
|
||||
if (Gpus.HasNvidia() && new Game(ctx).HasDlss(game)) return (UpDlss, "NVIDIA DLSS");
|
||||
return (UpFsr3, "AMD FSR 3.1");
|
||||
}
|
||||
|
||||
/// <summary>Does this game have benchmark mode (a build from v0.5.2 on: host/ answers HOS_BENCHMARK)? Its exe names the
|
||||
/// switch; read once per exe file (size + time).</summary>
|
||||
public static bool Supports(string exe)
|
||||
{
|
||||
try
|
||||
{
|
||||
var fi = new FileInfo(exe);
|
||||
var key = exe + "|" + fi.Length + "|" + fi.LastWriteTimeUtc.Ticks;
|
||||
lock (supportCache) if (supportCache.TryGetValue(key, out var known)) return known;
|
||||
var needle = Encoding.ASCII.GetBytes("HOS_BENCHMARK");
|
||||
var found = false;
|
||||
using (var f = File.OpenRead(exe))
|
||||
{
|
||||
var buf = new byte[1 << 22];
|
||||
var keep = needle.Length - 1;
|
||||
int got, have = 0;
|
||||
while (!found && (got = f.Read(buf, have, buf.Length - have)) > 0)
|
||||
{
|
||||
var n = have + got;
|
||||
found = buf.AsSpan(0, n).IndexOf(needle) >= 0;
|
||||
have = Math.Min(keep, n);
|
||||
Array.Copy(buf, n - have, buf, 0, have);
|
||||
}
|
||||
}
|
||||
lock (supportCache) supportCache[key] = found;
|
||||
return found;
|
||||
}
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
static readonly Dictionary<string, bool> supportCache = new();
|
||||
|
||||
/// <summary>Supports, or (tests) a test run told to take it as given (TRIFORCE_BENCH_ASSUME=1: the stand-in game).</summary>
|
||||
public bool Ready(string exe) => Supports(exe) || ctx.TestRoot != null && ctx.Env("TRIFORCE_BENCH_ASSUME") == "1";
|
||||
|
||||
/// <summary>One benchmark run: the game in its benchmark mode (it loads the newest save by itself, visits the scenes with
|
||||
/// its own panel on screen, writes its results and quits). Settings for the run: the player's, uncapped and without VSync,
|
||||
/// plus <paramref name="upscaler"/> at Quality when given. Stop: the token (the game is closed and writes "stopped").</summary>
|
||||
public async Task<BenchRun> RunOnceAsync(string game, (int upscaler, string name)? upscaler, IProgress<BenchmarkProgress>? progress, CancellationToken token)
|
||||
{
|
||||
var g = new Game(ctx);
|
||||
var exe = g.FindExe(game) ?? throw new BenchmarkException("There is no built game in " + game + ".");
|
||||
if (!Ready(exe)) throw new BenchmarkException("Your game was built before the benchmark existed: it comes with the next update.");
|
||||
if (g.IsRunning(game)) throw new BenchmarkException("Close the game first: the benchmark starts it by itself.");
|
||||
if (new Saves(ctx).Newest(game) == null) throw new BenchmarkException("Play until your first save, then run it: the benchmark starts from your newest save.");
|
||||
var ini = OptionsOf(game);
|
||||
if (!ctx.AllowedForGame(ini)) throw new BenchmarkException(ctx.TestOnly);
|
||||
Directory.CreateDirectory(WorkFolder);
|
||||
RestoreIfLeft();
|
||||
var userCopy = Path.Combine(WorkFolder, "user");
|
||||
if (Directory.Exists(userCopy)) Directory.Delete(userCopy, true);
|
||||
CopyUser(Path.Combine(game, "user"), userCopy);
|
||||
var backup = Path.Combine(WorkFolder, "options.backup.ini");
|
||||
var hadOptions = File.Exists(ini);
|
||||
if (hadOptions) File.Copy(ini, backup, true);
|
||||
File.WriteAllLines(Marker, new[] { ini, hadOptions ? backup : "none" });
|
||||
var results = Path.Combine(WorkFolder, "results.json");
|
||||
if (File.Exists(results)) File.Delete(results);
|
||||
var t0 = DateTime.UtcNow;
|
||||
try
|
||||
{
|
||||
var keys = new Dictionary<string, int> { [KCap] = CapUncapped, [KVsync] = 0, [KSteady] = 0, [KFrameGen] = 0 };
|
||||
if (upscaler is { } u) { keys[KUpscaler] = u.upscaler; keys[KResolution] = ResQuality; keys[KPreset] = 0; }
|
||||
BenchIni.Set(ini, keys);
|
||||
var si = new ProcessStartInfo(exe) { UseShellExecute = false, WorkingDirectory = game, RedirectStandardError = true, RedirectStandardOutput = true };
|
||||
foreach (var a in new[] { Path.Combine(game, "image.bin"), "--romfs", Path.Combine(game, "romfs"), "--user", userCopy }) si.ArgumentList.Add(a);
|
||||
si.Environment["HOS_BENCHMARK"] = results;
|
||||
si.Environment["HOS_OOT_CHEATS"] = "1";
|
||||
si.Environment["HOS_OOT_PROTECT_HEARTS"] = "1";
|
||||
si.Environment["HOS_INPUT_SCRIPT_BACKGROUND"] = "1";
|
||||
si.Environment["HOOKSHOT_NO_UPDATE_CHECK"] = "1";
|
||||
if (ctx.Env("TRIFORCE_BENCH_GAME_ENV") is { Length: > 0 } extra) // (tests: e.g. the stand-in game's speed)
|
||||
foreach (var kv in extra.Split(';')) if (kv.IndexOf('=') is var i and > 0) si.Environment[kv[..i]] = kv[(i + 1)..];
|
||||
var logPath = Path.Combine(WorkFolder, upscaler == null ? "run.log" : "run-upscaler.log");
|
||||
using var log = new StreamWriter(logPath, false, new UTF8Encoding(false)) { AutoFlush = true };
|
||||
var gate = new object();
|
||||
string? state = null;
|
||||
void Got(string? l)
|
||||
{
|
||||
if (l == null) return;
|
||||
lock (gate) log.WriteLine(l);
|
||||
// the game's own progress lines ("bench: ..."), for the launcher's line while it runs
|
||||
var at = l.IndexOf("bench: ", StringComparison.Ordinal);
|
||||
if (at >= 0) state = l[(at + 7)..].Trim();
|
||||
}
|
||||
var p = Process.Start(si) ?? throw new BenchmarkException("The game would not start.");
|
||||
GameJob.Tie(p);
|
||||
p.ErrorDataReceived += (_, e) => Got(e.Data);
|
||||
p.OutputDataReceived += (_, e) => Got(e.Data);
|
||||
p.BeginErrorReadLine(); p.BeginOutputReadLine();
|
||||
ctx.Log.Write("benchmark: started the game in benchmark mode (pid " + p.Id + ")" + (upscaler is { } up2 ? " with " + up2.name : ""));
|
||||
using (token.Register(() => { try { if (!p.HasExited && !(p.CloseMainWindow() && p.WaitForExit(15000))) p.Kill(true); } catch { } }))
|
||||
{
|
||||
while (!p.HasExited)
|
||||
{
|
||||
progress?.Report(new BenchmarkProgress("run", state ?? "", 1, 1, null, 0, state ?? "Starting the game"));
|
||||
try { await Task.Delay(500, token); } catch (OperationCanceledException) { break; }
|
||||
}
|
||||
try { await p.WaitForExitAsync(CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(20)); } catch { }
|
||||
}
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (!File.Exists(results)) throw new BenchmarkException("The game closed without results" + (p.HasExited ? " (exit code " + p.ExitCode + ")" : "") + ". Its log is in " + logPath + ".");
|
||||
var run = ReadResults(results, DateTime.UtcNow - t0);
|
||||
if (run.Stopped) throw new OperationCanceledException();
|
||||
if (run.Scenes.Count == 0) throw new BenchmarkException(run.Error ?? "The benchmark measured nothing.");
|
||||
return run;
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
if (hadOptions) File.Copy(backup, ini, true); else if (File.Exists(ini)) File.Delete(ini);
|
||||
File.Delete(Marker);
|
||||
}
|
||||
catch (Exception e) { ctx.Log.Write("benchmark: putting the options back: " + e.Message); }
|
||||
try { Directory.Delete(userCopy, true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The game's results file: {"version":1,"stopped":false,"gpu":..,"error":..,"scenes":[{name,avg,low1,low01,frames,seconds,frametimes_ms}]}.</summary>
|
||||
public static BenchRun ReadResults(string path, TimeSpan took)
|
||||
{
|
||||
using var doc = System.Text.Json.JsonDocument.Parse(File.ReadAllText(path));
|
||||
var r = doc.RootElement;
|
||||
var scenes = new List<PlaceResult>();
|
||||
if (r.TryGetProperty("scenes", out var arr))
|
||||
foreach (var s in arr.EnumerateArray())
|
||||
{
|
||||
double D(string k) => s.TryGetProperty(k, out var v) && v.TryGetDouble(out var d) ? d : 0;
|
||||
var ft = new List<double>();
|
||||
if (s.TryGetProperty("frametimes_ms", out var f)) foreach (var x in f.EnumerateArray()) if (x.TryGetDouble(out var d)) ft.Add(d);
|
||||
scenes.Add(new PlaceResult(s.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "", D("avg"), D("low1"), false) { Low01 = D("low01"), FrameTimes = ft });
|
||||
}
|
||||
return new BenchRun(scenes, r.TryGetProperty("gpu", out var gpu) ? gpu.GetString() : null,
|
||||
r.TryGetProperty("stopped", out var st) && st.ValueKind == System.Text.Json.JsonValueKind.True,
|
||||
r.TryGetProperty("error", out var er) ? er.GetString() : null, took);
|
||||
}
|
||||
|
||||
/// <summary>The old interface: one run, then the rules (the App runs the upscaler pass on its own, when asked).</summary>
|
||||
public async Task<BenchmarkResult> RunBenchmarkAsync(BenchmarkRequest request, IProgress<BenchmarkProgress>? progress, CancellationToken token)
|
||||
{
|
||||
var now = BenchIni.Read(OptionsOf(request.GameFolder));
|
||||
var run = await RunOnceAsync(request.GameFolder, null, progress, token);
|
||||
var recs = Recommend(now, run.Scenes, null, null, DisplayHz());
|
||||
return new BenchmarkResult(run.Scenes, null, null, recs, Summary(run.Scenes, null, null), run.Took);
|
||||
}
|
||||
|
||||
static void CopyUser(string from, string to)
|
||||
{
|
||||
Directory.CreateDirectory(to);
|
||||
if (!Directory.Exists(from)) return;
|
||||
foreach (var f in Directory.EnumerateFiles(from, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var rel = Path.GetRelativePath(from, f);
|
||||
if (rel.StartsWith("temp", StringComparison.OrdinalIgnoreCase) || Path.GetFileName(f).Equals("save.lock", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(to, rel))!);
|
||||
File.Copy(f, Path.Combine(to, rel), true);
|
||||
}
|
||||
}
|
||||
/// <summary>DESIGN 12's rules. <paramref name="now"/>: the player's options; second: pass 2's upscaler.</summary>
|
||||
public static List<SettingChange> Recommend(IReadOnlyDictionary<string, int> now, IReadOnlyList<PlaceResult> p1, IReadOnlyList<PlaceResult>? p2,
|
||||
(int upscaler, string name)? second, int displayHz)
|
||||
{
|
||||
int Now(string k, int d) => now.TryGetValue(k, out var v) ? v : d;
|
||||
var recs = new List<SettingChange>();
|
||||
var worst1 = p1.Min(r => r.OnePercentLow);
|
||||
var use2 = p2 != null && second != null && p2.Min(r => r.OnePercentLow) >= worst1 * 1.15;
|
||||
var chosen = use2 ? p2! : p1;
|
||||
var worstLow = chosen.Min(r => r.OnePercentLow);
|
||||
// the upscaler: the second pass's, when it raises the worst place's 1 % low by 15 % or more
|
||||
recs.Add(new SettingChange(KUpscaler, "Upscaler", Now(KUpscaler, UpGame), use2 ? second!.Value.upscaler : Now(KUpscaler, UpGame)));
|
||||
if (use2) recs.Add(new SettingChange(KResolution, "Render resolution", Now(KResolution, 1), worstLow < 60 ? ResBalanced : ResQuality));
|
||||
// the frame rate cap: the highest the worst place's low stays above, never above the display's refresh
|
||||
var cap = 0;
|
||||
foreach (var (value, fps) in Caps)
|
||||
if (worstLow >= fps && (displayHz <= 0 || fps <= displayHz + 1)) cap = value;
|
||||
recs.Add(new SettingChange(KCap, "Game frame rate cap", Now(KCap, 0), cap));
|
||||
// steady frame rate: on where the lows fall under 80 % of the average anywhere
|
||||
var uneven = chosen.Any(r => r.OnePercentLow < r.AverageFps * 0.8);
|
||||
recs.Add(new SettingChange(KSteady, "Steady frame rate", Now(KSteady, 0), uneven ? 1 : Now(KSteady, 0)));
|
||||
// frame generation: never turned on by this (DESIGN 12: only below 60 with DLSS-G / FSR 4 FG, not measured yet)
|
||||
recs.Add(new SettingChange(KFrameGen, "Frame generation", Now(KFrameGen, 0), Now(KFrameGen, 0)));
|
||||
if (recs.Any(r => r.Changes && (r.Key == KUpscaler || r.Key == KResolution)))
|
||||
recs.Add(new SettingChange(KPreset, "Quality preset", Now(KPreset, 0), 0));
|
||||
return recs;
|
||||
}
|
||||
|
||||
public static string Summary(IReadOnlyList<PlaceResult> p1, IReadOnlyList<PlaceResult>? p2, string? second)
|
||||
{
|
||||
var w1 = p1.Min(r => r.OnePercentLow);
|
||||
var s = w1 >= 60 ? $"Your PC holds <b>above 60 fps everywhere</b> at your settings (the slowest place's low: {w1:0})."
|
||||
: $"At your settings the slowest place dips to {w1:0} fps.";
|
||||
if (p2 != null && second != null)
|
||||
{
|
||||
var w2 = p2.Min(r => r.OnePercentLow);
|
||||
s += w2 >= w1 * 1.15 ? $" With {second} the slowest place holds {w2:0}, so it is worth turning on."
|
||||
: $" {second} changed little here ({w2:0}), so it stays as it is.";
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>The main display's refresh rate (Windows), 0 when not known.</summary>
|
||||
public static int DisplayHz()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return 0;
|
||||
try
|
||||
{
|
||||
var dm = new DEVMODE { dmSize = (short)System.Runtime.InteropServices.Marshal.SizeOf<DEVMODE>() };
|
||||
return EnumDisplaySettings(null, -1, ref dm) ? dm.dmDisplayFrequency : 0;
|
||||
}
|
||||
catch { return 0; }
|
||||
}
|
||||
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
|
||||
struct DEVMODE
|
||||
{
|
||||
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 32)] public string dmDeviceName;
|
||||
public short dmSpecVersion, dmDriverVersion, dmSize, dmDriverExtra; public int dmFields, dmPositionX, dmPositionY, dmDisplayOrientation, dmDisplayFixedOutput;
|
||||
public short dmColor, dmDuplex, dmYResolution, dmTTOption, dmCollate;
|
||||
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 32)] public string dmFormName;
|
||||
public short dmLogPixels; public int dmBitsPerPel, dmPelsWidth, dmPelsHeight, dmDisplayFlags, dmDisplayFrequency;
|
||||
}
|
||||
[System.Runtime.InteropServices.DllImport("user32", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
|
||||
static extern bool EnumDisplaySettings(string? device, int mode, ref DEVMODE dm);
|
||||
|
||||
/// <summary>Apply: the recommended rows into the game folder's options file (only those that change; every other line
|
||||
/// as it is). The caller refuses while the game runs.</summary>
|
||||
public void Apply(string gameFolder, IReadOnlyList<SettingChange> changes)
|
||||
{
|
||||
var ini = OptionsOf(gameFolder);
|
||||
if (!ctx.AllowedForGame(ini)) throw new BenchmarkException(ctx.TestOnly);
|
||||
BenchIni.Set(ini, changes.Where(c => c.Changes).ToDictionary(c => c.Key, c => c.To));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class BenchmarkException : Exception
|
||||
{
|
||||
public BenchmarkException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
/// <summary>triforce_options.ini as plain key=value lines: read, and keys set in place (a missing key added at the end), the
|
||||
/// file written whole beside and moved over it (as the game's own file_whole.h: a reader never meets half a file).</summary>
|
||||
public static class BenchIni
|
||||
{
|
||||
public static Dictionary<string, int> Read(string path)
|
||||
{
|
||||
var d = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
if (!File.Exists(path)) return d;
|
||||
foreach (var l in File.ReadAllLines(path))
|
||||
if (l.IndexOf('=') is var i and > 0 && int.TryParse(l[(i + 1)..].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var v)) d[l[..i].Trim()] = v;
|
||||
return d;
|
||||
}
|
||||
|
||||
public static void Set(string path, IReadOnlyDictionary<string, int> keys)
|
||||
{
|
||||
var lines = File.Exists(path) ? File.ReadAllLines(path).ToList() : new List<string>();
|
||||
var left = new Dictionary<string, int>(keys);
|
||||
for (var n = 0; n < lines.Count; n++)
|
||||
if (lines[n].IndexOf('=') is var i and > 0 && left.Remove(lines[n][..i].Trim(), out var v)) lines[n] = lines[n][..i].Trim() + "=" + v.ToString(CultureInfo.InvariantCulture);
|
||||
foreach (var (k, v) in left) lines.Add(k + "=" + v.ToString(CultureInfo.InvariantCulture));
|
||||
var fresh = path + ".new";
|
||||
File.WriteAllText(fresh, string.Join("\n", lines) + "\n");
|
||||
File.Move(fresh, path, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Windows: a job object that kills what it holds when its last handle closes, so a game the benchmark started never
|
||||
/// outlives the launcher (a crash, Task Manager). Elsewhere: nothing (the process group ends with Stop).</summary>
|
||||
static class GameJob
|
||||
{
|
||||
static IntPtr job;
|
||||
public static void Tie(Process p)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
try
|
||||
{
|
||||
if (job == IntPtr.Zero)
|
||||
{
|
||||
job = CreateJobObject(IntPtr.Zero, null);
|
||||
var info = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
|
||||
info.BasicLimitInformation.LimitFlags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
var size = System.Runtime.InteropServices.Marshal.SizeOf(info);
|
||||
var ptr = System.Runtime.InteropServices.Marshal.AllocHGlobal(size);
|
||||
System.Runtime.InteropServices.Marshal.StructureToPtr(info, ptr, false);
|
||||
SetInformationJobObject(job, 9 /* ExtendedLimitInformation */, ptr, (uint)size);
|
||||
System.Runtime.InteropServices.Marshal.FreeHGlobal(ptr);
|
||||
}
|
||||
AssignProcessToJobObject(job, p.Handle);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
|
||||
struct JOBOBJECT_BASIC_LIMIT_INFORMATION { public long PerProcessUserTimeLimit, PerJobUserTimeLimit; public uint LimitFlags; public UIntPtr MinimumWorkingSetSize, MaximumWorkingSetSize; public uint ActiveProcessLimit; public UIntPtr Affinity; public uint PriorityClass, SchedulingClass; }
|
||||
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
|
||||
struct IO_COUNTERS { public ulong a, b, c, d, e, f; }
|
||||
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
|
||||
struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION { public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation; public IO_COUNTERS IoInfo; public UIntPtr ProcessMemoryLimit, JobMemoryLimit, PeakProcessMemoryUsed, PeakJobMemoryUsed; }
|
||||
[System.Runtime.InteropServices.DllImport("kernel32", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] static extern IntPtr CreateJobObject(IntPtr a, string? name);
|
||||
[System.Runtime.InteropServices.DllImport("kernel32")] static extern bool SetInformationJobObject(IntPtr job, int cls, IntPtr info, uint size);
|
||||
[System.Runtime.InteropServices.DllImport("kernel32")] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
|
||||
}
|
||||
34
launcher/Logic/BuildInfo.cs
Normal file
34
launcher/Logic/BuildInfo.cs
Normal file
@@ -0,0 +1,34 @@
|
||||
// What this launcher is and where Triforce lives on the internet. Version comes from the TriforceVersion property
|
||||
// (Triforce.Logic.csproj): the release tag exactly, "v0.5.2", or "dev" for a local build.
|
||||
namespace Triforce.Logic;
|
||||
|
||||
public static partial class BuildInfo
|
||||
{
|
||||
/// <summary>A local build: never replaces itself from a release (old Setup.cs SetupNewer: Program.Version != "dev").</summary>
|
||||
public static bool IsDev => Version == "dev";
|
||||
|
||||
// (11-13: Triforce's own home. Releases are published in triforce/downloads on its Forgejo; the list is asked on the main
|
||||
// domain, which passes /api/v1 on, so the address outlives whatever answers behind it. Forgejo's list has GitHub's
|
||||
// names (tag_name, assets[].name / browser_download_url / size) and takes limit= where GitHub took per_page=.
|
||||
// Up to v0.3.5 this was api.github.com/repos/ruckus7382sfgsgdf/CBeta0.2: those builds ask there and nowhere else)
|
||||
public const string Home = "https://triforceproject.com";
|
||||
public const string ReleaseApi = Home + "/api/v1/repos/triforce/downloads/releases?limit=1";
|
||||
/// <summary>The Forgejo downloads repository (Linux: releases/download/<tag>/triforce-linux.txt).</summary>
|
||||
public const string Downloads = "https://git.triforceproject.com/triforce/downloads";
|
||||
|
||||
/// <summary>The app itself. Every install, shortcut, Apps-list entry and every built game's triforce_version.txt builder=
|
||||
/// line names this file: it must keep this name (research/02 2.8 point 7).</summary>
|
||||
public const string SetupAsset = "TriforceSetup.exe";
|
||||
public const string ToolsAsset = "Triforce-Tools.zip";
|
||||
// ((Triforce, 11-18) the tools in two parts (setup/pack_tools.ps1): the base, which does not change from one release to the
|
||||
// next (the compiler, Python, the libraries: 95 % of the zip), and the code, with the base's list (Tools.BaseList). An update
|
||||
// fetches the code and keeps the base it has: 12 MB instead of 284. Triforce-Tools.zip stays for older Setups and a first install)
|
||||
public const string ToolsCodeAsset = "Triforce-Tools-code.zip";
|
||||
public const string ToolsBaseAsset = "Triforce-Tools-base.zip";
|
||||
/// <summary>The Linux parts list (builder/linux/linux_update.py LIST_NAME).</summary>
|
||||
public const string LinuxListAsset = "triforce-linux.txt";
|
||||
public const string AppName = "Triforce";
|
||||
|
||||
/// <summary>The User-Agent every request to the release server carries (old Shell.cs Http).</summary>
|
||||
public static string UserAgent => "TriforceSetup/" + Version;
|
||||
}
|
||||
184
launcher/Logic/Game.cs
Normal file
184
launcher/Logic/Game.cs
Normal file
@@ -0,0 +1,184 @@
|
||||
// A built game folder: its program, its version, Play, and whether it runs (old Shell.cs GameExe/BuiltVersion/Play,
|
||||
// builder/linux/linux_update.py game_exe/game_version, hookshot_builder.py play/add_to_menu, hookshot-launch).
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>What the launcher knows of a game folder.</summary>
|
||||
public sealed record GameInfo(
|
||||
string Folder,
|
||||
/// <summary>The game's program, null when there is none (no game here, or the folder is gone).</summary>
|
||||
string? Exe,
|
||||
/// <summary>version= of triforce_version.txt (hookshot_version.txt in an older folder): the tools it was built with.</summary>
|
||||
string? Version,
|
||||
/// <summary>builder= of that file: the launcher the game starts again for its own update offer.</summary>
|
||||
string? Builder,
|
||||
/// <summary>The code line of language.txt.</summary>
|
||||
string? Language,
|
||||
/// <summary>It keeps the game files an update builds from (.triforce_exefs and romfs).</summary>
|
||||
bool Kept,
|
||||
/// <summary>It was built with NVIDIA DLSS (an update keeps it).</summary>
|
||||
bool Dlss,
|
||||
bool Exists);
|
||||
|
||||
public sealed class Game
|
||||
{
|
||||
readonly TriforceContext ctx;
|
||||
public Game(TriforceContext ctx) { this.ctx = ctx; }
|
||||
|
||||
/// <summary>The names of the game's program (Hookshot's after Triforce's, for a folder that still has those).</summary>
|
||||
public static readonly string[] WindowsExes = { "Triforce.exe", "hookshot.exe" };
|
||||
public static readonly string[] LinuxNames = { "triforce", "hookshot" };
|
||||
/// <summary>Process names that are this game (Windows: without .exe).</summary>
|
||||
public string[] ProcessNames => ctx.IsWindows ? new[] { "Triforce", "hookshot" } : LinuxNames;
|
||||
|
||||
/// <summary>The game's program in a folder. Windows: Triforce.exe, else hookshot.exe (make_game puts the game straight in the
|
||||
/// folder). Linux: only with image.bin there; bin/triforce under the folder's launcher script first, then triforce in a folder
|
||||
/// built without one (beside image.bin that name is the launcher itself) (linux_update.game_exe).</summary>
|
||||
public string? FindExe(string? folder)
|
||||
{
|
||||
if (string.IsNullOrEmpty(folder)) return null;
|
||||
if (ctx.IsWindows)
|
||||
{
|
||||
foreach (var n in WindowsExes)
|
||||
{
|
||||
var p = Path.Combine(folder, n);
|
||||
if (File.Exists(p)) return p;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (!File.Exists(Path.Combine(folder, "image.bin"))) return null;
|
||||
foreach (var n in LinuxNames)
|
||||
if (File.Exists(Path.Combine(folder, "bin", n))) return Path.Combine(folder, "bin", n);
|
||||
foreach (var n in LinuxNames)
|
||||
if (File.Exists(Path.Combine(folder, n))) return Path.Combine(folder, n);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>"name=value" from a small text file, null when it is not there.</summary>
|
||||
public static string? ReadValue(string file, string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var line in File.ReadAllLines(file))
|
||||
if (line.StartsWith(name + "=", StringComparison.Ordinal)) return line.Substring(name.Length + 1).Trim();
|
||||
}
|
||||
catch (Exception) { }
|
||||
return null;
|
||||
}
|
||||
|
||||
static string? VersionValue(string folder, string name) =>
|
||||
ReadValue(Path.Combine(folder, "triforce_version.txt"), name) ?? ReadValue(Path.Combine(folder, "hookshot_version.txt"), name);
|
||||
|
||||
/// <summary>The release a folder was built with (version= of triforce_version.txt, else hookshot_version.txt).</summary>
|
||||
public static string? BuiltVersion(string folder) => VersionValue(folder, "version");
|
||||
|
||||
/// <summary>The language a folder was built in: the code line of its language.txt (make_game.py folder_language).</summary>
|
||||
public static string? FolderLanguage(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var raw in File.ReadLines(Path.Combine(folder, "language.txt")))
|
||||
{
|
||||
var line = raw.Trim();
|
||||
if (line.Length > 0 && !line.StartsWith('#') && Languages.Find(line) != null) return line;
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Does the folder keep the game files an update builds from? (linux_update.game_version: .triforce_exefs or
|
||||
/// .hookshot_exefs, and romfs)</summary>
|
||||
public static bool KeptFiles(string folder) =>
|
||||
(Directory.Exists(Path.Combine(folder, ".triforce_exefs")) || Directory.Exists(Path.Combine(folder, ".hookshot_exefs"))) && Directory.Exists(Path.Combine(folder, "romfs"));
|
||||
|
||||
/// <summary>Was the folder built with NVIDIA DLSS? Windows: ngx\nvngx_dlss.dll. Linux: ngx/libnvidia-ngx-dlss.so* and NVIDIA's
|
||||
/// licence in the launcher's ngx-sdk (hookshot_builder.py folder_has_dlss).</summary>
|
||||
public bool HasDlss(string folder)
|
||||
{
|
||||
if (ctx.IsWindows) return File.Exists(Path.Combine(folder, "ngx", "nvngx_dlss.dll"));
|
||||
try
|
||||
{
|
||||
return Directory.EnumerateFiles(Path.Combine(folder, "ngx"), "libnvidia-ngx-dlss.so*").Any() && File.Exists(Path.Combine(ctx.NgxSdkFolder, "LICENSE.txt"));
|
||||
}
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
public GameInfo Describe(string folder) => new(folder, FindExe(folder), BuiltVersion(folder), VersionValue(folder, "builder"), FolderLanguage(folder),
|
||||
KeptFiles(folder), HasDlss(folder), Directory.Exists(folder));
|
||||
|
||||
/// <summary>The game folder the launcher built last (GameFolder), when it still holds a game.</summary>
|
||||
public string? Current => ctx.Settings.GameFolder is { } g && FindExe(g) != null ? g : null;
|
||||
|
||||
/// <summary>Does this folder's game run? A program of the game's names whose exe is inside the folder (another folder's game is
|
||||
/// another game). One whose exe cannot be read counts, except in a test run, where only programs inside the test folder do
|
||||
/// (old Shell.Mods.cs GameRuns).</summary>
|
||||
public bool IsRunning(string folder)
|
||||
{
|
||||
foreach (var p in ctx.Platform.FindProcesses(ProcessNames))
|
||||
{
|
||||
if (p.Exe == null) { if (ctx.TestRoot == null) return true; continue; }
|
||||
if (TriforceContext.Inside(folder, p.Exe) && (ctx.TestRoot == null || TriforceContext.Inside(ctx.TestRoot, p.Exe))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Is any Triforce game running (any folder)? The App mutes its sounds then (old Sound.cs).</summary>
|
||||
public bool AnyRunning() =>
|
||||
ctx.Platform.FindProcesses(ProcessNames).Any(p => ctx.TestRoot == null || p.Exe != null && TriforceContext.Inside(ctx.TestRoot, p.Exe));
|
||||
|
||||
/// <summary>The variables the game must not see (make_game.py GAME_ENV_DROP + LD_LIBRARY_PATH, hookshot-launch), and what the
|
||||
/// launcher's own .NET and WebKit add (research/12 6).</summary>
|
||||
static readonly string[] DropPrefixes = { "HOOKSHOT_", "PYTHON", "APPDIR", "APPIMAGE", "ARGV0", "OWD", "DOTNET_", "WEBKIT_", "COREHOST_" };
|
||||
static readonly string[] DropNames = { "LD_LIBRARY_PATH", "GDK_BACKEND" };
|
||||
|
||||
/// <summary>Starts the game in its folder (old Shell.cs Play; Linux hookshot_builder.py play / hookshot-launch), with
|
||||
/// HOOKSHOT_NO_UPDATE_CHECK=1: the launcher just asked about updates, and the game's own offer would ask again. Linux: the
|
||||
/// AppImage's variables dropped, a session of its own, its output nowhere. Refused in a test run outside the test folder.</summary>
|
||||
public Process? Play(string folder)
|
||||
{
|
||||
var exe = FindExe(folder);
|
||||
if (exe == null) return null;
|
||||
if (!ctx.AllowedForGame(exe)) { ctx.Log.Write("not started (a test run starts only what is in its own folder): " + exe); return null; }
|
||||
var si = new ProcessStartInfo(exe) { UseShellExecute = false, WorkingDirectory = folder };
|
||||
if (!ctx.IsWindows)
|
||||
{
|
||||
foreach (var key in si.Environment.Keys.ToList())
|
||||
if (DropPrefixes.Any(p => key.StartsWith(p, StringComparison.Ordinal)) || DropNames.Contains(key)) si.Environment.Remove(key);
|
||||
si.RedirectStandardOutput = si.RedirectStandardError = true;
|
||||
si.RedirectStandardInput = true;
|
||||
}
|
||||
si.Environment["HOOKSHOT_NO_UPDATE_CHECK"] = "1";
|
||||
var p = ctx.IsWindows ? Process.Start(si) : ctx.Platform.StartTree(si);
|
||||
if (p != null && !ctx.IsWindows)
|
||||
{
|
||||
// (stdio to nowhere: read and dropped, so a full pipe never blocks the game)
|
||||
p.OutputDataReceived += (_, _) => { };
|
||||
p.ErrorDataReceived += (_, _) => { };
|
||||
p.BeginOutputReadLine();
|
||||
p.BeginErrorReadLine();
|
||||
try { p.StandardInput.Close(); } catch (Exception) { }
|
||||
}
|
||||
ctx.Log.Write("started the game: " + exe);
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>The window class the game names itself with on Linux (host/posix/display_sdl.c HOS_APP_ID).</summary>
|
||||
public const string LinuxAppId = "io.github.NotRexed.Hookshot";
|
||||
|
||||
/// <summary>Linux: an applications-menu entry that starts the game folder's launcher script (hookshot_builder.py add_to_menu),
|
||||
/// written after every good build. Its icon: the crest copied into the folder as hookshot.png.</summary>
|
||||
public void AddToMenu(string folder, string? iconSource)
|
||||
{
|
||||
if (ctx.IsWindows) return;
|
||||
if (folder.IndexOfAny(new[] { '\r', '\n', '\0' }) >= 0) throw new ArgumentException("the game folder's name has a line break");
|
||||
var icon = Path.Combine(folder, "hookshot.png");
|
||||
if (iconSource != null && File.Exists(iconSource)) File.Copy(iconSource, icon, true);
|
||||
var apps = Path.Combine(((LinuxPlatform)ctx.Platform).DataHome, "applications");
|
||||
ctx.Require(apps);
|
||||
Directory.CreateDirectory(apps);
|
||||
File.WriteAllText(Path.Combine(apps, "triforce.desktop"),
|
||||
LinuxPlatform.DesktopEntry("Triforce", "The Legend of Zelda: Ocarina of Time, built from your copy", Path.Combine(folder, "triforce"), "", folder, icon, LinuxAppId));
|
||||
}
|
||||
}
|
||||
224
launcher/Logic/GameIntake.cs
Normal file
224
launcher/Logic/GameIntake.cs
Normal file
@@ -0,0 +1,224 @@
|
||||
// The player's own game files, as the build takes them (old Shell.cs:885-958, research/02 section 4, research/12 section 3):
|
||||
// a .nup file, or romfs + exefs folders. One path from a drop or a picker is turned into a source; quick checks run without
|
||||
// the tools (the file is there, a .nup's header reads, the folders are there, exefs\main is the supported build, no NX2navi
|
||||
// packed romfs); the full check is make_game.py --check (the tools read the .nup's exefs).
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
public enum SourceKind { Nup, Folders }
|
||||
|
||||
/// <summary>The game files a build reads. For Folders, Romfs and Exefs (either may be missing: Missing names it).</summary>
|
||||
public sealed record GameSource(SourceKind Kind, string? Nup, string? Romfs, string? Exefs)
|
||||
{
|
||||
/// <summary>The source is there whole (old SourceGiven: a .nup that exists; a romfs folder and exefs\main).</summary>
|
||||
public bool Complete => Kind == SourceKind.Nup ? File.Exists(Nup) : Directory.Exists(Romfs) && Exefs != null && File.Exists(Path.Combine(Exefs, "main"));
|
||||
/// <summary>What is still to be chosen: "romfs", "exefs", or null.</summary>
|
||||
public string? Missing => Kind == SourceKind.Nup ? null : !Directory.Exists(Romfs) ? "romfs" : Exefs == null || !Directory.Exists(Exefs) ? "exefs" : null;
|
||||
/// <summary>The name the file card shows.</summary>
|
||||
public string DisplayName => Kind == SourceKind.Nup ? Path.GetFileName(Nup!) : Path.GetFileName(Path.GetDirectoryName((Romfs ?? Exefs ?? "").TrimEnd('\\', '/')) ?? "") is { Length: > 0 } n ? n : Romfs ?? Exefs ?? "";
|
||||
/// <summary>make_game.py's arguments for it (--nup f, or --romfs d --exefs d).</summary>
|
||||
public IReadOnlyList<string> Args => Kind == SourceKind.Nup ? new[] { "--nup", Nup! } : new[] { "--romfs", Romfs ?? "", "--exefs", Exefs ?? "" };
|
||||
}
|
||||
|
||||
/// <summary>One title in a .nup package (its header's table): the base game or an update.</summary>
|
||||
public sealed record NupTitle(string Id, uint Version);
|
||||
|
||||
/// <summary>A quick answer, without the tools.</summary>
|
||||
public sealed record QuickCheck(bool Ok, string Text, IReadOnlyList<NupTitle>? Titles = null, string? BuildId = null)
|
||||
{
|
||||
/// <summary>The answer is final (a problem, or a folder whose build id was read): the tools' check adds nothing for folders.</summary>
|
||||
public bool Final => !Ok || BuildId != null;
|
||||
}
|
||||
|
||||
/// <summary>make_game.py --check's answer.</summary>
|
||||
public sealed record CheckResult(bool Ok, string Text, string? BuildId, bool ToolsMissing = false);
|
||||
|
||||
/// <summary>Room for a build on a disk (DESIGN 6: "Takes 60 GB while building, 24 GB after. 212 GB free on D:").</summary>
|
||||
public sealed record SpaceInfo(string Disk, long? Free, long NeedWhileBuilding, long NeedAfter)
|
||||
{
|
||||
/// <summary>Not enough: the line turns ruby and the Build button is off (the old Setup only asked; DESIGN 6 turns it off).</summary>
|
||||
public bool TooLittle => Free is { } f && f < NeedWhileBuilding;
|
||||
public string Text => "Takes " + (NeedWhileBuilding >> 30) + " GB while building, about " + (NeedAfter >> 30) + " GB after." +
|
||||
(Free is { } f ? " " + (f >> 30) + " GB free on " + Disk.TrimEnd('\\', '/') + "." : "");
|
||||
}
|
||||
|
||||
public sealed class GameIntake
|
||||
{
|
||||
readonly TriforceContext ctx;
|
||||
public GameIntake(TriforceContext ctx) { this.ctx = ctx; }
|
||||
|
||||
/// <summary>The build id the patches, the hot list and the profile were made from: the supported game version is identified
|
||||
/// only by this (make_game.py BUILD_ID; there is no literal "1.0.0" anywhere).</summary>
|
||||
public const string SupportedBuildId = "e0f3ccfa";
|
||||
/// <summary>What a build takes while it runs (old Shell.cs NeededBytes).</summary>
|
||||
public const long NeededWhileBuilding = 60L << 30;
|
||||
/// <summary>About what a built game folder keeps (DESIGN 6). An estimate, said with "about".</summary>
|
||||
public const long NeededAfter = 24L << 30;
|
||||
|
||||
/// <summary>make_game.py PACKED_ROMFS: NX2navi's romfs folder holds one packed romfs.bin, which the builder cannot read.</summary>
|
||||
public const string PackedRomfs = "This romfs folder is NX2navi's: it holds the game's data packed in one file (romfs.bin), which Triforce cannot " +
|
||||
"read, so the game would crash at start. Choose your game file (.nup) instead, or romfs and exefs folders with " +
|
||||
"the game's files unpacked in them.";
|
||||
|
||||
/// <summary>One dropped or picked path as a source (old Shell.cs Dropped): a *.nup; a folder named romfs or exefs (the other one
|
||||
/// beside it is taken along when it is there); a folder holding romfs and exefs; a built game folder keeps its exefs as
|
||||
/// .triforce_exefs beside romfs. merge: a source the player gave before, whose other half this path may be. Null when the
|
||||
/// path is none of these.</summary>
|
||||
public static GameSource? Normalize(string path, GameSource? merge = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path)) return null;
|
||||
path = path.Trim().Trim('"');
|
||||
try { path = Path.GetFullPath(path).TrimEnd('\\', '/'); } catch (Exception) { return null; }
|
||||
var name = Path.GetFileName(path).ToLowerInvariant();
|
||||
if (name.EndsWith(".nup", StringComparison.Ordinal) && !Directory.Exists(path)) return new GameSource(SourceKind.Nup, path, null, null);
|
||||
if (!Directory.Exists(path)) return null;
|
||||
var parent = Path.GetDirectoryName(path);
|
||||
var keep = merge is { Kind: SourceKind.Folders } ? merge : null;
|
||||
if (name == "romfs")
|
||||
return new GameSource(SourceKind.Folders, null, path, ExefsBeside(parent) ?? keep?.Exefs);
|
||||
if (name == "exefs" || name == ".triforce_exefs" || name == ".hookshot_exefs")
|
||||
return new GameSource(SourceKind.Folders, null, parent != null && Directory.Exists(Path.Combine(parent, "romfs")) ? Path.Combine(parent, "romfs") : keep?.Romfs, path);
|
||||
if (Directory.Exists(Path.Combine(path, "romfs")) && ExefsBeside(path) is { } exefs)
|
||||
return new GameSource(SourceKind.Folders, null, Path.Combine(path, "romfs"), exefs);
|
||||
// (a folder with one .nup in it: that file)
|
||||
try
|
||||
{
|
||||
var nups = Directory.GetFiles(path, "*.nup");
|
||||
if (nups.Length == 1) return new GameSource(SourceKind.Nup, nups[0], null, null);
|
||||
}
|
||||
catch (Exception) { }
|
||||
return null;
|
||||
}
|
||||
|
||||
static string? ExefsBeside(string? folder)
|
||||
{
|
||||
if (folder == null) return null;
|
||||
foreach (var n in new[] { "exefs", ".triforce_exefs", ".hookshot_exefs" })
|
||||
if (Directory.Exists(Path.Combine(folder, n))) return Path.Combine(folder, n);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The checks that need no tools. A .nup: there, and its header reads ("NUP\x01", a table of titles). Folders: there,
|
||||
/// exefs\main an NSO whose build id is read (0x40..0x60 of its header) and compared, and no packed romfs.bin.</summary>
|
||||
public static QuickCheck Quick(GameSource s)
|
||||
{
|
||||
if (s.Kind == SourceKind.Nup)
|
||||
{
|
||||
if (!File.Exists(s.Nup)) return new QuickCheck(false, "The file is not there: " + s.Nup);
|
||||
try
|
||||
{
|
||||
var titles = ReadNupTitles(s.Nup!);
|
||||
if (titles.Count == 0) return new QuickCheck(false, "This .nup file holds no game.");
|
||||
if (!titles.Any(t => t.Id.Equals("0400486024dec000", StringComparison.OrdinalIgnoreCase)))
|
||||
return new QuickCheck(false, "This .nup file holds another game (" + string.Join(", ", titles.Select(t => t.Id.ToUpperInvariant())) + "), not Ocarina of Time (0400486024DEC000).", titles);
|
||||
return new QuickCheck(true, "The game file reads.", titles);
|
||||
}
|
||||
catch (Exception e) { return new QuickCheck(false, "This is not a .nup game file Triforce can read (" + e.Message + ")."); }
|
||||
}
|
||||
if (s.Missing == "romfs") return new QuickCheck(false, "Choose the romfs folder too.");
|
||||
if (s.Romfs != null && File.Exists(Path.Combine(s.Romfs, "romfs.bin"))) return new QuickCheck(false, PackedRomfs);
|
||||
if (s.Missing == "exefs") return new QuickCheck(false, "Choose the exefs folder too.");
|
||||
var main = Path.Combine(s.Exefs!, "main");
|
||||
if (!File.Exists(main)) return new QuickCheck(false, "The exefs folder has no main file: it is not the game's exefs.");
|
||||
var bid = BuildIdOf(main);
|
||||
if (bid == null) return new QuickCheck(false, main + " is not a game executable");
|
||||
return bid.StartsWith(SupportedBuildId, StringComparison.Ordinal)
|
||||
? new QuickCheck(true, "This is the version Triforce supports (build " + bid.Substring(0, 8) + ").", null, bid)
|
||||
: new QuickCheck(false, "This is build " + bid.Substring(0, 8) + ". Triforce supports build " + SupportedBuildId + ".", null, bid);
|
||||
}
|
||||
|
||||
/// <summary>The module id of an NSO, plain or compressed (the header is the same): bytes 0x40..0x60 as hex; null when it is no
|
||||
/// NSO (make_game.py build_id).</summary>
|
||||
public static string? BuildIdOf(string main)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var f = new FileStream(main, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
var head = new byte[0x60];
|
||||
if (f.ReadAtLeast(head, head.Length, false) < head.Length) return null;
|
||||
if (head[0] != 'N' || head[1] != 'S' || head[2] != 'O' || head[3] != '0') return null;
|
||||
return Convert.ToHexStringLower(head, 0x40, 0x20);
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
/// <summary>The titles in a .nup's header, newest version first. Opened read-only, sharing reads: a .nup is never written.
|
||||
/// Layout (nx2/nup.py): a 0x80-byte header ("NUP\x01", u64 file size at +0x40), then at 0x80 the TOC ("TOC\x01", u32 titles at
|
||||
/// +4), the titles 0x40 each from 0xb0: u64 title id, u32 root, u32 exefs, u32 romfs, u32 version. A package shorter than its
|
||||
/// header says is a download or copy that did not finish (nup.py says so too, but 30 minutes into a build it once did).</summary>
|
||||
public static IReadOnlyList<NupTitle> ReadNupTitles(string nup)
|
||||
{
|
||||
using var f = new FileStream(nup, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||||
var head = new byte[0x80];
|
||||
if (f.ReadAtLeast(head, head.Length, false) < head.Length) throw new InvalidDataException("the file is too short");
|
||||
if (head[0] != 'N' || head[1] != 'U' || head[2] != 'P' || head[3] != 1) throw new InvalidDataException("not a NUP package");
|
||||
var size = BitConverter.ToInt64(head, 0x40);
|
||||
if (size > 0 && f.Length < size)
|
||||
throw new InvalidDataException("the .nup file is incomplete: it is " + (f.Length >> 20) + " MB, its header says " + (size >> 20) +
|
||||
" MB. Download or copy it again (wait for the download to finish) and check that the drive had room");
|
||||
var t = new byte[0x30];
|
||||
if (f.ReadAtLeast(t, t.Length, false) < t.Length || t[0] != 'T' || t[1] != 'O' || t[2] != 'C' || t[3] != 1) throw new InvalidDataException("no table of contents");
|
||||
var count = BitConverter.ToUInt32(t, 4);
|
||||
if (count == 0 || count > 64) throw new InvalidDataException("an odd number of titles (" + count + ")");
|
||||
var titles = new List<NupTitle>();
|
||||
var rec = new byte[0x40];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
if (f.ReadAtLeast(rec, rec.Length, false) < rec.Length) throw new InvalidDataException("the title table is cut off");
|
||||
titles.Add(new NupTitle(BitConverter.ToUInt64(rec, 0).ToString("x16"), BitConverter.ToUInt32(rec, 0x14)));
|
||||
}
|
||||
return titles.OrderByDescending(x => x.Version).ToList();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>The full check (old Runner.Check; make_game.py check): --check --nup f, or --check --exefs d --romfs d (the romfs too:
|
||||
/// NX2navi's packed romfs.bin is refused now, not after a 45-minute build). Without tools: ToolsMissing.</summary>
|
||||
public async Task<CheckResult> CheckAsync(GameSource s, CancellationToken token = default)
|
||||
{
|
||||
var tools = new Tools(ctx).Find();
|
||||
if (tools == null) return new CheckResult(false, "The Triforce tools are not here yet: they come with the first update check.", null, ToolsMissing: true);
|
||||
var args = new List<string> { "--check" };
|
||||
args.AddRange(s.Kind == SourceKind.Nup ? new[] { "--nup", s.Nup! } : new[] { "--exefs", s.Exefs ?? "", "--romfs", s.Romfs ?? "" });
|
||||
var result = new CheckResult(false, "The game files could not be read.", null);
|
||||
Process p;
|
||||
try { p = Process.Start(BuildRunner.StartInfo(ctx, tools, args, null, dlss: false))!; }
|
||||
catch (Exception)
|
||||
{
|
||||
if (ctx.IsWindows && Directory.Exists(Path.Combine(tools.Root, "python")) && !File.Exists(Path.Combine(tools.Root, "python", "python.exe")))
|
||||
return new CheckResult(false, "Triforce's own Python (tools\\python\\python.exe) is missing. Your antivirus probably removed it: restore it from " +
|
||||
"quarantine, or start Triforce again to download the tools once more.", null);
|
||||
return new CheckResult(false, "Python was not found. Start Triforce again to download the Triforce tools.", null);
|
||||
}
|
||||
using (p)
|
||||
using (token.Register(() => { try { ctx.Platform.KillTree(p); } catch (Exception) { } }))
|
||||
{
|
||||
p.ErrorDataReceived += (_, _) => { };
|
||||
p.BeginErrorReadLine();
|
||||
for (string? line; (line = await p.StandardOutput.ReadLineAsync(token).ConfigureAwait(false)) != null;)
|
||||
if (BuildProtocol.Parse(line) is { } e)
|
||||
result = e switch
|
||||
{
|
||||
BuildEvent.Check c => new CheckResult(c.Ok, c.Text, ParseBuildId(c.Text)),
|
||||
BuildEvent.Error x => new CheckResult(false, x.Text, null),
|
||||
_ => result,
|
||||
};
|
||||
await p.WaitForExitAsync(token).ConfigureAwait(false);
|
||||
}
|
||||
ctx.Log.Write("check " + string.Join(" ", args) + ": " + (result.Ok ? "OK " : "BAD ") + result.Text);
|
||||
return result;
|
||||
}
|
||||
|
||||
static string? ParseBuildId(string text)
|
||||
{
|
||||
var m = System.Text.RegularExpressions.Regex.Match(text, @"build ([0-9a-f]{8})");
|
||||
return m.Success ? m.Groups[1].Value : null;
|
||||
}
|
||||
|
||||
/// <summary>The words the add screen shows for a bad check (old: the localized VersionBad when the text starts "This is build").</summary>
|
||||
public static bool IsWrongVersion(string text) => text.StartsWith("This is build", StringComparison.Ordinal);
|
||||
|
||||
/// <summary>Room where the game is built.</summary>
|
||||
public SpaceInfo Space(string outFolder) => new(ctx.Platform.Disk(outFolder), ctx.FreeBytes(outFolder), NeededWhileBuilding, NeededAfter);
|
||||
}
|
||||
90
launcher/Logic/GameOptions/GameOptionRow.cs
Normal file
90
launcher/Logic/GameOptions/GameOptionRow.cs
Normal file
@@ -0,0 +1,90 @@
|
||||
// The game's in-game Options (gpu/vk/vk_menu.cpp, the Row table) as plain data for the launcher: one GameOptionRow per row the
|
||||
// game keeps in triforce_options.ini, with its tab, section, name, key, range, default, help and the labels its value shows.
|
||||
// GameOptionsSchema.All lists them; GameOptionsFile reads and writes the file the way the game does.
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>The Options screen's tabs, as the game's header shows them. (The game's Debug tab is not ported: its rows'
|
||||
/// keys are kept in the file as they are, GameOptionsSchema.KeptKeys.)</summary>
|
||||
public enum GameOptionTab { Display, Graphics, Audio, Controls, System }
|
||||
|
||||
/// <summary>Choice: a few values, each with a label (toggles and lists). Slider: a numeric range on steps (volume, nits,
|
||||
/// percent, sensitivity), each value labelled by its unit (Label).</summary>
|
||||
public enum GameOptionKind { Choice, Slider }
|
||||
|
||||
/// <summary>One value of a row and the text the game's menu shows for it.</summary>
|
||||
public sealed record GameOptionChoice(int Value, string Label);
|
||||
|
||||
/// <summary>The values of the other rows, for the labels that depend on them (the Render resolution's sizes follow the
|
||||
/// Upscaler, the Output resolution and the Handheld profile; the Anti-aliasing row shows the upscaler's own while one
|
||||
/// draws; the Microphone shows the saved device's name). GameOptionsFile is one.</summary>
|
||||
public interface IGameOptionValues
|
||||
{
|
||||
/// <summary>A row's value as the game reads it (its default when the file has no line).</summary>
|
||||
int Get(string key);
|
||||
/// <summary>A line's value as the file has it, null when it has no such line.</summary>
|
||||
string? Raw(string key);
|
||||
}
|
||||
|
||||
/// <summary>A row of the game's Options menu that has a value in triforce_options.ini.</summary>
|
||||
public sealed record GameOptionRow
|
||||
{
|
||||
/// <summary>The tab it is on. The Motion page's rows and the Controls page's Button prompts are on Controls, in
|
||||
/// the sections "Motion" and "Controls" (the rows that open those pages).</summary>
|
||||
public required GameOptionTab Tab { get; init; }
|
||||
/// <summary>The heading above it on its tab (the menu's section rows), null where the tab has none (Audio).</summary>
|
||||
public required string? Section { get; init; }
|
||||
/// <summary>The row's name, exactly as the menu shows it.</summary>
|
||||
public required string Name { get; init; }
|
||||
/// <summary>Its key in triforce_options.ini (vk_menu.cpp ini_key).</summary>
|
||||
public required string Key { get; init; }
|
||||
public required int Lo { get; init; }
|
||||
public required int Hi { get; init; }
|
||||
public required int Step { get; init; }
|
||||
/// <summary>The game's default (vk_menu.h Options): the value when the file has no line for it.</summary>
|
||||
public required int Default { get; init; }
|
||||
public required GameOptionKind Kind { get; init; }
|
||||
/// <summary>The help under the list while the row is selected, exactly the menu's.</summary>
|
||||
public required string Help { get; init; }
|
||||
/// <summary>Read once at the game's start: a change applies after a restart (the menu tags it "After restart").</summary>
|
||||
public required bool Restart { get; init; }
|
||||
/// <summary>A change here leaves the Quality preset alone; any other row changed by hand turns it back to Custom.</summary>
|
||||
public required bool PresetExempt { get; init; }
|
||||
|
||||
internal Func<int, IGameOptionValues?, string> Format { get; init; } = (v, _) => v.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
internal Func<IReadOnlyList<GameOptionChoice>>? ChoiceList { get; init; }
|
||||
|
||||
/// <summary>The values a Choice row offers, in the menu's order, with their labels as the menu shows them where nothing
|
||||
/// is known of this PC (fps cap 6 "Monitor's rate", GPU device from GameOptionsSchema.GpuNames). Empty for a Slider.
|
||||
/// GameOptionsFile.ChoicesOf has the ones that follow the file's other rows (the Render resolution).</summary>
|
||||
public IReadOnlyList<GameOptionChoice> Choices => ChoiceList?.Invoke() ?? Array.Empty<GameOptionChoice>();
|
||||
|
||||
/// <summary>The label of a value, as the menu shows it with the other rows at their defaults.</summary>
|
||||
public string Label(int value) => Format(value, null);
|
||||
|
||||
/// <summary>The label of a value with the other rows as values has them.</summary>
|
||||
public string Label(int value, IGameOptionValues? values) => Format(value, values);
|
||||
|
||||
/// <summary>A value as the launcher may set it: inside Lo..Hi, on the row's steps from Lo (the nearest, the larger on a
|
||||
/// tie). The Output resolution's values past its list are its first, as the game reads them.</summary>
|
||||
public int Clamp(int value)
|
||||
{
|
||||
if (Key == GameOptionsSchema.OutputResKey) return value >= Lo && value <= Hi ? value : 0;
|
||||
var v = Math.Clamp(value, Lo, Hi);
|
||||
if (Step > 1)
|
||||
{
|
||||
var k = (v - Lo + Step / 2) / Step;
|
||||
v = Math.Min(Lo + k * Step, Hi);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
/// <summary>A value as the game reads it from the file (menu_init): inside Lo..Hi, not moved onto the steps (a hand-edited
|
||||
/// 125 stays 125), except the Rumble strength (the nearest 25) and the Output resolution (past its list: its first).</summary>
|
||||
public int AsRead(int value)
|
||||
{
|
||||
if (Key == GameOptionsSchema.OutputResKey) return value >= Lo && value <= Hi ? value : 0;
|
||||
var v = Math.Clamp(value, Lo, Hi);
|
||||
if (Key == GameOptionsSchema.RumbleKey) v = (Math.Clamp(v, 0, 300) + 12) / 25 * 25;
|
||||
return v;
|
||||
}
|
||||
}
|
||||
340
launcher/Logic/GameOptions/GameOptionsFile.cs
Normal file
340
launcher/Logic/GameOptions/GameOptionsFile.cs
Normal file
@@ -0,0 +1,340 @@
|
||||
// triforce_options.ini in a game folder, read and written as the game does it (gpu/vk/vk_menu.cpp menu_init and save,
|
||||
// ini_merge.h, file_whole.h): plain key=value lines; a row's value is the last line with its key, as an int the way atoi
|
||||
// reads it, kept in its range; a row with no line has its default. Every line that is not a row of GameOptionsSchema is kept
|
||||
// as it is, in its place.
|
||||
//
|
||||
// The game writes the whole file at every change in its menu, and reads it once at its start. So the launcher must not write
|
||||
// it while the game runs: the game's next save would merge (it keeps a line changed outside unless it changed that row
|
||||
// itself), but the running game would not take the launcher's values until its next start, and its menu would show its own.
|
||||
// Refusing to write while Game.IsRunning(folder) is the caller's job: this class does not look at processes.
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
public sealed class GameOptionsFile : IGameOptionValues
|
||||
{
|
||||
/// <summary>The file's path: the game folder's triforce_options.ini.</summary>
|
||||
public string Path { get; }
|
||||
readonly (int W, int H)? mainScreen;
|
||||
List<string> lines = new(); // (the file as last read or written, each line without its line end)
|
||||
Dictionary<string, string> raw = new(StringComparer.Ordinal); // (each key's last value, trimmed as ini_merge.h does)
|
||||
Dictionary<string, int> read = new(StringComparer.Ordinal); // (each row's value as the game reads this file)
|
||||
readonly Dictionary<string, int> set = new(StringComparer.Ordinal); // (the rows the launcher changed: their new values)
|
||||
|
||||
GameOptionsFile(string path, (int W, int H)? mainScreen)
|
||||
{
|
||||
Path = path;
|
||||
this.mainScreen = mainScreen;
|
||||
Reload();
|
||||
}
|
||||
|
||||
/// <summary>The game folder's options. mainScreen: the main monitor's size in pixels, for a file from before
|
||||
/// options_version 6 whose Ultrawide is 1 (then "Monitor's shape": the game reads it as the shape nearest the main
|
||||
/// monitor's); without it such a 1 is read as 16:9, as the game does where it cannot ask. A missing file is all defaults.</summary>
|
||||
public static GameOptionsFile Load(string gameFolder, (int W, int H)? mainScreen = null) =>
|
||||
new(System.IO.Path.Combine(gameFolder, GameOptionsSchema.FileName), mainScreen);
|
||||
|
||||
/// <summary>The file was there when it was last read.</summary>
|
||||
public bool Exists { get; private set; }
|
||||
/// <summary>Its options_version (0: none, a file from before the line, or no file).</summary>
|
||||
public int Version { get; private set; }
|
||||
|
||||
/// <summary>Reads the file again: the launcher's changes not yet saved are dropped.</summary>
|
||||
public void Reload()
|
||||
{
|
||||
Exists = File.Exists(Path);
|
||||
var text = Exists ? File.ReadAllText(Path, Encoding.Latin1) : "";
|
||||
Parse(text);
|
||||
set.Clear();
|
||||
}
|
||||
|
||||
void Parse(string text)
|
||||
{
|
||||
lines = SplitLines(text);
|
||||
raw = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var l in lines)
|
||||
if (KeyOf(l) is { } k) raw[k] = Trim(l[(k.Length + 1)..]);
|
||||
Version = raw.TryGetValue(GameOptionsSchema.VersionKey, out var ver) ? Atoi(ver) : 0;
|
||||
read = Effective(raw, Exists);
|
||||
}
|
||||
|
||||
// ---- reading as the game does ----
|
||||
|
||||
/// <summary>The key of a key=value line (all before the first '='; none for a line without one or starting with it).</summary>
|
||||
static string? KeyOf(string line)
|
||||
{
|
||||
var eq = line.IndexOf('=');
|
||||
return eq > 0 ? line[..eq] : null;
|
||||
}
|
||||
static string Trim(string v) => v.Trim(' ', '\t', '\r', '\n');
|
||||
/// <summary>C's atoi: spaces, a sign, digits, the rest ignored; 0 without digits (and the int's end past it).</summary>
|
||||
internal static int Atoi(string s)
|
||||
{
|
||||
int i = 0;
|
||||
while (i < s.Length && (s[i] == ' ' || s[i] is >= '\t' and <= '\r')) i++;
|
||||
var neg = false;
|
||||
if (i < s.Length && (s[i] == '+' || s[i] == '-')) neg = s[i++] == '-';
|
||||
long v = 0;
|
||||
while (i < s.Length && s[i] is >= '0' and <= '9' && v <= int.MaxValue) v = v * 10 + (s[i++] - '0');
|
||||
v = neg ? -v : v;
|
||||
return (int)Math.Clamp(v, int.MinValue, int.MaxValue);
|
||||
}
|
||||
|
||||
/// <summary>Each row's value as the game reads the file at its start (menu_init): the last line's, in the row's range;
|
||||
/// then the rules for a file of an older options_version (the defaults that changed: such a file wrote the old one
|
||||
/// whether chosen or not), the old dynamic_resolution key, the Microphone without a device's name.</summary>
|
||||
Dictionary<string, int> Effective(Dictionary<string, string> lines, bool exists)
|
||||
{
|
||||
var v = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
foreach (var r in GameOptionsSchema.All)
|
||||
v[r.Key] = exists && lines.TryGetValue(r.Key, out var s) ? r.AsRead(Atoi(s)) : r.Default;
|
||||
if (!exists) return v;
|
||||
foreach (var (key, value) in Migrated(lines)) if (v.ContainsKey(key)) v[key] = value;
|
||||
if (!lines.ContainsKey(GameOptionsSchema.ResolutionKey) && lines.TryGetValue("dynamic_resolution", out var dyn))
|
||||
v[GameOptionsSchema.ResolutionKey] = Atoi(dyn) != 0 ? 0 : 1;
|
||||
if (!lines.ContainsKey(GameOptionsSchema.MicDeviceKey) && v[GameOptionsSchema.MicKey] >= 2) v[GameOptionsSchema.MicKey] = 1;
|
||||
return v;
|
||||
}
|
||||
|
||||
/// <summary>menu_init's rules for a file of an older options_version, as key and the value the game takes in its place
|
||||
/// (only the keys whose value it changes). The Debug tab's keys too: the game's readers before the menu take the same rules.</summary>
|
||||
List<(string Key, int Value)> Migrated(Dictionary<string, string> lines)
|
||||
{
|
||||
var list = new List<(string, int)>();
|
||||
var hasVersion = lines.TryGetValue(GameOptionsSchema.VersionKey, out var vs);
|
||||
var version = hasVersion ? Atoi(vs!) : 0;
|
||||
void Force(string key, int value)
|
||||
{
|
||||
if (!lines.TryGetValue(key, out var s) || Atoi(s) != value) list.Add((key, value));
|
||||
}
|
||||
if (!hasVersion) Force("game_speed", 1);
|
||||
if (version < 4) Force("descriptor_reuse", 1);
|
||||
if (version < 5)
|
||||
{
|
||||
Force("sampler_cache", 1); Force("fast_pipeline_link", 1); Force("lazy_write-back", 1); Force("opaque_textures_as_bc1", 1);
|
||||
Force("nvidia_reflex", 2);
|
||||
}
|
||||
if (version < 6)
|
||||
{
|
||||
Force("tail_early", 1);
|
||||
if (lines.TryGetValue("ultrawide", out var uw) && Atoi(uw) == 1) Force("ultrawide", NearestShape(mainScreen));
|
||||
}
|
||||
if (version < 7) Force("frame_pacing", 1);
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>ultrawide_rows.h ultrawide_row_nearest: the Ultrawide value whose shape is nearest the screen's; 16:9 unknown.</summary>
|
||||
internal static int NearestShape((int W, int H)? screen)
|
||||
{
|
||||
if (screen is not { } s || s.W <= 0 || s.H <= 0) return 0;
|
||||
var r = (double)s.W / s.H;
|
||||
double[] shapes = { 16.0 / 9.0, 1.6, 64.0 / 27.0, 32.0 / 9.0 };
|
||||
int best = 0;
|
||||
double bestD = 0;
|
||||
for (var i = 0; i < shapes.Length; i++)
|
||||
{
|
||||
var d = r > shapes[i] ? r / shapes[i] : shapes[i] / r;
|
||||
if (i == 0 || d < bestD) { best = i; bestD = d; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// ---- the values ----
|
||||
|
||||
/// <summary>A row's value: the launcher's change, else what the game reads from the file (its default without a line).
|
||||
/// KeyNotFoundException for a key that is no row (Raw has those).</summary>
|
||||
public int Get(string key)
|
||||
{
|
||||
GameOptionsSchema.Get(key);
|
||||
return set.TryGetValue(key, out var v) ? v : read[key];
|
||||
}
|
||||
|
||||
/// <summary>A line's value as the file has it (the last line with that key, trimmed), null without one. Any key.</summary>
|
||||
public string? Raw(string key) => raw.GetValueOrDefault(key);
|
||||
|
||||
/// <summary>A row's value's label as the game's menu shows it, the other rows as they are here (the Render resolution's
|
||||
/// sizes, the Anti-aliasing while an upscaler draws, the Microphone's device).</summary>
|
||||
public string Label(string key) => GameOptionsSchema.Get(key).Label(Get(key), this);
|
||||
|
||||
/// <summary>The values a row offers with the other rows as they are here: the Render resolution's steps for the Upscaler
|
||||
/// chosen (none with DLAA or a native AA), the Microphone's saved device, the row's own Choices otherwise. The value it has
|
||||
/// now is always in the list (a hand-edited one where it would sit).</summary>
|
||||
public IReadOnlyList<GameOptionChoice> ChoicesOf(string key)
|
||||
{
|
||||
var row = GameOptionsSchema.Get(key);
|
||||
if (row.Kind == GameOptionKind.Slider) return Array.Empty<GameOptionChoice>();
|
||||
var values = key switch
|
||||
{
|
||||
GameOptionsSchema.ResolutionKey => GameOptionsSchema.ResolutionSteps(Get(GameOptionsSchema.UpscalerKey)).ToList(),
|
||||
GameOptionsSchema.MicKey => Raw(GameOptionsSchema.MicDeviceKey) is { Length: > 0 } ? new List<int> { 0, 1, 2 } : new List<int> { 0, 1 },
|
||||
_ => row.Choices.Select(c => c.Value).ToList(),
|
||||
};
|
||||
var now = Get(key);
|
||||
if (!values.Contains(now)) values.Add(now);
|
||||
if (key == GameOptionsSchema.GpuKey)
|
||||
{
|
||||
var gpus = row.Choices.ToList();
|
||||
if (!gpus.Any(c => c.Value == now)) gpus.Add(new GameOptionChoice(now, row.Label(now)));
|
||||
return gpus;
|
||||
}
|
||||
if (key == GameOptionsSchema.MicKey && now >= 2) values = values.Where(v => v < 2 || v == now).ToList();
|
||||
return values.Select(v => new GameOptionChoice(v, row.Label(v, this))).ToList();
|
||||
}
|
||||
|
||||
/// <summary>The rows the launcher changed since the file was read, with their new values (Save writes these).</summary>
|
||||
public IReadOnlyDictionary<string, int> Changes => set;
|
||||
|
||||
/// <summary>The file's lines that are no row here, in order, as (key, value): the KeptKeys and pad_/key_ lines, and
|
||||
/// any key nobody knows (kept as it is). Lines without a key (blank, a comment) are kept too but not listed.</summary>
|
||||
public IReadOnlyList<(string Key, string Value)> OtherLines =>
|
||||
lines.Select(l => (Key: KeyOf(l), Line: l)).Where(x => x.Key != null && GameOptionsSchema.ByKey(x.Key) == null)
|
||||
.Select(x => (x.Key!, x.Line[(x.Key!.Length + 1)..])).ToList();
|
||||
|
||||
/// <summary>OtherLines' keys that neither the schema nor KeptKeys knows.</summary>
|
||||
public IReadOnlyList<string> UnknownKeys => OtherLines.Select(o => o.Key).Where(k => !GameOptionsSchema.IsKept(k)).Distinct().ToList();
|
||||
|
||||
/// <summary>Sets a row as the game's menu would (set_row): the value inside its range and on its steps (GameOptionRow.Clamp);
|
||||
/// the Quality preset sets its rows (PresetValues, the Render resolution then on the Upscaler's nearest step); another
|
||||
/// Upscaler moves the Render resolution to its nearest step; a row that is not PresetExempt, changed, turns the preset
|
||||
/// back to Custom. Returns the value set. Nothing is written until Save.</summary>
|
||||
public int Set(string key, int value)
|
||||
{
|
||||
var row = GameOptionsSchema.Get(key);
|
||||
var v = row.Clamp(value);
|
||||
if (key == GameOptionsSchema.PresetKey)
|
||||
{
|
||||
Put(key, v);
|
||||
foreach (var (k, pv) in GameOptionsSchema.PresetValues(v)) Put(k, pv);
|
||||
if (v > 0) Put(GameOptionsSchema.ResolutionKey, GameOptionsSchema.SnapResolution(Get(GameOptionsSchema.UpscalerKey), Get(GameOptionsSchema.ResolutionKey)));
|
||||
return v;
|
||||
}
|
||||
var changed = Get(key) != v;
|
||||
Put(key, v);
|
||||
if (key == GameOptionsSchema.UpscalerKey)
|
||||
Put(GameOptionsSchema.ResolutionKey, GameOptionsSchema.SnapResolution(v, Get(GameOptionsSchema.ResolutionKey)));
|
||||
if (changed && !row.PresetExempt) Put(GameOptionsSchema.PresetKey, 0);
|
||||
return v;
|
||||
}
|
||||
|
||||
void Put(string key, int v)
|
||||
{
|
||||
if (read[key] == v) set.Remove(key); // (what the game reads from the file already: nothing to write)
|
||||
else set[key] = v;
|
||||
}
|
||||
|
||||
/// <summary>The benchmark's recommendations (key to value): the Quality preset first when it is one of them, then each
|
||||
/// other row with Set's rules (so a row the preset set to the same value leaves it as it is; one that differs, and is not
|
||||
/// PresetExempt, makes it Custom, as in the game). KeyNotFoundException, and nothing set, for a key that is no row.
|
||||
/// Returns the rows' values afterwards, for the keys given. Nothing is written until Save.</summary>
|
||||
public IReadOnlyDictionary<string, int> Apply(IReadOnlyDictionary<string, int> values)
|
||||
{
|
||||
foreach (var k in values.Keys) GameOptionsSchema.Get(k);
|
||||
if (values.TryGetValue(GameOptionsSchema.PresetKey, out var p)) Set(GameOptionsSchema.PresetKey, p);
|
||||
foreach (var (k, v) in values)
|
||||
if (k != GameOptionsSchema.PresetKey) Set(k, v);
|
||||
return values.Keys.ToDictionary(k => k, Get, StringComparer.Ordinal);
|
||||
}
|
||||
public IReadOnlyDictionary<string, int> Apply(Dictionary<string, int> values) => Apply((IReadOnlyDictionary<string, int>)values);
|
||||
|
||||
// ---- writing ----
|
||||
|
||||
/// <summary>Writes the launcher's changes into the file as it is NOW on disk (read again here): each changed row's lines
|
||||
/// get its value, every other line stays exactly as the file has it (so a line changed outside since Load is kept, as
|
||||
/// the game's merge keeps it), a changed row the file has no line for is added before options_version. A file of an
|
||||
/// older options_version is brought up to the current one as the game would read it (the values its rules give are
|
||||
/// written, options_version=7), so the game does not read the launcher's values by the old rules. The whole file is
|
||||
/// written beside it as .new and then put in its place: a reader never meets half a file, and a failure leaves the old
|
||||
/// one (IOException). Nothing to write: nothing written. The caller refuses while the game runs (Game.IsRunning).
|
||||
/// Afterwards this object holds the file as written.</summary>
|
||||
public void Save()
|
||||
{
|
||||
if (set.Count == 0) return;
|
||||
var exists = File.Exists(Path);
|
||||
var text = exists ? File.ReadAllText(Path, Encoding.Latin1) : "";
|
||||
var disk = SplitLines(text);
|
||||
var nl = text.Contains("\r\n") ? "\r\n" : text.Contains('\n') ? "\n" : OperatingSystem.IsWindows() ? "\r\n" : "\n";
|
||||
var diskRaw = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var l in disk)
|
||||
if (KeyOf(l) is { } k) diskRaw[k] = Trim(l[(k.Length + 1)..]);
|
||||
|
||||
var write = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
var hasVersion = diskRaw.TryGetValue(GameOptionsSchema.VersionKey, out var vs);
|
||||
if (exists && (!hasVersion || Atoi(vs!) < GameOptionsSchema.CurrentVersion))
|
||||
{
|
||||
foreach (var (k, v) in Migrated(diskRaw)) write[k] = v.ToString(CultureInfo.InvariantCulture);
|
||||
if (!diskRaw.ContainsKey(GameOptionsSchema.ResolutionKey) && diskRaw.TryGetValue("dynamic_resolution", out var dyn))
|
||||
write[GameOptionsSchema.ResolutionKey] = (Atoi(dyn) != 0 ? 0 : 1).ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
foreach (var (k, v) in set) write[k] = v.ToString(CultureInfo.InvariantCulture);
|
||||
var bump = !exists || !hasVersion || Atoi(vs!) < GameOptionsSchema.CurrentVersion;
|
||||
if (bump) write[GameOptionsSchema.VersionKey] = GameOptionsSchema.CurrentVersion.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
var outLines = new List<string>(disk.Count + write.Count);
|
||||
var done = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var l in disk)
|
||||
{
|
||||
var k = KeyOf(l);
|
||||
if (k != null && write.TryGetValue(k, out var v)) { outLines.Add(k + "=" + v); done.Add(k); }
|
||||
else outLines.Add(l);
|
||||
}
|
||||
var missing = write.Keys.Where(k => !done.Contains(k) && k != GameOptionsSchema.VersionKey)
|
||||
.OrderBy(k => GameOptionsSchema.ByKey(k) is { } r ? IndexOf(r) : int.MaxValue).Select(k => k + "=" + write[k]).ToList();
|
||||
var at = outLines.FindIndex(l => KeyOf(l) == GameOptionsSchema.VersionKey);
|
||||
if (at < 0) at = outLines.Count;
|
||||
outLines.InsertRange(at, missing);
|
||||
if (bump && !done.Contains(GameOptionsSchema.VersionKey))
|
||||
outLines.Insert(at + missing.Count, GameOptionsSchema.VersionKey + "=" + GameOptionsSchema.CurrentVersion);
|
||||
|
||||
var sb = new StringBuilder();
|
||||
foreach (var l in outLines) sb.Append(l).Append(nl); // (every line ends, as the game writes them)
|
||||
WriteWhole(Path, Encoding.Latin1.GetBytes(sb.ToString()));
|
||||
Exists = true;
|
||||
Parse(sb.ToString());
|
||||
set.Clear();
|
||||
}
|
||||
|
||||
static int IndexOf(GameOptionRow r)
|
||||
{
|
||||
for (var i = 0; i < GameOptionsSchema.All.Count; i++) if (ReferenceEquals(GameOptionsSchema.All[i], r)) return i;
|
||||
return int.MaxValue;
|
||||
}
|
||||
|
||||
/// <summary>The file's lines without their line ends (\r\n or \n).</summary>
|
||||
static List<string> SplitLines(string text)
|
||||
{
|
||||
var list = new List<string>();
|
||||
var start = 0;
|
||||
while (start < text.Length)
|
||||
{
|
||||
var nl = text.IndexOf('\n', start);
|
||||
var end = nl < 0 ? text.Length : nl;
|
||||
var line = text[start..end];
|
||||
if (line.EndsWith('\r')) line = line[..^1];
|
||||
list.Add(line);
|
||||
start = nl < 0 ? text.Length : nl + 1;
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>file_whole.h's write_whole: <path>.new written, flushed to the disk and closed, then moved over path;
|
||||
/// on any failure the .new is removed, path is as it was, and the IOException goes to the caller.</summary>
|
||||
internal static void WriteWhole(string path, byte[] data)
|
||||
{
|
||||
var part = path + ".new";
|
||||
try
|
||||
{
|
||||
using (var f = new FileStream(part, FileMode.Create, FileAccess.Write, FileShare.None))
|
||||
{
|
||||
f.Write(data);
|
||||
f.Flush(true);
|
||||
}
|
||||
File.Move(part, path, true);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
try { File.Delete(part); } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
502
launcher/Logic/GameOptions/GameOptionsSchema.cs
Normal file
502
launcher/Logic/GameOptions/GameOptionsSchema.cs
Normal file
@@ -0,0 +1,502 @@
|
||||
// The game's Options menu as data: gpu/vk/vk_menu.cpp's Row table (rows[]), the tx_* functions that label its values, the
|
||||
// keys ini_key gives them, the defaults of vk_menu.h's Options, and the Quality preset (apply_preset, hn_preset). Every row
|
||||
// the game keeps in triforce_options.ini is here except the ones KeptKeys names (the Debug tab, the Layout preset); the Game
|
||||
// language is language.txt's, not this file's (Languages.cs). Labels are the menu's own words: players compare them.
|
||||
// Where the menu's label depends on this PC (the display's refresh, a gyroscope, what the driver runs) the label here is the
|
||||
// one the menu shows when it knows nothing of it. When vk_menu.cpp's table changes, change this one: the test
|
||||
// "game options: schema matches vk_menu.cpp" reads the table and says what differs.
|
||||
using System.Globalization;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
public static class GameOptionsSchema
|
||||
{
|
||||
/// <summary>The file the game reads at its start and writes at every change in its menu, in the game folder.</summary>
|
||||
public const string FileName = "triforce_options.ini";
|
||||
/// <summary>The options_version the game writes (vk_menu.cpp save): the file's format, which menu_init's rules read.</summary>
|
||||
public const int CurrentVersion = 7;
|
||||
|
||||
public const string OutputResKey = "output_res";
|
||||
public const string ResolutionKey = "resolution";
|
||||
public const string UpscalerKey = "dlss";
|
||||
public const string PresetKey = "quality_preset";
|
||||
public const string RumbleKey = "rumble_strength";
|
||||
public const string GpuKey = "gpu_device";
|
||||
public const string MicKey = "microphone";
|
||||
public const string HandheldKey = "handheld_profile";
|
||||
public const string VersionKey = "options_version";
|
||||
public const string MicDeviceKey = "microphone_device";
|
||||
|
||||
/// <summary>The names of the graphics cards, in the order the game counts them (its GPU device row's 1 is the first),
|
||||
/// for the GPU device row's labels. The launcher sets it (UseSystemGpus: Gpus.List()). The game lists the cards
|
||||
/// Vulkan gives it, which is usually but not always the order Windows lists them in. Null: "1: Device 1" and so on, as
|
||||
/// the menu shows a card it has no name for.</summary>
|
||||
public static Func<IReadOnlyList<string>>? GpuNames { get; set; }
|
||||
|
||||
/// <summary>GpuNames from Gpus.List() (this PC's display adapters).</summary>
|
||||
public static void UseSystemGpus() => GpuNames = () => Gpus.List().Select(g => g.Name).ToList();
|
||||
|
||||
// ---- the keys ----
|
||||
|
||||
/// <summary>vk_menu.cpp ini_key: a few rows keep the keys they were first saved with; every other row's key is its
|
||||
/// name lower-cased, its spaces as '_', cut to 31 characters.</summary>
|
||||
public static string IniKey(string name) => name switch
|
||||
{
|
||||
"Output resolution" => OutputResKey,
|
||||
"Render resolution" => ResolutionKey,
|
||||
"Game frame rate cap" => "frame_rate_cap",
|
||||
"Window scaling filter" => "upscaling",
|
||||
"Upscaler" => UpscalerKey,
|
||||
"Start next frame early" => "tail_early",
|
||||
_ => Cut(new string(name.Select(c => c == ' ' ? '_' : c is >= 'A' and <= 'Z' ? (char)(c + 32) : c).ToArray()), 31),
|
||||
};
|
||||
static string Cut(string s, int n) => s.Length > n ? s[..n] : s;
|
||||
|
||||
// ---- the labels (the tx_* functions) ----
|
||||
|
||||
static int V(IGameOptionValues? o, string key, int dflt) => o?.Get(key) ?? dflt;
|
||||
static string Pick(string[] t, int v) => t[Math.Clamp(v, 0, t.Length - 1)];
|
||||
static string OrFirst(string[] t, int v) => v >= 0 && v < t.Length ? t[v] : t[0];
|
||||
static string Pct(int v) => v.ToString(CultureInfo.InvariantCulture) + "%";
|
||||
|
||||
static string TxOnoff(int v, IGameOptionValues? o) => v != 0 ? "On" : "Off";
|
||||
static string TxMenuShortcut(int v, IGameOptionValues? o) => v != 0 ? "F1 only" : "Insert or F1";
|
||||
static string TxHdr(int v, IGameOptionValues? o) => v == 1 ? "Expanded" : v == 2 ? "Native" : "Off";
|
||||
static string TxNits(int v, IGameOptionValues? o) => v.ToString(CultureInfo.InvariantCulture) + " nits";
|
||||
/// <summary>tx_fps_cap. 6, Monitor's rate, shows the display's rate in the game ("Monitor's rate (144)") once it knows it.</summary>
|
||||
static string TxFpsCap(int v, IGameOptionValues? o)
|
||||
{
|
||||
if (v < 0) return v == -1 ? "45" : v == -2 ? "40" : "30";
|
||||
if (v >= 6) return "Monitor's rate";
|
||||
return new[] { "60 (the console's)", "90", "120", "144", "165", "240" }[v];
|
||||
}
|
||||
static string TxSteadyFps(int v, IGameOptionValues? o) => v == 1 ? "Any rate" : v == 2 ? "Refresh steps" : "Off";
|
||||
/// <summary>tx_gyro without a controller's answer (the game adds "(gyro found)" and the like).</summary>
|
||||
static string TxGyro(int v, IGameOptionValues? o) => v != 0 ? "On" : "Off";
|
||||
static string TxMousecam(int v, IGameOptionValues? o) => v != 0 ? "Native" : "As the stick";
|
||||
static string TxSens(int v, IGameOptionValues? o) =>
|
||||
(v < 0 ? "-" : "") + (Math.Abs(v) / 100).ToString(CultureInfo.InvariantCulture) + "." + (Math.Abs(v) % 100).ToString("00", CultureInfo.InvariantCulture);
|
||||
static readonly string[] Upscales = { "Off", "Catmull-Rom", "Lanczos", "AMD FSR 1" };
|
||||
/// <summary>tx_filter as tx_upscale: the game shows "Not needed (window = output)" while its window is the output's size.</summary>
|
||||
static string TxFilter(int v, IGameOptionValues? o) => OrFirst(Upscales, v);
|
||||
/// <summary>tx_reflex as on an NVIDIA card with Reflex (elsewhere the game shows Off, and On with DLSS frame generation).</summary>
|
||||
static string TxReflex(int v, IGameOptionValues? o) => Pick(new[] { "Off", "On", "On + Boost" }, v);
|
||||
/// <summary>tx_antilag as on an AMD card with Anti-Lag 2 (elsewhere the game shows Off).</summary>
|
||||
static string TxAntilag(int v, IGameOptionValues? o) => v != 0 ? "On" : "Off";
|
||||
static readonly string[] Upscalers = { "Game", "NVIDIA DLSS", "NVIDIA DLAA", "AMD FSR 3.1", "AMD FSR 4", "AMD FSR 4 Native AA", "AMD FSR 3.1 Native AA" };
|
||||
/// <summary>tx_upscaler by the value chosen (the game shows what runs: the game's own where the choice cannot).</summary>
|
||||
static string TxUpscaler(int v, IGameOptionValues? o) => Pick(Upscalers, v);
|
||||
/// <summary>tx_dlss_model without RX_VK_DLSS_PRESET.</summary>
|
||||
static string TxDlssModel(int v, IGameOptionValues? o) => Pick(new[] { "Transformer (K)", "Transformer 2 (M)", "Transformer 2 (L)", "NVIDIA default" }, v);
|
||||
static string TxAniso(int v, IGameOptionValues? o) => OrFirst(new[] { "Game", "2x", "4x", "8x", "16x" }, v);
|
||||
/// <summary>tx_tex_detail: the game adds the level Automatic gives ("Automatic (Full)") once its first texture is made.</summary>
|
||||
static string TxTexDetail(int v, IGameOptionValues? o) => OrFirst(new[] { "Automatic", "Full", "Reduced", "Low" }, v);
|
||||
static string TxPercent(int v, IGameOptionValues? o) => Pct(v);
|
||||
static string TxRdxTonemap(int v, IGameOptionValues? o) => v == 2 ? "RenoDRT" : v != 0 ? "PsychoV35" : "Vanilla";
|
||||
static string TxRdxGamma(int v, IGameOptionValues? o) => v == 1 ? "2.2" : v == 2 ? "BT.1886 (2.4)" : "Off";
|
||||
static string TxRdxMidgray(int v, IGameOptionValues? o) => v == 1 ? "Vanilla" : v == 2 ? "Eye adaptation" : "Render";
|
||||
static string TxRdxSpace(int v, IGameOptionValues? o) => v == 1 ? "BT.709" : v == 2 ? "DCI-P3" : "Vanilla";
|
||||
static string TxRdxGrade(int v, IGameOptionValues? o) => v.ToString(CultureInfo.InvariantCulture);
|
||||
static string TxSpeed(int v, IGameOptionValues? o) => v != 0 ? "Real time" : "Per frame";
|
||||
static string TxTextSpeed(int v, IGameOptionValues? o) => OrFirst(new[] { "Normal", "2x", "4x", "Instant" }, v);
|
||||
static string TxUltrawide(int v, IGameOptionValues? o) => Pick(new[] { "16:9", "16:10", "21:9", "32:9" }, v);
|
||||
static string TxWideHud(int v, IGameOptionValues? o) => v != 0 ? "Screen edges" : "Middle";
|
||||
static string TxWideMenus(int v, IGameOptionValues? o) => Pick(new[] { "Full width", "Centred, blurred sides", "Centred, black bars" }, v);
|
||||
static string TxPrompts(int v, IGameOptionValues? o) =>
|
||||
Pick(new[] { "Auto", "Switch", "Xbox", "PlayStation 4", "PlayStation 5", "Steam Deck", "Keyboard & mouse" }, v);
|
||||
static string TxRumble(int v, IGameOptionValues? o) => v != 0 ? Pct(v) : "Off";
|
||||
static string TxVolume(int v, IGameOptionValues? o) => v != 0 ? Pct(v) : "Muted";
|
||||
static string TxMenuSounds(int v, IGameOptionValues? o) => v != 0 ? Pct(v) : "Off";
|
||||
static string TxSprint(int v, IGameOptionValues? o) => v == 1 ? "Left stick click" : v == 2 ? "B" : "Off";
|
||||
static string TxSprintMode(int v, IGameOptionValues? o) => v != 0 ? "Hold" : "Toggle";
|
||||
static string TxStickDeadZone(int v, IGameOptionValues? o) => OrFirst(new[] { "Default (24%)", "5%", "10%", "15%", "20%", "30%" }, v);
|
||||
static string TxOwnDeadZone(int v, IGameOptionValues? o) => v < 0 ? "As Stick dead zone" : Pct(v);
|
||||
static string TxWalkKey(int v, IGameOptionValues? o) => OrFirst(new[] { "Off", "Caps Lock", "Shift", "Ctrl", "Tab" }, v);
|
||||
static string TxAudioOutput(int v, IGameOptionValues? o) => OrFirst(new[] { "Auto", "Stereo", "5.1" }, v);
|
||||
static string TxDeadzone(int v, IGameOptionValues? o) => Pick(new[] { "Low", "Standard", "High" }, v);
|
||||
static string TxRobust(int v, IGameOptionValues? o) => OrFirst(new[] { "Auto", "Off", "On" }, v);
|
||||
static string TxMesh(int v, IGameOptionValues? o) => v == 1 ? "Compute fallback" : "Auto";
|
||||
static string TxPerf(int v, IGameOptionValues? o) => v == 1 ? "On" : v >= 2 ? "Full" : "Off";
|
||||
static string TxDlssg(int v, IGameOptionValues? o) => v == 1 ? "2x" : v == 2 ? "3x" : v == 3 ? "4x" : "Off";
|
||||
/// <summary>tx_framegen where AMD's library can make the frames (elsewhere the game shows a saved AMD FSR 4 as 2x).</summary>
|
||||
static string TxFramegen(int v, IGameOptionValues? o) => Pick(new[] { "Off", "Auto", "2x", "3x", "4x", "5x", "6x", "7x", "8x", "AMD FSR 4" }, v);
|
||||
static readonly string[] Presets = { "Custom", "Minimum (6GB)", "Low (8GB)", "Balanced (12GB)", "High (16GB)", "Ultra (20GB+)" };
|
||||
static string TxPreset(int v, IGameOptionValues? o) => Pick(Presets, v);
|
||||
/// <summary>tx_gpu: 0 "Auto", then "<n>: <name>" counted from 0 (GpuNames), "<n>: Device <n>" without a name.</summary>
|
||||
static string TxGpu(int v, IGameOptionValues? o)
|
||||
{
|
||||
if (v <= 0) return "Auto";
|
||||
var idx = v - 1;
|
||||
var names = GpuNamesNow();
|
||||
return idx < names.Count ? idx + ": " + names[idx] : idx + ": Device " + idx;
|
||||
}
|
||||
static IReadOnlyList<string> GpuNamesNow()
|
||||
{
|
||||
try { return GpuNames?.Invoke() ?? Array.Empty<string>(); } catch (Exception) { return Array.Empty<string>(); }
|
||||
}
|
||||
/// <summary>tx_mic without the game's device list: Off, Default, and a device by the name the file keeps
|
||||
/// (microphone_device), "Microphone" without one.</summary>
|
||||
static string TxMic(int v, IGameOptionValues? o)
|
||||
{
|
||||
if (v <= 0) return "Off";
|
||||
if (v == 1) return "Default";
|
||||
var name = o?.Raw(MicDeviceKey) is { } raw ? MicName(raw) : "";
|
||||
return name.Length > 0 ? name : "Microphone";
|
||||
}
|
||||
/// <summary>The microphone_device line's name as text: the file's bytes are UTF-8 (read here as Latin-1, byte for byte).</summary>
|
||||
internal static string MicName(string raw) => System.Text.Encoding.UTF8.GetString(System.Text.Encoding.Latin1.GetBytes(raw)).Trim();
|
||||
|
||||
// ---- the Output resolution and the Render resolution ----
|
||||
|
||||
/// <summary>The Output resolution's sizes by their saved value (kOutputs); 6 came after the others so that saved values
|
||||
/// keep their sizes.</summary>
|
||||
public static readonly IReadOnlyList<(int W, int H)> Outputs = new[] { (2048, 1152), (2560, 1440), (3840, 2160), (1920, 1080), (5120, 1440), (5120, 2880), (5120, 2160) };
|
||||
/// <summary>The order the menu shows them in, smallest to largest (kOutputOrder).</summary>
|
||||
public static readonly IReadOnlyList<int> OutputOrder = new[] { 3, 0, 1, 2, 4, 6, 5 };
|
||||
static int OutputChoice(int v) => v >= 0 && v < Outputs.Count ? v : 0;
|
||||
static string TxOutputRes(int v, IGameOptionValues? o)
|
||||
{
|
||||
var (w, h) = Outputs[OutputChoice(v)];
|
||||
return w + "x" + h;
|
||||
}
|
||||
|
||||
// (upscaler_rows.h)
|
||||
const int Game = 0, Dlss = 1, Dlaa = 2, Fsr3 = 3, Fsr4 = 4, Fsr4Aa = 5, Fsr3Aa = 6;
|
||||
/// <summary>The Upscaler row's order in the menu: each engine's native anti-aliasing after it (kOrder).</summary>
|
||||
public static readonly IReadOnlyList<int> UpscalerOrder = new[] { Game, Dlss, Dlaa, Fsr3, Fsr3Aa, Fsr4, Fsr4Aa };
|
||||
static readonly int[] Percents = { 0, 100, 75, 67, 50, 58, 33 };
|
||||
static int Percent(int v) => v > 0 && v < Percents.Length ? Percents[v] : 0;
|
||||
static bool FullScale(int up) => up == Dlaa || up == Fsr4Aa || up == Fsr3Aa;
|
||||
static bool ScalesByMode(int up) => up == Dlss || up == Fsr3 || up == Fsr4;
|
||||
static readonly int[] GameSteps = { 0, 1, 2, 3, 4 }, DlssSteps = { 0, 3, 5, 4, 6 };
|
||||
/// <summary>The Render resolution values the menu steps through with this Upscaler (none with DLAA or a native AA:
|
||||
/// the 3D is drawn at full size).</summary>
|
||||
public static IReadOnlyList<int> ResolutionSteps(int upscaler) => FullScale(upscaler) ? Array.Empty<int>() : ScalesByMode(upscaler) ? DlssSteps : GameSteps;
|
||||
/// <summary>upscaler_rows.h snap: v as one of the upscaler's steps, the nearest in size (the larger on a tie); Auto stays,
|
||||
/// and with a full-size upscaler v is kept for the next.</summary>
|
||||
public static int SnapResolution(int upscaler, int v)
|
||||
{
|
||||
if (FullScale(upscaler) || Percent(v) == 0) return Percent(v) == 0 ? 0 : v;
|
||||
var steps = ScalesByMode(upscaler) ? DlssSteps : GameSteps;
|
||||
int best = v, bestD = 1000;
|
||||
foreach (var s in steps)
|
||||
{
|
||||
if (s == v) return v;
|
||||
if (Percent(s) == 0) continue;
|
||||
var d = Math.Abs(Percent(s) - Percent(v));
|
||||
if (d < bestD || (d == bestD && Percent(s) > Percent(best))) { best = s; bestD = d; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
static string ModeName(int v) => Percent(v) switch { 67 => "Quality", 58 => "Balanced", 50 => "Performance", 33 => "Ultra Performance", _ => "" };
|
||||
/// <summary>tx_resolution: by the Upscaler chosen, and the size the game draws the 3D at for a fixed share of the
|
||||
/// Output resolution (the handheld profile's 1536x864), a twelfth of it as the game takes it.</summary>
|
||||
static string TxResolution(int v, IGameOptionValues? o)
|
||||
{
|
||||
var up = V(o, UpscalerKey, 0);
|
||||
if (up == Dlaa) return "Native (DLAA)";
|
||||
if (up == Fsr4Aa) return "Native (FSR 4)";
|
||||
if (up == Fsr3Aa) return "Native (FSR 3.1)";
|
||||
var p = Percent(v);
|
||||
if (p == 0) return "Auto (dynamic)";
|
||||
if (ScalesByMode(up) && ModeName(v).Length > 0) return ModeName(v) + " (" + p + "%)";
|
||||
var (ow, oh) = V(o, HandheldKey, 0) != 0 ? (1536, 864) : Outputs[OutputChoice(V(o, OutputResKey, 0))];
|
||||
var k = Math.Min(Math.Max((int)(p / 100.0f * 12.0f + 0.5f), 1), 12);
|
||||
return p + "% (" + (ow * k + 11) / 12 + "x" + oh * k / 12 + ")";
|
||||
}
|
||||
static readonly string[] AaNames = { "Game SMAA", "Off", "FXAA", "SMAA Ultra" };
|
||||
/// <summary>tx_aa: the choice, or whose anti-aliasing the picture has while DLSS or FSR draws (the row does not apply).</summary>
|
||||
static string TxAa(int v, IGameOptionValues? o)
|
||||
{
|
||||
var up = V(o, UpscalerKey, 0);
|
||||
if (up == Dlss || up == Dlaa) return "DLSS's own";
|
||||
if (up != Game) return "FSR's own";
|
||||
return OrFirst(AaNames, v);
|
||||
}
|
||||
|
||||
// ---- the rows ----
|
||||
|
||||
static GameOptionRow Row(GameOptionTab tab, string? section, string name, int lo, int hi, int step, int dflt, GameOptionKind kind,
|
||||
Func<int, IGameOptionValues?, string> format, bool restart, bool exempt, string help)
|
||||
{
|
||||
var key = IniKey(name);
|
||||
Func<IReadOnlyList<GameOptionChoice>>? list = null;
|
||||
if (kind == GameOptionKind.Choice)
|
||||
{
|
||||
IEnumerable<int> values = key switch
|
||||
{
|
||||
OutputResKey => OutputOrder,
|
||||
UpscalerKey => UpscalerOrder,
|
||||
ResolutionKey => GameSteps,
|
||||
MicKey => new[] { 0, 1 },
|
||||
_ => Enumerable.Range(lo, hi - lo + 1),
|
||||
};
|
||||
if (key == GpuKey)
|
||||
list = () => new[] { new GameOptionChoice(0, "Auto") }
|
||||
.Concat(GpuNamesNow().Take(hi).Select((n, i) => new GameOptionChoice(i + 1, i + ": " + n))).ToList();
|
||||
else
|
||||
{
|
||||
var fixedList = values.Select(v => new GameOptionChoice(v, format(v, null))).ToList();
|
||||
list = () => fixedList;
|
||||
}
|
||||
}
|
||||
return new GameOptionRow
|
||||
{
|
||||
Tab = tab, Section = section, Name = name, Key = key, Lo = lo, Hi = hi, Step = step, Default = dflt, Kind = kind,
|
||||
Format = format, ChoiceList = list, Restart = restart, PresetExempt = exempt, Help = help,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Every row, in the menu's order (Display, Graphics, System, Audio, Controls as the table has them; the
|
||||
/// Motion page's rows and Button prompts after the Controls tab's own).</summary>
|
||||
public static readonly IReadOnlyList<GameOptionRow> All = new[]
|
||||
{
|
||||
Row(GameOptionTab.Display, "Screen", "Fullscreen", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, true,
|
||||
"Fills the whole screen with the game, without the window's border. The same as F10 or Alt+Enter."),
|
||||
Row(GameOptionTab.Display, "Screen", "Output resolution", 0, 6, 1, 0, GameOptionKind.Choice, TxOutputRes, true, false,
|
||||
"The game's whole frame, HUD included, before it is scaled to the window. Docked only. Applies after a restart."),
|
||||
Row(GameOptionTab.Display, "Screen", "GPU device", 0, 8, 1, 0, GameOptionKind.Choice, TxGpu, true, true,
|
||||
"Which graphics card the game runs on. Applies after a restart."),
|
||||
Row(GameOptionTab.Display, "Widescreen", "Ultrawide", 0, 3, 1, 0, GameOptionKind.Choice, TxUltrawide, true, false,
|
||||
"The camera's shape: the game's own 16:9, or a fixed 16:10, 21:9 or 32:9 for a screen or a window of that shape. A screen of another shape shows the picture between black bars. Applies after a restart."),
|
||||
Row(GameOptionTab.Display, "Widescreen", "Ultrawide HUD", 0, 1, 1, 0, GameOptionKind.Choice, TxWideHud, true, true,
|
||||
"With Ultrawide: where the hearts, the item slot and the map sit on a screen wider than 16:9. Middle: in the middle 16:9, as on a normal screen. Screen edges: out in the screen's corners. Applies after a restart."),
|
||||
Row(GameOptionTab.Display, "Widescreen", "Ultrawide menus", 0, 2, 1, 1, GameOptionKind.Choice, TxWideMenus, false, false,
|
||||
"With Ultrawide: the pause, item and map menus, and what shows beside them. Loading screens and pre-rendered movies, which draw no world either, get the same sides; a fade always covers the whole screen. Changes at once."),
|
||||
Row(GameOptionTab.Display, "Frame rate", "Game frame rate cap", -3, 6, 1, 0, GameOptionKind.Choice, TxFpsCap, true, true,
|
||||
"Limits frames rendered by the game. Generated frames are additional. Takes a restart. 30, 40 and 45 are for a PC or handheld that holds one of them steadily where 60 swings; the game keeps its speed. Past 60 is experimental: the game keeps real time, but some cutscenes and bosses can misbehave (Gohma, the intro's narration). 60 is the safe choice. Monitor's rate is the refresh rate of the screen the game starts on, from 30 to 240."),
|
||||
Row(GameOptionTab.Display, "Frame rate", "Steady frame rate", 0, 2, 1, 0, GameOptionKind.Choice, TxSteadyFps, true, true,
|
||||
"Paces the game to a frame rate this PC holds where you are, under the Game frame rate cap, and shows each frame a period after the last, so that frames come evenly instead of each as soon as it is ready. It goes down quickly where frames run late and back up slowly where there is room; loads and single hitches do not move it. Gives up some frame rate for steadiness. Any rate suits a screen with variable refresh (G-SYNC, FreeSync) or VSync off; Refresh steps keeps to whole divisions of the refresh rate (at 240 Hz: 120, 80, 60 ...) for VSync without variable refresh. Takes a restart."),
|
||||
Row(GameOptionTab.Display, "Frame rate", "Reflex frame limit", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, true,
|
||||
"With DLSS frame generation: NVIDIA Reflex holds the Game frame rate cap where each frame starts, in place of the game's own wait, so a frame waits once and the controls are read later. The game's own wait is back whenever no frame is being generated. Where RivaTuner Statistics Server is the game's limiter it holds the frames instead. Changes at once."),
|
||||
Row(GameOptionTab.Display, "Frame rate", "VSync", 0, 1, 1, 1, GameOptionKind.Choice, TxOnoff, false, true,
|
||||
"Whether a finished frame waits for the screen's next refresh. Off shows it at once: a little less delay, and the picture can tear. Neither changes the frame rate, which the Game frame rate cap limits. Changes at once."),
|
||||
Row(GameOptionTab.Display, "Frame rate", "FPS counter", 0, 2, 1, 0, GameOptionKind.Choice, TxPerf, false, true,
|
||||
"On: frames per second in the top right corner. Full: a performance overlay in its place, with the GPU's and the CPU's load, temperatures and memory, the frame rate and its 1% and 0.1% lows, the frame times and their graph, the waits per frame and the picture's settings."),
|
||||
Row(GameOptionTab.Display, "High dynamic range", "HDR", 0, 2, 1, 0, GameOptionKind.Choice, TxHdr, false, true,
|
||||
"HDR10 out on an HDR display (Windows: Use HDR on in the display settings). Expanded: the game's SDR picture, its white at the paper white and its highlights up to the peak. Native: the game's own HDR, told the display's peak and paper white."),
|
||||
Row(GameOptionTab.Display, "High dynamic range", "HDR paper white", 80, 400, 10, 200, GameOptionKind.Slider, TxNits, false, true,
|
||||
"How bright the picture's white is with HDR on. Around 200 for a normal room; higher in a bright one."),
|
||||
Row(GameOptionTab.Display, "High dynamic range", "HDR peak brightness", 400, 10000, 100, 1000, GameOptionKind.Slider, TxNits, false, true,
|
||||
"The brightest highlights with HDR on: set it to your display's peak brightness."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX HDR", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, true, true,
|
||||
"With HDR set to Native: RenoDX's tone mapping, eye adaptation and colour grading in place of the game's own, and its rows below. Off: the game's own HDR. Applies after a restart. RenoDX is by Carlos Lopez (clshortfuse), under the MIT license."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX tonemapper", 0, 2, 1, 1, GameOptionKind.Choice, TxRdxTonemap, false, true,
|
||||
"With HDR Native: how the scene's light is brought to the display. Vanilla: the game's own curve. PsychoV35: RenoDX's, which keeps hue and saturation into the highlights, up to the peak brightness. RenoDRT: RenoDX's, which carries the game's SDR look up to the peak by brightness. RenoDX is by Carlos Lopez (clshortfuse), under the MIT license."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX gamma correction", 0, 2, 1, 0, GameOptionKind.Choice, TxRdxGamma, false, true,
|
||||
"Shows the picture as a 2.2 or BT.1886 (2.4) display would, as the game was made to be seen: darker shadows. Off keeps the sRGB curve. With every tonemapper. PsychoV35 and RenoDRT still end at the peak brightness; Vanilla's highlights are the game's own, which 2.2 dims a little and 2.4 brightens a little."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX midgray", 0, 2, 1, 1, GameOptionKind.Choice, TxRdxMidgray, false, true,
|
||||
"With PsychoV35: what the scene's middle grey is held to. Render: as rendered. Vanilla: where the game's own curve puts it. Eye adaptation: it follows what is on screen over a few seconds, weighted towards the middle of the view, as eyes adjust."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX match tone slope", 0, 1, 1, 1, GameOptionKind.Choice, TxOnoff, false, true,
|
||||
"With PsychoV35: gives the mid tones the contrast of the game's own curve. Off: PsychoV35's own, softer."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX tone slope", 0, 100, 1, 50, GameOptionKind.Slider, TxRdxGrade, false, true,
|
||||
"With PsychoV35: the steepness of the tone curve through middle grey. 50 leaves it unchanged."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX hue clip", 0, 100, 5, 50, GameOptionKind.Slider, TxPercent, false, true,
|
||||
"With PsychoV35: how much bright colours turn as they do where the game's SDR picture clips: fire towards yellow and white. 0% keeps their hue."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX UI brightness", 80, 400, 10, 200, GameOptionKind.Slider, TxNits, false, true,
|
||||
"How bright the menus' and the HUD's white is with RenoDX's tonemapper. The scene's follows HDR paper white."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX color space", 0, 2, 1, 1, GameOptionKind.Choice, TxRdxSpace, false, true,
|
||||
"The colours the picture is taken to be in before HDR10's. Vanilla: the game's own matrix. BT.709: as the SDR picture. DCI-P3: more saturated."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX exposure", 0, 200, 5, 100, GameOptionKind.Slider, TxPercent, false, true,
|
||||
"The scene's brightness before RenoDX's tone mapping. 100% is the game's."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX highlights", 0, 100, 5, 50, GameOptionKind.Slider, TxRdxGrade, false, true,
|
||||
"RenoDX's colour grading: the bright parts of the scene. 50 is neutral."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX shadows", 0, 100, 5, 50, GameOptionKind.Slider, TxRdxGrade, false, true,
|
||||
"RenoDX's colour grading: the dark parts of the scene. 50 is neutral."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX contrast", 0, 100, 5, 50, GameOptionKind.Slider, TxRdxGrade, false, true,
|
||||
"RenoDX's colour grading: the scene's contrast. 50 is neutral."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX saturation", 0, 100, 5, 50, GameOptionKind.Slider, TxRdxGrade, false, true,
|
||||
"RenoDX's colour grading: the scene's saturation. 50 is neutral."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX highlight saturation", 0, 100, 1, 50, GameOptionKind.Slider, TxRdxGrade, false, true,
|
||||
"With RenoDRT: the strength of the colours of the brightest parts. 50 leaves it unchanged."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX blowout", 0, 100, 1, 0, GameOptionKind.Slider, TxRdxGrade, false, true,
|
||||
"With RenoDRT: turns the brightest parts towards white. 0 keeps their colour."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX flare", 0, 100, 1, 0, GameOptionKind.Slider, TxRdxGrade, false, true,
|
||||
"With RenoDRT: lifts the darkest parts as a little stray light would. 0 keeps black black."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX hue correction", 0, 100, 5, 100, GameOptionKind.Slider, TxPercent, false, true,
|
||||
"With RenoDRT: how much bright colours keep the hue they have before the tonemapper. 0% lets them shift as the curve takes them."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX color grading", 0, 100, 5, 100, GameOptionKind.Slider, TxPercent, false, true,
|
||||
"With RenoDRT: how much of the game's own colour grading the HDR picture keeps. 0% is the scene without it."),
|
||||
Row(GameOptionTab.Display, "RenoDX", "RenoDX bloom", 0, 100, 5, 50, GameOptionKind.Slider, TxRdxGrade, false, true,
|
||||
"How strong the glow around bright things is. 50 is the game's."),
|
||||
Row(GameOptionTab.Graphics, "Quality", "Quality preset", 0, 5, 1, 0, GameOptionKind.Choice, TxPreset, false, false,
|
||||
"Sets the scaling rows and memory limits for a GPU with that much memory. The Upscaler and Frame generation stay yours."),
|
||||
Row(GameOptionTab.Graphics, "Quality", "Render resolution", 0, 6, 1, 0, GameOptionKind.Choice, TxResolution, true, false,
|
||||
"The share of the output the 3D is drawn at; the Upscaler fills in the rest. Applies after a restart."),
|
||||
Row(GameOptionTab.Graphics, "Quality", "Texture detail", 0, 3, 1, 0, GameOptionKind.Choice, TxTexDetail, true, false,
|
||||
"How large the game's textures are kept in video memory. Automatic suits the graphics card; a Quality preset sets it for its card's size. Applies after a restart."),
|
||||
Row(GameOptionTab.Graphics, "Quality", "Texture filtering", 0, 4, 1, 0, GameOptionKind.Choice, TxAniso, false, false,
|
||||
"Anisotropic filtering: keeps ground, paths and walls sharp where they slope away from the camera. Game's is what the game asks for; 16x is the sharpest, at a small cost."),
|
||||
Row(GameOptionTab.Graphics, "Upscaling and edges", "Upscaler", 0, 6, 1, 0, GameOptionKind.Choice, TxUpscaler, false, false,
|
||||
"What scales the 3D up to the Output resolution."),
|
||||
Row(GameOptionTab.Graphics, "Upscaling and edges", "DLSS model", 0, 3, 1, 0, GameOptionKind.Choice, TxDlssModel, false, true,
|
||||
"Which of NVIDIA's DLSS networks draws the picture."),
|
||||
Row(GameOptionTab.Graphics, "Upscaling and edges", "Upscale before bloom", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, true, true,
|
||||
"With NVIDIA DLSS, DLAA or AMD FSR as the Upscaler: On, it works on the scene before the game's glow and tone mapping, so both are made from the sharpened scene. Off: on the finished picture, as before. Applies after a restart."),
|
||||
Row(GameOptionTab.Graphics, "Upscaling and edges", "Anti-aliasing", 0, 3, 1, 0, GameOptionKind.Choice, TxAa, false, true,
|
||||
"How the 3D's edges are smoothed before it is scaled up: by the game's own SMAA, not at all, by FXAA, or by SMAA at its Ultra preset. Changes at once."),
|
||||
Row(GameOptionTab.Graphics, "Upscaling and edges", "Sharpness", 0, 100, 10, 0, GameOptionKind.Slider, TxPercent, false, false,
|
||||
"Sharpens the picture as it goes to the window, with any filter. Too much shows halos around edges."),
|
||||
Row(GameOptionTab.Graphics, "Upscaling and edges", "Window scaling filter", 0, 3, 1, 0, GameOptionKind.Choice, TxFilter, false, false,
|
||||
"How the finished picture is scaled to the window, when its size differs from the Output resolution."),
|
||||
Row(GameOptionTab.Graphics, "Smoothness", "Frame generation", 0, 9, 1, 0, GameOptionKind.Choice, TxFramegen, false, true,
|
||||
"Makes frames between the game's own, for smoother motion, at a little input delay. Fast motion or camera cuts can show artifacts."),
|
||||
Row(GameOptionTab.Graphics, "Smoothness", "DLSS frame generation", 0, 3, 1, 0, GameOptionKind.Choice, TxDlssg, true, true,
|
||||
"NVIDIA RTX 40 and 50 cards: frames made between the game's own by NVIDIA DLSS, from the scene's depth and motion, with NVIDIA Reflex. The Frame generation row above is not used with it. Applies after a restart."),
|
||||
Row(GameOptionTab.Graphics, "Smoothness", "Frame pacing", 0, 1, 1, 1, GameOptionKind.Choice, TxOnoff, false, false,
|
||||
"When each frame is shown."),
|
||||
Row(GameOptionTab.Graphics, "Latency", "NVIDIA Reflex", 0, 2, 1, 2, GameOptionKind.Choice, TxReflex, false, false,
|
||||
"NVIDIA GPUs: each frame starts as late as it can, for less input delay. With DLSS frame generation it runs through NVIDIA Streamline; not used with the other frame generation."),
|
||||
Row(GameOptionTab.Graphics, "Latency", "AMD Anti-Lag 2", 0, 1, 1, 0, GameOptionKind.Choice, TxAntilag, false, false,
|
||||
"AMD GPUs: each frame starts as late as it can, for less input delay. Not used with frame generation."),
|
||||
Row(GameOptionTab.Graphics, "Advanced", "Handheld profile", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, true, false,
|
||||
"Runs the game as if the console were undocked. Applies after a restart."),
|
||||
Row(GameOptionTab.Graphics, "Advanced", "Robust buffers", 0, 2, 1, 1, GameOptionKind.Choice, TxRobust, true, false,
|
||||
"Bounds-checked buffer reads: a read past a buffer's end is dropped instead of stopping the GPU. Applies after a restart."),
|
||||
Row(GameOptionTab.Graphics, "Advanced", "Mesh shaders", 0, 1, 1, 0, GameOptionKind.Choice, TxMesh, true, false,
|
||||
"How the game's mesh-shader draws run. Try Compute fallback on an AMD card that shows glowing walls or loses the GPU. Applies after a restart."),
|
||||
Row(GameOptionTab.System, "Game", "Game speed", 0, 1, 1, 1, GameOptionKind.Choice, TxSpeed, false, false,
|
||||
"How the game keeps time when it runs below 60 fps."),
|
||||
Row(GameOptionTab.System, "Game", "Text speed", 0, 3, 1, 0, GameOptionKind.Choice, TxTextSpeed, false, false,
|
||||
"How fast the letters of dialogue and other messages appear."),
|
||||
Row(GameOptionTab.System, "Game", "Discord status", 0, 1, 1, 1, GameOptionKind.Choice, TxOnoff, false, true,
|
||||
"Shows \"Playing Triforce\" and the time played in your Discord status, while Discord runs on this PC."),
|
||||
Row(GameOptionTab.Audio, null, "Master volume", 0, 100, 5, 100, GameOptionKind.Slider, TxVolume, false, true,
|
||||
"How loud the game is, in percent of its own volume. The game's sounds and music keep their balance."),
|
||||
Row(GameOptionTab.Audio, null, "Menu sounds", 0, 100, 5, 80, GameOptionKind.Slider, TxMenuSounds, false, true,
|
||||
"How loud these options' own sounds are: the game's interface sounds, played from your game files as you move through the tabs and rows. Off is silent. The Master volume is over them too."),
|
||||
Row(GameOptionTab.Audio, null, "Audio output", 0, 2, 1, 0, GameOptionKind.Choice, TxAudioOutput, true, true,
|
||||
"The speakers the game mixes its sound for. Applies after a restart."),
|
||||
Row(GameOptionTab.Audio, null, "Microphone", 0, 18, 1, 1, GameOptionKind.Choice, TxMic, false, true,
|
||||
"What the ocarina hears when the game's microphone option is on (playing an instrument, or humming)."),
|
||||
Row(GameOptionTab.Controls, "Camera", "Camera speed", 25, 300, 5, 100, GameOptionKind.Slider, TxSens, true, true,
|
||||
"How fast the right stick turns the camera: times the game's own speed, at any Camera sensitivity of the game's Options. The mouse keeps its own sensitivity. Applies after a restart."),
|
||||
Row(GameOptionTab.Controls, "Camera", "Invert camera X", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, true,
|
||||
"Inverts horizontal look (left/right) on the right analog stick."),
|
||||
Row(GameOptionTab.Controls, "Camera", "Invert camera Y", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, true,
|
||||
"Inverts vertical look (up/down) on the right analog stick."),
|
||||
Row(GameOptionTab.Controls, "Camera", "Mouse camera", 0, 1, 1, 0, GameOptionKind.Choice, TxMousecam, false, true,
|
||||
"How the captured mouse turns the camera."),
|
||||
Row(GameOptionTab.Controls, "Camera", "Mouse sensitivity", 10, 500, 10, 100, GameOptionKind.Slider, TxSens, false, true,
|
||||
"How far the camera turns for a mouse movement, with either Mouse camera: at 1.00 native look turns 0.1 degree a count. The - and = keys change it in game too."),
|
||||
Row(GameOptionTab.Controls, "Camera", "Invert mouse vertical", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, true,
|
||||
"Swaps up and down for the mouse."),
|
||||
Row(GameOptionTab.Controls, "Sticks", "Stick dead zone", 0, 5, 1, 0, GameOptionKind.Choice, TxStickDeadZone, false, true,
|
||||
"How far a stick moves before the game sees it, on each axis. Lower for a precise stick, higher for one that drifts. The game's own dead zone still follows."),
|
||||
Row(GameOptionTab.Controls, "Sticks", "Left stick dead zone", -1, 50, 1, -1, GameOptionKind.Slider, TxOwnDeadZone, false, true,
|
||||
"The left stick's own dead zone, in percent of its travel on each axis, in place of Stick dead zone: a worn stick can have a larger one than the other. 0% cuts nothing; the game's own dead zone still follows."),
|
||||
Row(GameOptionTab.Controls, "Sticks", "Right stick dead zone", -1, 50, 1, -1, GameOptionKind.Slider, TxOwnDeadZone, false, true,
|
||||
"The right stick's own dead zone, in percent of its travel on each axis, in place of Stick dead zone: a worn stick can have a larger one than the other. 0% cuts nothing; the game's own dead zone still follows."),
|
||||
Row(GameOptionTab.Controls, "Movement", "Sprint button", 0, 2, 1, 0, GameOptionKind.Choice, TxSprint, false, true,
|
||||
"Link sprints from a button press, without rolling first. Left stick click: the game has no other use for it. B: sprints only while Link moves, and puts the weapon away as usual otherwise (with the game's Swap Jump Controls B is the jump: use the stick's click)."),
|
||||
Row(GameOptionTab.Controls, "Movement", "Sprint mode", 0, 1, 1, 0, GameOptionKind.Choice, TxSprintMode, false, true,
|
||||
"Toggle: a press starts the sprint and the next press, or stopping, ends it. Hold: Link sprints while the button is held."),
|
||||
Row(GameOptionTab.Controls, "Movement", "Walk key", 0, 4, 1, 0, GameOptionKind.Choice, TxWalkKey, false, true,
|
||||
"A key that makes Link walk on the keyboard: held with the movement keys, they push the left stick only as far as Walk scale. While it is chosen the key presses nothing else."),
|
||||
Row(GameOptionTab.Controls, "Movement", "Walk scale", 20, 90, 1, 51, GameOptionKind.Slider, TxSens, false, true,
|
||||
"How far the movement keys push the left stick while the Walk key is held: 1.00 would be all the way, lower walks slower. A controller's stick and the camera's keys are not changed."),
|
||||
Row(GameOptionTab.Controls, "Vibration", "Rumble strength", 0, 300, 25, 100, GameOptionKind.Slider, TxRumble, false, true,
|
||||
"How strongly the controller rumbles, in percent of the game's rumble. Off turns it off. Over 100% a rumble that would pass the motors' full strength stops there."),
|
||||
Row(GameOptionTab.Controls, "Vibration", "Vibration curve", 20, 150, 5, 100, GameOptionKind.Slider, TxSens, false, true,
|
||||
"Shapes the rumble of a controller's two motors. 1.00 is the game's. Lower lifts the many weak rumbles so they can be felt and hardly changes the strong ones; higher quiets them. A Switch controller's HD rumble is not changed by it."),
|
||||
Row(GameOptionTab.Controls, "Vibration", "Trigger vibration", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, true,
|
||||
"Xbox One and Series controllers: the motors in the triggers rumble too, with the lighter of the two motors. Controllers without them rumble as before."),
|
||||
Row(GameOptionTab.Controls, "Other", "Controller in background", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, false,
|
||||
"Whether the controller plays the game while another window has the focus."),
|
||||
Row(GameOptionTab.Controls, "Other", "Menu shortcut", 0, 1, 1, 0, GameOptionKind.Choice, TxMenuShortcut, false, true,
|
||||
"Which keys open and close these options from anywhere. F1 always does; F1 only leaves Insert free for an overlay."),
|
||||
Row(GameOptionTab.Controls, "Motion", "Motion controls", 0, 1, 1, 1, GameOptionKind.Choice, TxGyro, false, true,
|
||||
"Aims and looks with the controller's gyroscope where the game uses motion, as on the Switch. Works with Switch Pro controllers and pads in Switch mode, DualSense and DualShock 4. Shown beside it: whether the connected pad has one."),
|
||||
Row(GameOptionTab.Controls, "Motion", "Motion sensitivity X", 10, 600, 10, 100, GameOptionKind.Slider, TxPercent, false, true,
|
||||
"How far the aim moves left and right for a given turn of the controller. 100% is the console's own."),
|
||||
Row(GameOptionTab.Controls, "Motion", "Motion sensitivity Y", 10, 300, 10, 100, GameOptionKind.Slider, TxPercent, false, true,
|
||||
"How far the aim moves up and down for a given tilt of the controller. 100% is the console's own."),
|
||||
Row(GameOptionTab.Controls, "Motion", "Invert motion X", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, true,
|
||||
"Turns the motion aim's left and right around."),
|
||||
Row(GameOptionTab.Controls, "Motion", "Invert motion Y", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, true,
|
||||
"Turns the motion aim's up and down around."),
|
||||
Row(GameOptionTab.Controls, "Motion", "Motion deadzone", 0, 2, 1, 1, GameOptionKind.Choice, TxDeadzone, false, true,
|
||||
"How slow a turn counts as none, the console's three settings: Standard is its own. High steadies a pad that jitters when held still; Low keeps the smallest movements."),
|
||||
Row(GameOptionTab.Controls, "Controls", "Button prompts", 0, 6, 1, 0, GameOptionKind.Choice, TxPrompts, true, true,
|
||||
"The button icons the game shows, in its texts and menus: those of this controller, or the keyboard's and the mouse's, for the buttons or keys your controls put each action on."),
|
||||
};
|
||||
|
||||
static readonly Dictionary<string, GameOptionRow> byKey = All.ToDictionary(r => r.Key, StringComparer.Ordinal);
|
||||
static readonly Dictionary<string, GameOptionRow> byName = All.ToDictionary(r => r.Name, StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The row of a triforce_options.ini key (exact, as the game compares them), null for any other key.</summary>
|
||||
public static GameOptionRow? ByKey(string key) => byKey.GetValueOrDefault(key);
|
||||
/// <summary>The row of a key; KeyNotFoundException for a key no row has.</summary>
|
||||
public static GameOptionRow Get(string key) => ByKey(key) ?? throw new KeyNotFoundException("no Options row has the key " + key);
|
||||
/// <summary>The row by its name as the menu shows it.</summary>
|
||||
public static GameOptionRow? ByName(string name) => byName.GetValueOrDefault(name);
|
||||
/// <summary>A tab's rows, in order.</summary>
|
||||
public static IReadOnlyList<GameOptionRow> RowsOf(GameOptionTab tab) => All.Where(r => r.Tab == tab).ToList();
|
||||
/// <summary>A tab's sections that have rows here, in order (Audio has none: its rows' Section is null).</summary>
|
||||
public static IReadOnlyList<string> Sections(GameOptionTab tab) => RowsOf(tab).Select(r => r.Section).OfType<string>().Distinct().ToList();
|
||||
|
||||
// ---- the keys of the file that are not rows here ----
|
||||
|
||||
/// <summary>The file's keys the launcher knowingly leaves as they are (GameOptionsFile keeps their lines, in order), and why.
|
||||
/// Besides these: every pad_* and key_* line (KeptPrefixes).</summary>
|
||||
public static readonly IReadOnlyDictionary<string, string> KeptKeys = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
[VersionKey] = "the file's format: the rules the game reads an older file by (GameOptionsFile.Save writes 7 when it brings an older file up to date)",
|
||||
[MicDeviceKey] = "the Microphone row's device, by its name: the game's to choose from the devices it lists",
|
||||
["layout_preset"] = "the Controls page's Layout preset: choosing one in the game rebinds the pad_ lines, which a changed value alone would not do",
|
||||
["debug_tools"] = "the Debug tab (not ported)",
|
||||
["descriptor_reuse"] = "the Debug tab's Developer rows (not ported)",
|
||||
["fast_pipeline_link"] = "the Debug tab's Developer rows (not ported)",
|
||||
["sampler_cache"] = "the Debug tab's Developer rows (not ported)",
|
||||
["lazy_write-back"] = "the Debug tab's Developer rows (not ported)",
|
||||
["replay_helper_threads"] = "the Debug tab's Developer rows (not ported)",
|
||||
["tail_early"] = "the Debug tab's Start next frame early (not ported)",
|
||||
["opaque_textures_as_bc1"] = "the Debug tab's Developer rows (not ported)",
|
||||
["menu_size"] = "the old Menu size row, gone from the menu (the game's menus have one size): the game keeps the line and reads nothing from it",
|
||||
["dynamic_resolution"] = "the Render resolution's old key: read once by the game where the file has no resolution line",
|
||||
["debug_tab"] = "an old line (Alt+G's Debug tab): the game drops it at its next save",
|
||||
["rivatuner_limit"] = "an old test builds' line: the game drops it at its next save",
|
||||
["discord_app_id"] = "the Discord status's application, for a test application (host/discord_rpc.c): no row",
|
||||
};
|
||||
/// <summary>The binding lines of the Controls page's grid: pad_<button>=<input> and key_<button>=<key>,<key>.</summary>
|
||||
public static readonly IReadOnlyList<string> KeptPrefixes = new[] { "pad_", "key_" };
|
||||
/// <summary>A key that is not a row here but is known (KeptKeys, KeptPrefixes): kept in the file as it is.</summary>
|
||||
public static bool IsKept(string key) => KeptKeys.ContainsKey(key) || KeptPrefixes.Any(p => key.StartsWith(p, StringComparison.Ordinal));
|
||||
|
||||
// ---- the Quality preset ----
|
||||
|
||||
/// <summary>What each Quality preset sets (vk_menu.cpp apply_preset), in the menu's own words (hn_preset).</summary>
|
||||
public static readonly IReadOnlyList<string> PresetSummaries = new[]
|
||||
{
|
||||
"Each row as you set it. Changing most rows yourself comes back to Custom.",
|
||||
"Resolution 50% (with DLSS its nearest mode), Lanczos, Sharpness 30%, Handheld profile.",
|
||||
"Resolution 75% (with DLSS its nearest mode), Lanczos, Sharpness 30%, Handheld profile.",
|
||||
"Resolution 100% (with DLSS its nearest mode), Catmull-Rom, Sharpness 30%.",
|
||||
"Resolution 100% (with DLSS its nearest mode), Lanczos, Sharpness 40%.",
|
||||
"Resolution 100% (with DLSS its nearest mode), Lanczos, Sharpness 50%.",
|
||||
};
|
||||
|
||||
/// <summary>The rows a Quality preset sets and their values (apply_preset): the Render resolution (then moved to the
|
||||
/// Upscaler's nearest step: GameOptionsFile.Set does that), the Window scaling filter, Sharpness, Frame pacing, Game speed,
|
||||
/// the Handheld profile and the Texture detail. Custom (0) sets nothing. The Upscaler and Frame generation stay the
|
||||
/// player's. (The game also sets its memory budgets from the preset; they are not kept in the file.)</summary>
|
||||
public static IReadOnlyDictionary<string, int> PresetValues(int preset)
|
||||
{
|
||||
var (res, filter, sharp, handheld) = preset switch
|
||||
{
|
||||
1 => (4, 2, 30, 1),
|
||||
2 => (2, 2, 30, 1),
|
||||
3 => (1, 1, 30, 0),
|
||||
4 => (1, 2, 40, 0),
|
||||
5 => (1, 2, 50, 0),
|
||||
_ => (-1, 0, 0, 0),
|
||||
};
|
||||
if (res < 0) return new Dictionary<string, int>();
|
||||
int[] detail = { 0, 3, 2, 1, 1, 1 };
|
||||
return new Dictionary<string, int>(StringComparer.Ordinal)
|
||||
{
|
||||
[ResolutionKey] = res, ["upscaling"] = filter, ["sharpness"] = sharp, ["frame_pacing"] = 1, ["game_speed"] = 1,
|
||||
[HandheldKey] = handheld, ["texture_detail"] = detail[preset],
|
||||
};
|
||||
}
|
||||
}
|
||||
130
launcher/Logic/Gpu.cs
Normal file
130
launcher/Logic/Gpu.cs
Normal file
@@ -0,0 +1,130 @@
|
||||
// The graphics cards of this PC (read only): for NVIDIA DLSS (offered on NVIDIA cards only, DESIGN 6) and the shader step's
|
||||
// honest time (DESIGN 6 Build: "About 13 min on an RTX 4070"; "1 to 2 hours on an RX 6800 XT").
|
||||
using System.Runtime.Versioning;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
public enum GpuVendor { Nvidia, Amd, Intel, Other }
|
||||
|
||||
public sealed record GpuInfo(GpuVendor Vendor, string Name);
|
||||
|
||||
public static class Gpus
|
||||
{
|
||||
static GpuVendor VendorOf(string text, uint? id = null)
|
||||
{
|
||||
if (id == 0x10DE || text.Contains("NVIDIA", StringComparison.OrdinalIgnoreCase)) return GpuVendor.Nvidia;
|
||||
if (id == 0x1002 || text.Contains("AMD", StringComparison.OrdinalIgnoreCase) || text.Contains("Radeon", StringComparison.OrdinalIgnoreCase) ||
|
||||
text.Contains("Advanced Micro Devices", StringComparison.OrdinalIgnoreCase)) return GpuVendor.Amd;
|
||||
if (id == 0x8086 || text.Contains("Intel", StringComparison.OrdinalIgnoreCase)) return GpuVendor.Intel;
|
||||
return GpuVendor.Other;
|
||||
}
|
||||
|
||||
/// <summary>The display adapters: Windows from the display class's driver keys (HKLM, read only), Linux from /sys/class/drm.</summary>
|
||||
public static IReadOnlyList<GpuInfo> List()
|
||||
{
|
||||
try { return OperatingSystem.IsWindows() ? Windows() : Linux(); } catch (Exception) { return Array.Empty<GpuInfo>(); }
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
static IReadOnlyList<GpuInfo> Windows()
|
||||
{
|
||||
var found = new List<GpuInfo>();
|
||||
using var cls = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}", false);
|
||||
if (cls == null) return found;
|
||||
foreach (var sub in cls.GetSubKeyNames())
|
||||
{
|
||||
if (sub.Length != 4 || !sub.All(char.IsDigit)) continue;
|
||||
try
|
||||
{
|
||||
using var k = cls.OpenSubKey(sub, false);
|
||||
var name = k?.GetValue("DriverDesc") as string;
|
||||
if (string.IsNullOrWhiteSpace(name)) continue;
|
||||
var provider = k!.GetValue("ProviderName") as string ?? "";
|
||||
var v = VendorOf(name + " " + provider);
|
||||
if (v == GpuVendor.Other && (name.Contains("Basic", StringComparison.OrdinalIgnoreCase) || name.Contains("Remote", StringComparison.OrdinalIgnoreCase))) continue;
|
||||
if (found.All(g => g.Name != name)) found.Add(new GpuInfo(v, name));
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
static IReadOnlyList<GpuInfo> Linux()
|
||||
{
|
||||
var found = new List<GpuInfo>();
|
||||
if (!Directory.Exists("/sys/class/drm")) return found;
|
||||
foreach (var card in Directory.GetDirectories("/sys/class/drm", "card*"))
|
||||
{
|
||||
if (Path.GetFileName(card).Contains('-')) continue; // (card0-DP-1: a connector)
|
||||
try
|
||||
{
|
||||
var vendor = File.ReadAllText(Path.Combine(card, "device", "vendor")).Trim();
|
||||
var device = File.Exists(Path.Combine(card, "device", "device")) ? File.ReadAllText(Path.Combine(card, "device", "device")).Trim() : "";
|
||||
var id = Convert.ToUInt32(vendor.Replace("0x", ""), 16);
|
||||
var v = VendorOf("", id);
|
||||
found.Add(new GpuInfo(v, v + " " + device));
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
if (found.All(g => g.Vendor != GpuVendor.Nvidia) && File.Exists("/proc/driver/nvidia/version")) found.Add(new GpuInfo(GpuVendor.Nvidia, "NVIDIA"));
|
||||
return found;
|
||||
}
|
||||
|
||||
/// <summary>The card that most likely runs the game: an NVIDIA or AMD one before an integrated Intel one.</summary>
|
||||
public static GpuInfo? Main()
|
||||
{
|
||||
var all = List();
|
||||
return all.FirstOrDefault(g => g.Vendor == GpuVendor.Nvidia) ?? all.FirstOrDefault(g => g.Vendor == GpuVendor.Amd) ?? all.FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>Is NVIDIA DLSS worth offering here: an NVIDIA card.</summary>
|
||||
public static bool HasNvidia() => List().Any(g => g.Vendor == GpuVendor.Nvidia);
|
||||
}
|
||||
|
||||
/// <summary>NVIDIA DLSS in the game that is built: NVIDIA's files come under NVIDIA's own licences, so the choice holds only once
|
||||
/// they are accepted (old Shell.cs:246-260, 1017-1029; hookshot_builder.py DLSS_LICENSE). Kept as Dlss=1: an update builds with
|
||||
/// it again; an update of a folder built with DLSS keeps it whatever the setting says.</summary>
|
||||
public sealed class Dlss
|
||||
{
|
||||
readonly TriforceContext ctx;
|
||||
public Dlss(TriforceContext ctx) { this.ctx = ctx; }
|
||||
|
||||
/// <summary>Show the DLSS row at all (an NVIDIA card).</summary>
|
||||
public bool Available => Gpus.HasNvidia();
|
||||
|
||||
public bool Chosen => ctx.Settings.Dlss;
|
||||
|
||||
/// <summary>The licence question, in the old words (11-15: the tick brings DLSS frame generation too: NVIDIA's Streamline (MIT)
|
||||
/// and nvngx_dlssg.dll, under the NVIDIA RTX SDKs License as DLSS itself).</summary>
|
||||
public string LicenseText => ctx.IsWindows
|
||||
? "NVIDIA DLSS and DLSS frame generation are NVIDIA's, under NVIDIA's own licenses (github.com/NVIDIA/DLSS, LICENSE.txt; " +
|
||||
"github.com/NVIDIA-RTX/Streamline, license.txt). Their files are downloaded to this PC; a game folder built with them " +
|
||||
"must not be shared. Do you accept NVIDIA's licenses?"
|
||||
: "NVIDIA DLSS is NVIDIA's, not Triforce's. With it ticked, the build downloads NVIDIA's DLSS SDK (release v310.9.16) from " +
|
||||
"github.com/NVIDIA/DLSS, under NVIDIA's own license, the NVIDIA RTX SDKs license:\n\n" +
|
||||
"https://github.com/NVIDIA/DLSS/blob/9981c6350dc58c0ce21f024fd65e31e851c31689/LICENSE.txt\n\n" +
|
||||
"Its files stay on this PC (in the builder's ngx-sdk folder, and libnvidia-ngx-dlss.so in the game folder's ngx folder). " +
|
||||
"Triforce never includes or shares them: never share a game folder built with them.\n\n" +
|
||||
"Do you accept NVIDIA's license?";
|
||||
|
||||
public const string AcceptLabel = "I accept";
|
||||
|
||||
/// <summary>"I accept": DLSS on, kept.</summary>
|
||||
public void Accept() => ctx.Settings.Dlss = true;
|
||||
/// <summary>The box un-ticked.</summary>
|
||||
public void TurnOff() => ctx.Settings.Dlss = false;
|
||||
|
||||
/// <summary>Does a build use DLSS: the setting, or (an update) a folder built with it, which then stores the choice again
|
||||
/// (#bug-tracker 11-18 "Update & merge removes NVIDIA DLSS").</summary>
|
||||
public bool ForBuild(string? updateFolder)
|
||||
{
|
||||
if (ctx.Settings.Dlss) return true;
|
||||
if (updateFolder != null && new Game(ctx).HasDlss(updateFolder))
|
||||
{
|
||||
ctx.Settings.Dlss = true;
|
||||
ctx.Log.Write("update: the folder was built with NVIDIA DLSS: updated with it");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
199
launcher/Logic/Guard/Download.cs
Normal file
199
launcher/Logic/Guard/Download.cs
Normal file
@@ -0,0 +1,199 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>How far a download is: 0..1 (0 while the size is unknown), the bytes there, the whole size (0 unknown).</summary>
|
||||
public readonly record struct DownloadProgress(double Fraction, long Bytes, long Total);
|
||||
|
||||
/// <summary>A file fetched over HTTP into place through <file>.part, and checked before it is used (old Guard.cs Download).
|
||||
///
|
||||
/// A download that was cut off (the connection, Cancel, the launcher closed) leaves its part file, and the next one goes on from
|
||||
/// it with a Range request where the server answers those; a server that does not sends the whole file, and the part is written
|
||||
/// over. A part is gone on from only as a part of the same file: <file>.part.of beside it names the address and the size it
|
||||
/// was begun for and the server's mark for the file it sent (its ETag, else its date), which goes back with the request
|
||||
/// (If-Range), so a file published again under the same address comes whole and is never joined to the beginning of the one
|
||||
/// before. A part without that note, or from a server that marks its files in neither way, is fetched anew.
|
||||
///
|
||||
/// The file gets its name only once it has the size the release lists (else the one the server names), and a server that names
|
||||
/// another size than the release's is not believed before its first byte.</summary>
|
||||
public sealed class Downloader
|
||||
{
|
||||
readonly TriforceContext ctx;
|
||||
public Downloader(TriforceContext ctx) { this.ctx = ctx; }
|
||||
|
||||
/// <summary>How long the server may send nothing before the download is given up (its part stays to be gone on from). A read
|
||||
/// that waits on the network hears no cancellation: it is left waiting and its connection closed behind it, for Cancel too.</summary>
|
||||
public TimeSpan Stall { get; set; } = TimeSpan.FromSeconds(60);
|
||||
|
||||
static void Remove(string file)
|
||||
{
|
||||
try { File.Delete(file); } catch (Exception) { }
|
||||
}
|
||||
|
||||
static string Mb(long bytes) => (bytes >> 20).ToString();
|
||||
|
||||
/// <summary>The server's mark for the file it sends, to hand back with If-Range: a strong ETag, else the date it was last changed.</summary>
|
||||
static string Mark(HttpResponseMessage response) =>
|
||||
response.Headers.ETag is { IsWeak: false } tag ? tag.ToString()
|
||||
: response.Content.Headers.LastModified is { } changed ? changed.UtcDateTime.ToString("r") : "";
|
||||
|
||||
/// <summary>url to file, with progress. size is what the release lists for it, 0 when it lists none.</summary>
|
||||
public async Task ToFileAsync(HttpClient http, string url, string file, long size, Action<DownloadProgress>? progress, CancellationToken token)
|
||||
{
|
||||
var name = Path.GetFileName(file);
|
||||
var part = file + ".part";
|
||||
var note = part + ".of";
|
||||
long have = 0;
|
||||
RangeConditionHeaderValue? same = null;
|
||||
void Forget() { Remove(part); Remove(note); }
|
||||
void Say(double f, long b, long t) => progress?.Invoke(new DownloadProgress(f, b, t));
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(file))!);
|
||||
if (File.Exists(part))
|
||||
{
|
||||
// (what the part is a part of: only the same address, size and mark are gone on from, and never a part as long as the file)
|
||||
string[] of = { };
|
||||
try { of = File.ReadAllLines(note); } catch (Exception) { }
|
||||
var length = new FileInfo(part).Length;
|
||||
if (of.Length >= 3 && of[0] == url && of[1] == size.ToString() && RangeConditionHeaderValue.TryParse(of[2], out same) && length > 0 && (size <= 0 || length < size))
|
||||
have = length;
|
||||
else Forget();
|
||||
}
|
||||
|
||||
using var stall = new CancellationTokenSource();
|
||||
using var either = CancellationTokenSource.CreateLinkedTokenSource(token, stall.Token);
|
||||
for (var again = false; ; again = true)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
if (have > 0)
|
||||
{
|
||||
request.Headers.Range = new RangeHeaderValue(have, null);
|
||||
request.Headers.IfRange = same;
|
||||
}
|
||||
stall.CancelAfter(Stall);
|
||||
HttpResponseMessage response;
|
||||
try { response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, either.Token).ConfigureAwait(false); }
|
||||
catch (OperationCanceledException) when (!token.IsCancellationRequested && stall.IsCancellationRequested)
|
||||
{
|
||||
throw new CutOffException("The server did not answer for " + (int)Stall.TotalSeconds + " seconds about " + name + ". Try again.");
|
||||
}
|
||||
var left = false; // (the answer was left with a read still waiting on it)
|
||||
try
|
||||
{
|
||||
var range = response.StatusCode == HttpStatusCode.PartialContent ? response.Content.Headers.ContentRange : null;
|
||||
// (416: the part is no part of what the server has now. A range other than the one asked for: not to be joined on.
|
||||
// Either way the whole file is asked for, once)
|
||||
if (have > 0 && !again && (response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable ||
|
||||
response.StatusCode == HttpStatusCode.PartialContent && !(range is { HasRange: true } && range.From == have)))
|
||||
{
|
||||
Forget();
|
||||
have = 0;
|
||||
continue;
|
||||
}
|
||||
response.EnsureSuccessStatusCode();
|
||||
if (response.StatusCode == HttpStatusCode.PartialContent && (have == 0 || !(range is { HasRange: true } && range.From == have)))
|
||||
throw new IOException("The server sent a piece of " + name + " that was not asked for.");
|
||||
// (200 to a request for the rest: the server knows no ranges, or the file is another one now. The whole file comes)
|
||||
if (response.StatusCode != HttpStatusCode.PartialContent) have = 0;
|
||||
|
||||
// the whole file's size: the release's, which the server must not contradict; else the server's
|
||||
var told = have > 0 ? range!.Length ?? have + response.Content.Headers.ContentLength : response.Content.Headers.ContentLength;
|
||||
if (size > 0 && told is { } other && other != size)
|
||||
{
|
||||
Forget();
|
||||
throw new IOException("The server offers " + other + " bytes as " + name + ", and the release lists " + size + ". Nothing was downloaded.");
|
||||
}
|
||||
var total = size > 0 ? size : told ?? 0;
|
||||
if (total > 0 && ctx.SpaceProblem(name, total - have, file) is { } none) throw new NoRoomException(none);
|
||||
if (have == 0)
|
||||
{
|
||||
Remove(part);
|
||||
try { File.WriteAllLines(note, new[] { url, size.ToString(), Mark(response) }); } catch (Exception) { }
|
||||
}
|
||||
Say(total > 0 ? Math.Min(1.0, (double)have / total) : 0, have, total);
|
||||
|
||||
var from = await response.Content.ReadAsStreamAsync(either.Token).ConfigureAwait(false);
|
||||
var gone = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var tooMuch = false;
|
||||
using (var to = new FileStream(part, have > 0 ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.None))
|
||||
using (either.Token.Register(() => gone.TrySetResult(true)))
|
||||
{
|
||||
var buffer = new byte[1 << 20];
|
||||
var shown = DateTime.MinValue;
|
||||
try
|
||||
{
|
||||
for (;;)
|
||||
{
|
||||
stall.CancelAfter(Stall);
|
||||
var read = from.ReadAsync(buffer, 0, buffer.Length, either.Token);
|
||||
if (await Task.WhenAny(read, gone.Task).ConfigureAwait(false) != read)
|
||||
{
|
||||
// (Cancel, or nothing came: the read is left where it waits, whatever becomes of it)
|
||||
left = true;
|
||||
_ = read.ContinueWith(t => t.Exception, TaskContinuationOptions.OnlyOnFaulted);
|
||||
throw new OperationCanceledException();
|
||||
}
|
||||
var n = await read.ConfigureAwait(false);
|
||||
stall.CancelAfter(Timeout.InfiniteTimeSpan);
|
||||
if (n <= 0) break;
|
||||
await to.WriteAsync(buffer.AsMemory(0, n), CancellationToken.None).ConfigureAwait(false);
|
||||
have += n;
|
||||
// (a server that sends more than the file would fill the disk)
|
||||
if (total > 0 && have > total) { tooMuch = true; break; }
|
||||
if (DateTime.UtcNow - shown > TimeSpan.FromMilliseconds(150))
|
||||
{
|
||||
shown = DateTime.UtcNow;
|
||||
Say(total > 0 ? Math.Min(1.0, (double)have / total) : 0, have, total);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (token.IsCancellationRequested) throw new OperationCanceledException(token);
|
||||
var of = total > 0 ? " of " + Mb(total) : "";
|
||||
if (stall.IsCancellationRequested)
|
||||
throw new CutOffException("The download of " + name + " stopped after " + Mb(have) + of + " MB: nothing more came for " + (int)Stall.TotalSeconds +
|
||||
" seconds. Try again: it goes on from there.");
|
||||
if (ctx.Platform.IsDiskFull(e)) throw;
|
||||
throw new CutOffException("The download of " + name + " was cut off after " + Mb(have) + of + " MB. Try again: it goes on from there.", e);
|
||||
}
|
||||
}
|
||||
if (tooMuch)
|
||||
{
|
||||
Forget();
|
||||
throw new IOException("The server sent more than the " + total + " bytes of " + name + ". Nothing of it was kept.");
|
||||
}
|
||||
if (total > 0 && have < total)
|
||||
throw new CutOffException("The download of " + name + " ended early, after " + Mb(have) + " of " + Mb(total) + " MB. Try again: it goes on from there.");
|
||||
break;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// (closing an answer can wait for the network as its read did: one that was left is closed where nobody waits for that)
|
||||
if (left) _ = Task.Run(() => { try { response.Dispose(); } catch (Exception) { } });
|
||||
else response.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// (before it is used: what is on the disk is what was counted)
|
||||
var there = new FileInfo(part).Length;
|
||||
if (there != have)
|
||||
{
|
||||
Forget();
|
||||
throw new IOException(name + " is " + there + " bytes on the disk where " + have + " were downloaded. Nothing of it was kept.");
|
||||
}
|
||||
if (File.Exists(file)) File.Delete(file);
|
||||
File.Move(part, file);
|
||||
Remove(note);
|
||||
Say(1, have, have);
|
||||
}
|
||||
|
||||
/// <summary>The HttpClient every release request goes through: no overall timeout (a 300 MB download takes what it takes; the
|
||||
/// release check has its own 20 s), the launcher's User-Agent (old Shell.cs Http).</summary>
|
||||
public static HttpClient CreateHttp()
|
||||
{
|
||||
var http = new HttpClient { Timeout = Timeout.InfiniteTimeSpan };
|
||||
http.DefaultRequestHeaders.UserAgent.ParseAdd(BuildInfo.UserAgent);
|
||||
return http;
|
||||
}
|
||||
}
|
||||
328
launcher/Logic/Guard/Instance.cs
Normal file
328
launcher/Logic/Guard/Instance.cs
Normal file
@@ -0,0 +1,328 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Net.Sockets;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>One launcher at a time for an install (old Guard.cs Instance). Two of them on one folder each downloaded the tools into
|
||||
/// the same files, unpacked them over each other and built into the same game folder. The first one holds a named mutex for as
|
||||
/// long as it runs; Windows lets go of it when the process ends, however it ends. A second start for the same folder asks the
|
||||
/// first to come to the front (a named event the first one waits on) and ends.
|
||||
///
|
||||
/// The names are the old Setup's exactly (research/02 2.6), so an old Setup started from a stale download defers to the new
|
||||
/// launcher and the other way round: Local\TriforceSetup-<FNV-1a 64 of the folder (and "|" test root), 16 hex>-<the folder's last
|
||||
/// 60 characters, each one that is not a letter or digit as ->; the event "<name>-show" brings the holder forward, and
|
||||
/// "<name>-up" is the handover's sign (Handover).
|
||||
///
|
||||
/// A mutex belongs to the thread that took it: here one thread of its own takes it, holds it and lets go of it, so the
|
||||
/// launcher's async code may Release from any thread (the old Setup's Release on another thread only closed the handle).
|
||||
/// Linux: a lock file (flock through FileShare.None) in $XDG_RUNTIME_DIR, and a unix socket for "come forward".</summary>
|
||||
public sealed class InstanceLock : IDisposable
|
||||
{
|
||||
/// <summary>One spelling for a folder, however it was typed.</summary>
|
||||
static string Same(string path)
|
||||
{
|
||||
try { path = Path.GetFullPath(path); } catch (Exception) { }
|
||||
return path.TrimEnd('\\', '/').ToUpperInvariant();
|
||||
}
|
||||
|
||||
/// <summary>FNV-1a 64 over the UTF-16 code units of a text (offset 14695981039346656037, prime 1099511628211).</summary>
|
||||
public static ulong Fnv1a64(string text)
|
||||
{
|
||||
var h = 14695981039346656037UL;
|
||||
foreach (var c in text) { h ^= c; h *= 1099511628211UL; }
|
||||
return h;
|
||||
}
|
||||
|
||||
/// <summary>The lock's name for a folder: a number made from the whole path (and the test folder's), then the end of the path
|
||||
/// for whoever looks at it. (Local\: one user's session. An install is one user's, HKCU and %LOCALAPPDATA%)</summary>
|
||||
public static string Name(string folder, string? testRoot)
|
||||
{
|
||||
var text = Same(folder) + (testRoot != null ? "|" + Same(testRoot) : "");
|
||||
var h = Fnv1a64(text);
|
||||
var tail = new string(Same(folder).Select(c => char.IsLetterOrDigit(c) ? c : '-').ToArray());
|
||||
return @"Local\TriforceSetup-" + h.ToString("x16") + "-" + (tail.Length > 60 ? tail.Substring(tail.Length - 60) : tail);
|
||||
}
|
||||
|
||||
/// <summary>The handover's sign: "<name>-up" (Handover).</summary>
|
||||
public static string UpName(string folder, string? testRoot) => Name(folder, testRoot) + "-up";
|
||||
public static string ShowName(string folder, string? testRoot) => Name(folder, testRoot) + "-show";
|
||||
|
||||
readonly string folder;
|
||||
readonly string? testRoot;
|
||||
// (Windows: the thread that owns the mutex, and what it is asked to do)
|
||||
BlockingCollection<Action>? asks;
|
||||
Thread? owner;
|
||||
Mutex? held;
|
||||
EventWaitHandle? call;
|
||||
ManualResetEvent? quit;
|
||||
Thread? waiting;
|
||||
Action? come;
|
||||
// (Linux)
|
||||
FileStream? lockFile;
|
||||
Socket? listener;
|
||||
|
||||
InstanceLock(string folder, string? testRoot) { this.folder = folder; this.testRoot = testRoot; }
|
||||
|
||||
public bool Held => held != null || lockFile != null;
|
||||
|
||||
/// <summary>The lock of this folder, or null when another launcher holds it. Where no lock can be made at all nobody is
|
||||
/// refused: the launcher must still start there (a lock that holds nothing is returned).</summary>
|
||||
public static InstanceLock? TryTake(string folder, string? testRoot)
|
||||
{
|
||||
var l = new InstanceLock(folder, testRoot);
|
||||
return l.Take() ? l : null;
|
||||
}
|
||||
|
||||
bool Take()
|
||||
{
|
||||
if (Held) return true;
|
||||
if (!OperatingSystem.IsWindows()) return TakeFile();
|
||||
asks ??= StartOwner();
|
||||
var done = new TaskCompletionSource<bool>();
|
||||
asks.Add(() => done.SetResult(TakeMutex()));
|
||||
return done.Task.GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
BlockingCollection<Action> StartOwner()
|
||||
{
|
||||
var q = new BlockingCollection<Action>();
|
||||
owner = new Thread(() => { foreach (var a in q.GetConsumingEnumerable()) a(); }) { IsBackground = true, Name = "Triforce instance lock" };
|
||||
owner.Start();
|
||||
return q;
|
||||
}
|
||||
|
||||
bool TakeMutex() // (on the owner thread)
|
||||
{
|
||||
var name = Name(folder, testRoot);
|
||||
Mutex m;
|
||||
try { m = new Mutex(false, name); }
|
||||
catch (UnauthorizedAccessException) { return false; } // (it is there, and belongs to a launcher run as administrator)
|
||||
catch (Exception) { return true; }
|
||||
try
|
||||
{
|
||||
if (!m.WaitOne(0)) { m.Dispose(); return false; }
|
||||
}
|
||||
catch (AbandonedMutexException) { } // (its holder ended without letting go: Windows hands it on, and it is ours)
|
||||
catch (Exception) { m.Dispose(); return true; }
|
||||
held = m;
|
||||
try
|
||||
{
|
||||
call = new EventWaitHandle(false, EventResetMode.AutoReset, name + "-show");
|
||||
call.Reset(); // (a call meant for the launcher before this one)
|
||||
}
|
||||
catch (Exception) { call = null; }
|
||||
if (come != null) Wait();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The lock again after Release (a launcher that let go of it for its successor, which then did not start).</summary>
|
||||
public bool TakeAgain() => Take();
|
||||
|
||||
/// <summary>What the holder does when a second launcher is started: called on a thread of its own, each time.</summary>
|
||||
public void Listen(Action onCall)
|
||||
{
|
||||
come = onCall;
|
||||
if (held != null || lockFile != null) Wait();
|
||||
}
|
||||
|
||||
void Wait()
|
||||
{
|
||||
if (come == null || waiting != null) return;
|
||||
var act = come;
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
if (call == null) return;
|
||||
var (c, q) = (call, quit = new ManualResetEvent(false));
|
||||
waiting = new Thread(() =>
|
||||
{
|
||||
try { while (WaitHandle.WaitAny(new WaitHandle[] { q, c }) == 1) act(); }
|
||||
catch (Exception) { }
|
||||
}) { IsBackground = true, Name = "Triforce come forward" };
|
||||
waiting.Start();
|
||||
return;
|
||||
}
|
||||
var l = listener;
|
||||
if (l == null) return;
|
||||
waiting = new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
for (;;)
|
||||
{
|
||||
using var s = l.Accept();
|
||||
act();
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
}) { IsBackground = true, Name = "Triforce come forward" };
|
||||
waiting.Start();
|
||||
}
|
||||
|
||||
/// <summary>Lets go of the folder: before the launcher that takes this one's place is started, and when the window has closed.</summary>
|
||||
public void Release()
|
||||
{
|
||||
try { quit?.Set(); waiting?.Join(2000); } catch (Exception) { }
|
||||
try { listener?.Dispose(); } catch (Exception) { }
|
||||
listener = null;
|
||||
waiting = null;
|
||||
quit = null;
|
||||
try { call?.Dispose(); } catch (Exception) { }
|
||||
call = null;
|
||||
if (lockFile != null)
|
||||
{
|
||||
try { lockFile.Dispose(); } catch (Exception) { }
|
||||
lockFile = null;
|
||||
try { File.Delete(SocketPath(folder, testRoot)); } catch (Exception) { }
|
||||
}
|
||||
if (held == null || asks == null) return;
|
||||
var done = new TaskCompletionSource();
|
||||
asks.Add(() =>
|
||||
{
|
||||
try { held?.ReleaseMutex(); } catch (Exception) { }
|
||||
held?.Dispose();
|
||||
held = null;
|
||||
done.SetResult();
|
||||
});
|
||||
done.Task.Wait(5000);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Release();
|
||||
asks?.CompleteAdding();
|
||||
}
|
||||
|
||||
/// <summary>A second launcher asks the one that holds the folder to come to the front. False when there is nobody to ask (yet).</summary>
|
||||
public static bool CallForward(string folder, string? testRoot)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
try
|
||||
{
|
||||
using var s = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
|
||||
s.Connect(new UnixDomainSocketEndPoint(SocketPath(folder, testRoot)));
|
||||
return true;
|
||||
}
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
try
|
||||
{
|
||||
if (!EventWaitHandle.TryOpenExisting(ShowName(folder, testRoot), out var c)) return false;
|
||||
using (c)
|
||||
{
|
||||
// (Windows lets only the program in front hand the front on: this one, just started by the player, may)
|
||||
try { AllowSetForegroundWindow(-1); } catch (Exception) { }
|
||||
return c.Set();
|
||||
}
|
||||
}
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
static extern bool AllowSetForegroundWindow(int process);
|
||||
|
||||
// ---- Linux ----
|
||||
|
||||
static string RuntimeDir => Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR") is { Length: > 0 } r && Directory.Exists(r) ? r : Path.GetTempPath();
|
||||
static string FileStem(string folder, string? testRoot) => "triforce-" + Fnv1a64(Same(folder) + (testRoot != null ? "|" + Same(testRoot) : "")).ToString("x16");
|
||||
static string LockPath(string folder, string? testRoot) => Path.Combine(RuntimeDir, FileStem(folder, testRoot) + ".lock");
|
||||
// (a unix socket's path is at most 108 bytes: the hash alone names it)
|
||||
static string SocketPath(string folder, string? testRoot) => Path.Combine(RuntimeDir, FileStem(folder, testRoot) + ".sock");
|
||||
|
||||
bool TakeFile()
|
||||
{
|
||||
try { lockFile = new FileStream(LockPath(folder, testRoot), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); }
|
||||
catch (IOException) { return false; } // (another launcher has it)
|
||||
catch (Exception) { return true; } // (no lock can be made here: nobody is refused)
|
||||
try
|
||||
{
|
||||
var sock = SocketPath(folder, testRoot);
|
||||
try { File.Delete(sock); } catch (Exception) { }
|
||||
listener = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
|
||||
listener.Bind(new UnixDomainSocketEndPoint(sock));
|
||||
listener.Listen(4);
|
||||
}
|
||||
catch (Exception) { listener = null; }
|
||||
if (come != null) Wait();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The launcher replacing itself with a newer one, so that a new one that does not start is not what the player is left
|
||||
/// with (old Guard.cs Handover). The new exe takes the running one's name, the running one keeps running under another (Windows
|
||||
/// lets a running program be renamed, not written over), and the new one is started. The old one stays, out of sight, until the
|
||||
/// new one gives a sign that its window is up (the named event "<lock name>-up"). A new launcher that cannot be started, or that
|
||||
/// ends with an error's exit code before that sign, is taken back. One that gives no sign and goes on running is left alone.</summary>
|
||||
public static class Handover
|
||||
{
|
||||
/// <summary>Up: its window came up. Failed: it could not come up. Unclear: neither is known.</summary>
|
||||
public enum Outcome { Up, Failed, Unclear }
|
||||
|
||||
/// <summary>The old launcher, before it starts the new one: the sign it will wait for. Null where there are no named events.</summary>
|
||||
public static EventWaitHandle? Expect(string folder, string? testRoot)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return null;
|
||||
return new EventWaitHandle(false, EventResetMode.ManualReset, InstanceLock.UpName(folder, testRoot));
|
||||
}
|
||||
|
||||
/// <summary>The new launcher, once its window is up: tells the launcher that started it, when one waits to hear it. Without
|
||||
/// it an old Setup waits 30 s hidden and then quits (research/02 2.8 point 3).</summary>
|
||||
public static void Up(string folder, string? testRoot)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
try
|
||||
{
|
||||
if (EventWaitHandle.TryOpenExisting(InstanceLock.UpName(folder, testRoot), out var up))
|
||||
using (up) up.Set();
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>What became of the launcher that was started, within the time given (polled every 100 ms).</summary>
|
||||
public static Outcome Watch(Process started, WaitHandle? up, TimeSpan limit)
|
||||
{
|
||||
try
|
||||
{
|
||||
for (var until = DateTime.UtcNow + limit; ;)
|
||||
{
|
||||
if (up != null) { if (up.WaitOne(100)) return Outcome.Up; }
|
||||
else started.WaitForExit(100); // (no sign to wait for: only how it ends says anything)
|
||||
if (started.HasExited) return up != null && up.WaitOne(0) ? Outcome.Up : started.ExitCode != 0 ? Outcome.Failed : Outcome.Unclear;
|
||||
if (DateTime.UtcNow > until) return Outcome.Unclear;
|
||||
}
|
||||
}
|
||||
catch (Exception) { return Outcome.Unclear; }
|
||||
}
|
||||
|
||||
/// <summary>The running launcher (self) steps aside as previous, and fresh takes its name. A second step that fails is undone:
|
||||
/// there is always a launcher under the name the shortcuts start.</summary>
|
||||
public static void Swap(string fresh, string self, string previous)
|
||||
{
|
||||
if (File.Exists(previous)) File.Delete(previous);
|
||||
File.Move(self, previous);
|
||||
try { File.Move(fresh, self); }
|
||||
catch (Exception)
|
||||
{
|
||||
try { File.Move(previous, self); } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The launcher before (previous, which may be the program that calls this) back over the one that did not start, in
|
||||
/// one step. Tried for a few seconds: a virus scanner may still hold the new file. False when it could not be done.</summary>
|
||||
public static bool Restore(IPlatform platform, string previous, string self, int tries = 20)
|
||||
{
|
||||
for (var i = 0; i < tries; i++)
|
||||
{
|
||||
if (i > 0) Thread.Sleep(250);
|
||||
try
|
||||
{
|
||||
if (File.Exists(previous)) { platform.ReplaceFile(previous, self); return true; }
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
103
launcher/Logic/Guard/Partial.cs
Normal file
103
launcher/Logic/Guard/Partial.cs
Normal file
@@ -0,0 +1,103 @@
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>(Triforce) A copy that is never seen half done (old Guard.cs Partial). The old Setup copied itself into the install
|
||||
/// folder and a save over the one there file by file, in place: a full disk, a file held open or Setup closed in the middle left
|
||||
/// a Setup that does not start under the name every shortcut starts, or half a save. Now the copy is written as
|
||||
/// <name>.partial beside its place and renamed into it once complete; what was there is replaced in one step (a file) or
|
||||
/// moved aside as <name>.old and removed after (a folder), and moved back when the new one cannot go in.</summary>
|
||||
public sealed class Partial
|
||||
{
|
||||
public const string Suffix = ".partial", Aside = ".old";
|
||||
readonly IPlatform platform;
|
||||
public Partial(IPlatform platform) { this.platform = platform; }
|
||||
|
||||
/// <summary>(testing) called with the partial once it is complete, before it goes into its place: a test checks what holds
|
||||
/// then, or throws to stand for a failure there.</summary>
|
||||
public Action<string>? Copied { get; set; }
|
||||
|
||||
/// <summary>A file or a folder and what is in it, gone; quietly when it cannot be.</summary>
|
||||
public static void Remove(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path)) { File.SetAttributes(path, FileAttributes.Normal); File.Delete(path); }
|
||||
else if (Directory.Exists(path)) Directory.Delete(path, true);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>from copied to to, through to.partial: an older to is replaced in one step only once the copy is complete.</summary>
|
||||
public void CopyFile(string from, string to)
|
||||
{
|
||||
var partial = to + Suffix;
|
||||
try
|
||||
{
|
||||
Remove(partial);
|
||||
File.Copy(from, partial, false);
|
||||
Copied?.Invoke(partial);
|
||||
platform.ReplaceFile(partial, to);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Remove(partial);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The folder from copied as to.partial (one there from a copy that was cut off is removed first); its path.</summary>
|
||||
public string Stage(string from, string to)
|
||||
{
|
||||
var partial = to + Suffix;
|
||||
try
|
||||
{
|
||||
Remove(partial);
|
||||
Tree(from, partial);
|
||||
return partial;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Remove(partial);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
static void Tree(string from, string to)
|
||||
{
|
||||
Directory.CreateDirectory(to);
|
||||
foreach (var f in Directory.GetFiles(from)) File.Copy(f, Path.Combine(to, Path.GetFileName(f)), false);
|
||||
foreach (var d in Directory.GetDirectories(from)) Tree(d, Path.Combine(to, Path.GetFileName(d)));
|
||||
}
|
||||
|
||||
/// <summary>A complete partial folder put in to's place: the folder there moved aside as to.old first and removed after, or
|
||||
/// moved back when the new one cannot go in (the partial is then removed).</summary>
|
||||
public void SwapIn(string partial, string to)
|
||||
{
|
||||
var old = to + Aside;
|
||||
try
|
||||
{
|
||||
Copied?.Invoke(partial);
|
||||
Remove(old);
|
||||
if (Directory.Exists(to)) Directory.Move(to, old);
|
||||
try { Directory.Move(partial, to); }
|
||||
catch (Exception)
|
||||
{
|
||||
try { if (!Directory.Exists(to) && Directory.Exists(old)) Directory.Move(old, to); } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Remove(partial);
|
||||
throw;
|
||||
}
|
||||
Remove(old);
|
||||
}
|
||||
|
||||
/// <summary>What a copy that was cut off left beside to: the folder moved aside goes back when to is gone, and a partial goes.</summary>
|
||||
public static void Recover(string to)
|
||||
{
|
||||
try { if (!Directory.Exists(to) && Directory.Exists(to + Aside)) Directory.Move(to + Aside, to); } catch (Exception) { }
|
||||
if (Directory.Exists(to)) Remove(to + Aside);
|
||||
Remove(to + Suffix);
|
||||
}
|
||||
}
|
||||
65
launcher/Logic/Guard/Report.cs
Normal file
65
launcher/Logic/Guard/Report.cs
Normal file
@@ -0,0 +1,65 @@
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>What a player copies after a build that stopped, to paste where they ask for help: what the launcher knows of the
|
||||
/// build, the build's last lines and setup.log's. The folder of the player's account, which carries their name and is in most
|
||||
/// paths of a log, reads %USERPROFILE% in it (old Guard.cs Report).</summary>
|
||||
public static class Report
|
||||
{
|
||||
/// <summary>How many of its last lines each log gives.</summary>
|
||||
public const int Lines = 200;
|
||||
|
||||
/// <summary>The last lines of a text, at most so many, without the empty ones at its end.</summary>
|
||||
public static string Tail(string text, int lines)
|
||||
{
|
||||
var all = text.Replace("\r", "").TrimEnd('\n', ' ').Split('\n');
|
||||
return string.Join(Environment.NewLine, all.Skip(Math.Max(0, all.Length - lines)));
|
||||
}
|
||||
|
||||
/// <summary>The text with each of the folders (the account's own, and its short name) read as %USERPROFILE%: in any case of
|
||||
/// its letters, with either slash or doubled ones between its parts, as a build's tools print paths. A folder that only
|
||||
/// begins with the same letters (C:\Users\Ann and C:\Users\Anna) is another one and stays.</summary>
|
||||
public static string NoName(string text, params string?[] folders)
|
||||
{
|
||||
foreach (var folder in folders.Where(f => !string.IsNullOrWhiteSpace(f)).OrderByDescending(f => f!.Length))
|
||||
{
|
||||
var parts = folder!.Split(new[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2) continue; // (a whole drive is nobody's name)
|
||||
var pattern = (folder.StartsWith("\\") || folder.StartsWith("/") ? @"[\\/]+" : "") + string.Join(@"[\\/]+", parts.Select(Regex.Escape)) + @"(?![\p{L}\p{N}])";
|
||||
text = Regex.Replace(text, pattern, "%USERPROFILE%", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/// <summary>The report: what the launcher knows, then the last lines of what the build said and of setup.log.</summary>
|
||||
public static string Compose(IEnumerable<string> known, string build, string log, params string?[] folders)
|
||||
{
|
||||
var s = new StringBuilder();
|
||||
foreach (var line in known) s.AppendLine(line);
|
||||
s.AppendLine().AppendLine("---- the build's last lines ----").AppendLine(Tail(build, Lines));
|
||||
s.AppendLine().AppendLine("---- setup.log's last lines ----").AppendLine(Tail(log, Lines));
|
||||
return NoName(s.ToString(), folders);
|
||||
}
|
||||
|
||||
/// <summary>The report for a build that stopped (old Shell.cs CopyTheReport): the launcher's and tools' versions, the OS, the
|
||||
/// step it stopped at, why, the command, the game folder and the install with their free space, then the logs.</summary>
|
||||
public static string ForBuild(TriforceContext ctx, BuildResult? result, string buildLines, string? toolsVersion)
|
||||
{
|
||||
string Room(string folder) => ctx.FreeBytes(folder) is { } free ? " (" + ctx.Platform.Disk(folder) + " has " + (free >> 30) + " GB free)" : "";
|
||||
var step = result?.StoppedAt is { } s && BuildStages.Find(s) is { } st ? "\"" + st.Text + "\"" : "its start";
|
||||
var known = new[]
|
||||
{
|
||||
"Triforce " + BuildInfo.Version + ", tools " + (toolsVersion ?? "none") + ", " + Environment.OSVersion.VersionString,
|
||||
"The build stopped at " + step + " after " + BuildClock.Span(result?.Elapsed ?? TimeSpan.Zero) + ": " + (result?.Failure ?? "no reason given"),
|
||||
result?.CommandLine ?? "",
|
||||
"Game folder: " + (result?.OutFolder ?? "") + (result?.OutFolder is { } o ? Room(o) : ""),
|
||||
"Launcher: " + ctx.Home + Room(ctx.Home),
|
||||
};
|
||||
var profile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
string? shortName = null;
|
||||
if (OperatingSystem.IsWindows()) shortName = WindowsPlatform.ShortName(profile);
|
||||
return Compose(known, buildLines, ctx.Log.ReadAll(), profile, shortName);
|
||||
}
|
||||
}
|
||||
48
launcher/Logic/Guard/SaveLock.cs
Normal file
48
launcher/Logic/Guard/SaveLock.cs
Normal file
@@ -0,0 +1,48 @@
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>(Triforce) The save's lock between the game and the launcher (old Guard.cs SaveLock). The game holds
|
||||
/// <user>\save.lock open without sharing from its first save mount to its end (host/save_tx.h save_tx_lock); NX2navi holds
|
||||
/// <profile>\instance.lock the same way. Taken by the launcher across the whole copy, the lock says for certain whether the game
|
||||
/// runs, and a game started meanwhile waits for it before it mounts its save.
|
||||
///
|
||||
/// Linux: .NET takes FileShare.None as an advisory flock there, and the game takes none (research/02 section 11: "No Linux guard
|
||||
/// exists today"), so on Linux only the process check (Saves.RunningGame) guards a copy.</summary>
|
||||
public static class SaveLock
|
||||
{
|
||||
public const string Running = "The game is running: quit it first. It keeps its save open while it runs, and would write over the copy.";
|
||||
|
||||
/// <summary>The lock of a save folder <user>\save\<uid> (or a commit waiting in <user>\save-tx\<uid>\ready-<n>):
|
||||
/// <user>\save.lock, or instance.lock in NX2navi's profile folder; null for another kind of save folder (an emulator's).</summary>
|
||||
public static string? PathOf(string save)
|
||||
{
|
||||
string dir;
|
||||
try { dir = Path.GetFullPath(save).TrimEnd('\\', '/'); }
|
||||
catch (Exception) { return null; }
|
||||
var parent = Path.GetDirectoryName(dir);
|
||||
if (parent != null && Path.GetDirectoryName(parent) is { } tx && string.Equals(Path.GetFileName(tx), "save-tx", StringComparison.OrdinalIgnoreCase))
|
||||
parent = Path.Combine(Path.GetDirectoryName(tx) ?? tx, "save");
|
||||
if (parent == null || !string.Equals(Path.GetFileName(parent), "save", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
var user = Path.GetDirectoryName(parent);
|
||||
if (string.IsNullOrEmpty(user)) return null;
|
||||
return Path.Combine(user, string.Equals(Path.GetFileName(user), "profile", StringComparison.OrdinalIgnoreCase) ? "instance.lock" : "save.lock");
|
||||
}
|
||||
|
||||
/// <summary>The lock of a save folder, held until it is disposed (an open handle that shares nothing). Null when the folder has
|
||||
/// none or it cannot be made there (nothing is locked: the copy goes on as before). InvalidOperationException (Running) when a
|
||||
/// game holds it.</summary>
|
||||
public static FileStream? Take(string save)
|
||||
{
|
||||
if (PathOf(save) is not { } path) return null;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
return new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
|
||||
}
|
||||
catch (IOException e) when ((e.HResult & 0xFFFF) == 32 || (e.HResult & 0xFFFF) == 33 || !OperatingSystem.IsWindows() && (e.HResult & 0xFFFF) == 11)
|
||||
{
|
||||
// (ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION; EWOULDBLOCK from flock)
|
||||
throw new InvalidOperationException(Running);
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
}
|
||||
47
launcher/Logic/Guard/Space.cs
Normal file
47
launcher/Logic/Guard/Space.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
// What keeps a run of the launcher from damaging an install (old setup/Guard.cs). Nothing here needs a window.
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>Room on a disk, asked before it is needed. A download or an unpacking that ran out of room stopped somewhere in the
|
||||
/// middle with Windows' own words for it and left half of itself behind; asked first, the player is told how much it takes and
|
||||
/// how much there is, before anything is written.</summary>
|
||||
public static class Space
|
||||
{
|
||||
/// <summary>What a disk keeps free beyond what is about to be written to it.</summary>
|
||||
public const long Margin = 32L << 20;
|
||||
|
||||
/// <summary>Null when the free bytes are room for need more of them and the margin, or are not known; else the sentence that
|
||||
/// says there is no room for what, how much it takes and how much is free (what it takes rounded up and what is free rounded
|
||||
/// down, so the two numbers never read the same).</summary>
|
||||
public static string? Problem(string what, long need, long? free, string disk)
|
||||
{
|
||||
need = Math.Max(0, need) + Margin;
|
||||
if (free is not { } f || f >= need) return null;
|
||||
return "There is no room for " + what + " on " + disk + ": it takes " + ((need + (1 << 20) - 1) >> 20) + " MB there, and " + (Math.Max(0, f) >> 20) +
|
||||
" MB are free. Make room and try again.";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>There is no room for what is about to be written (Space.Problem's sentence), said before any of it is.</summary>
|
||||
public sealed class NoRoomException : IOException
|
||||
{
|
||||
public NoRoomException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
/// <summary>A download stopped before its end (the connection was cut, went silent or closed early): its part is kept, and the
|
||||
/// next try goes on from it.</summary>
|
||||
public sealed class CutOffException : IOException
|
||||
{
|
||||
public CutOffException(string message, Exception? inner = null) : base(message, inner) { }
|
||||
}
|
||||
|
||||
/// <summary>The launcher an update brought could not start, and what was done about it.</summary>
|
||||
public sealed class NotStartedException : Exception
|
||||
{
|
||||
public NotStartedException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
/// <summary>The release server has no release (404, an empty list, an empty tag).</summary>
|
||||
public sealed class NoReleaseException : InvalidOperationException
|
||||
{
|
||||
public NoReleaseException() : base("There is no Triforce release yet.") { }
|
||||
}
|
||||
127
launcher/Logic/Install.cs
Normal file
127
launcher/Logic/Install.cs
Normal file
@@ -0,0 +1,127 @@
|
||||
// A per-user install, as the old Setup made it (research/02 1.1-1.5): the exe copied into %LOCALAPPDATA%\Programs\Triforce,
|
||||
// the Apps-list entry under HKCU, the shortcuts; and the uninstall that takes it away again (game folders and saves stay).
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
public sealed class Installer
|
||||
{
|
||||
readonly TriforceContext ctx;
|
||||
public Installer(TriforceContext ctx) { this.ctx = ctx; }
|
||||
|
||||
/// <summary>The folder an install goes to when the player changes nothing.</summary>
|
||||
public string DefaultDir => ctx.Platform.DefaultInstallDir;
|
||||
|
||||
/// <summary>The line under the install folder (old Shell.cs InstallSpaceText): "about 2 GB", red at 3 GiB free or less.</summary>
|
||||
public (string Text, bool Low) SpaceLine(string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
var disk = ctx.Platform.Disk(dir);
|
||||
if (ctx.FreeBytes(dir) is not { } free) return ("Triforce and its tools take about 2 GB.", false);
|
||||
return ("Triforce and its tools take about 2 GB. " + disk + " has " + (free >> 30) + " GB free.", free <= (3L << 30));
|
||||
}
|
||||
catch (Exception) { return ("Triforce and its tools take about 2 GB.", false); }
|
||||
}
|
||||
|
||||
/// <summary>Copies this exe into the folder, registers it in the Apps list and makes the shortcuts. Returns the installed exe.
|
||||
/// ("Triforce" opens the launcher, not the game: every start goes through the update question first, then Play.)</summary>
|
||||
public string Run(string dir, bool desktop, bool startMenu)
|
||||
{
|
||||
dir = Path.GetFullPath(dir);
|
||||
ctx.Require(dir);
|
||||
Directory.CreateDirectory(dir);
|
||||
var exe = Path.Combine(dir, BuildInfo.SetupAsset);
|
||||
if (ctx.IsWindows)
|
||||
{
|
||||
// ((Triforce) through <exe>.partial, renamed into place once complete: a copy cut off in the middle left a Setup that
|
||||
// does not start under the name every shortcut starts. Partial)
|
||||
if (!TriforceContext.SamePath(exe, ctx.SelfPath)) new Partial(ctx.Platform).CopyFile(ctx.SelfPath, exe);
|
||||
var s = ctx.Platform.Settings;
|
||||
if (!ctx.NoWrites)
|
||||
{
|
||||
s.SetUninstall("DisplayName", BuildInfo.AppName);
|
||||
s.SetUninstall("DisplayIcon", exe + ",0");
|
||||
s.SetUninstall("DisplayVersion", BuildInfo.Version);
|
||||
s.SetUninstall("Publisher", "Triforce");
|
||||
s.SetUninstall("InstallLocation", dir);
|
||||
s.SetUninstall("UninstallString", "\"" + exe + "\" --uninstall");
|
||||
s.SetUninstall("QuietUninstallString", "\"" + exe + "\" --uninstall --quiet");
|
||||
s.SetUninstall("URLInfoAbout", BuildInfo.Home);
|
||||
s.SetUninstallNumber("NoModify", 1);
|
||||
s.SetUninstallNumber("NoRepair", 1);
|
||||
}
|
||||
}
|
||||
else exe = ctx.Env("APPIMAGE") ?? ctx.SelfPath; // (Linux: the AppImage stays where the player keeps it; only the menu entries are made)
|
||||
ctx.Settings.Desktop = desktop;
|
||||
ctx.Settings.StartMenu = startMenu;
|
||||
try
|
||||
{
|
||||
var link = new Shortcut(exe, "", ctx.IsWindows ? dir : Path.GetDirectoryName(exe)!, exe, "Play Triforce");
|
||||
if (startMenu) ctx.Platform.CreateShortcut(ShortcutPlace.StartMenu, link);
|
||||
if (desktop) ctx.Platform.CreateShortcut(ShortcutPlace.Desktop, link);
|
||||
}
|
||||
catch (Exception e) { ctx.Log.Write("shortcuts: " + e.Message); }
|
||||
ctx.Log.Write("installed " + BuildInfo.Version + " to " + dir);
|
||||
return exe;
|
||||
}
|
||||
|
||||
/// <summary>Starts a launcher exe with arguments (each one as is; quoted by .NET with the MSVC rules), in its own folder.</summary>
|
||||
public static Process? Start(string exe, IEnumerable<string> args)
|
||||
{
|
||||
var si = new ProcessStartInfo(exe) { UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(exe)! };
|
||||
foreach (var a in args) si.ArgumentList.Add(a);
|
||||
return Process.Start(si);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What an uninstall removes and what it keeps, said before it is done (DESIGN 6 Settings: "says what goes and what stays").</summary>
|
||||
public sealed record UninstallPlan(IReadOnlyList<string> Removes, IReadOnlyList<string> Keeps);
|
||||
|
||||
/// <summary>Removes the launcher, its tools and the shortcuts (old Setup.cs Install.Uninstall). Game folders and saves are the
|
||||
/// player's and stay. The question ("Remove Triforce and its tools from this PC?") is the App's; --quiet asks nothing.</summary>
|
||||
public sealed class Uninstaller
|
||||
{
|
||||
readonly TriforceContext ctx;
|
||||
public Uninstaller(TriforceContext ctx) { this.ctx = ctx; }
|
||||
|
||||
public UninstallPlan Describe()
|
||||
{
|
||||
var removes = new List<string>
|
||||
{
|
||||
"Triforce and its tools (" + ctx.Home + ")",
|
||||
"the shortcuts",
|
||||
"the build's work folder and compile cache (" + ctx.WorkFolder + ", made again by a build)",
|
||||
"the launcher's settings",
|
||||
};
|
||||
if (!ctx.IsWindows) removes[0] = "the launcher's updates and NVIDIA's SDK (" + ctx.Platform.DefaultInstallDir + ")";
|
||||
var keeps = new List<string> { "your game folders" + (ctx.Settings.GameFolder is { } g ? " (" + g + ")" : ""), "your saves" };
|
||||
return new UninstallPlan(removes, keeps);
|
||||
}
|
||||
|
||||
/// <summary>Does it. The launcher's own folder goes once this process is gone (Windows: a short-lived cmd waits 2 s, then
|
||||
/// rmdir; Linux: removed now, a running binary can be unlinked).</summary>
|
||||
public void Run()
|
||||
{
|
||||
var dir = ctx.InstalledDir ?? ctx.Home;
|
||||
ctx.Log.Write("uninstall: " + dir);
|
||||
ctx.Platform.RemoveShortcuts();
|
||||
// (the build's work folder and compile cache, nx2/make_game.py --work: several GB, made again by a build)
|
||||
var work = ctx.WorkFolder;
|
||||
try { if (Directory.Exists(work) && ctx.Allowed(work)) Directory.Delete(work, true); } catch (Exception) { }
|
||||
ctx.Platform.Settings.RemoveUninstall();
|
||||
ctx.Platform.Settings.RemoveAll();
|
||||
if (ctx.IsWindows)
|
||||
{
|
||||
// (this exe is running from the folder: a short-lived cmd removes it once we are gone)
|
||||
if (File.Exists(Path.Combine(dir, BuildInfo.SetupAsset)) && ctx.Allowed(dir))
|
||||
Process.Start(new ProcessStartInfo("cmd.exe", "/c timeout /t 2 /nobreak >nul & rmdir /s /q \"" + dir + "\"")
|
||||
{ CreateNoWindow = true, UseShellExecute = false, WorkingDirectory = Path.GetTempPath() })?.Dispose();
|
||||
}
|
||||
else
|
||||
{
|
||||
var root = ctx.Platform.DefaultInstallDir;
|
||||
try { if (Directory.Exists(root) && ctx.Allowed(root)) Directory.Delete(root, true); } catch (Exception) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
43
launcher/Logic/Languages.cs
Normal file
43
launcher/Logic/Languages.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>One of the game's languages: the code make_game.py takes (--language) and writes to language.txt, its name in English
|
||||
/// (make_game.py LANGUAGES) and in itself (old Strings.cs).</summary>
|
||||
public sealed record GameLanguage(string Code, string EnglishName, string NativeName);
|
||||
|
||||
public static class Languages
|
||||
{
|
||||
/// <summary>The 16 codes, identical in make_game.py LANGUAGES (nx2/make_game.py:60-63) and the old Strings.cs All.</summary>
|
||||
public static readonly IReadOnlyList<GameLanguage> All = new GameLanguage[]
|
||||
{
|
||||
new("en-US", "English (US)", "English (US)"), new("en-GB", "English (UK)", "English (UK)"),
|
||||
new("fr", "French (France)", "Français"), new("fr-CA", "French (Canada)", "Français (Canada)"),
|
||||
new("de", "German", "Deutsch"), new("it", "Italian", "Italiano"),
|
||||
new("es", "Spanish (Spain)", "Español (España)"), new("es-419", "Spanish (Latin America)", "Español (Latinoamérica)"),
|
||||
new("pt-BR", "Portuguese (Brazil)", "Português (Brasil)"), new("nl", "Dutch", "Nederlands"),
|
||||
new("pl", "Polish", "Polski"), new("ru", "Russian", "Русский"),
|
||||
new("ja", "Japanese", "日本語"), new("ko", "Korean", "한국어"),
|
||||
new("zh-Hans", "Chinese (Simplified)", "简体中文"), new("zh-Hant", "Chinese (Traditional)", "繁體中文"),
|
||||
};
|
||||
|
||||
public static GameLanguage? Find(string? code) => All.FirstOrDefault(l => l.Code == code);
|
||||
|
||||
/// <summary>The language closest to the system's own (old Strings.cs Default): the exact one, then the same family, else
|
||||
/// English (US). name: a culture name ("de-AT"); the current UI culture's, or LANG's on Linux, when none is given.</summary>
|
||||
public static GameLanguage Default(string? name = null)
|
||||
{
|
||||
name ??= CultureInfo.CurrentUICulture.Name;
|
||||
if (string.IsNullOrEmpty(name) && Environment.GetEnvironmentVariable("LANG") is { Length: > 0 } lang)
|
||||
name = lang.Split('.')[0].Replace('_', '-'); // (InvariantGlobalization: the culture says nothing; LANG=de_AT.UTF-8 does)
|
||||
name ??= "";
|
||||
var pick = All.FirstOrDefault(l => l.Code.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
if (pick != null) return pick;
|
||||
if (name.StartsWith("zh", StringComparison.OrdinalIgnoreCase))
|
||||
return Find(name.Contains("TW") || name.Contains("HK") || name.Contains("Hant") ? "zh-Hant" : "zh-Hans")!;
|
||||
if (name.StartsWith("es-", StringComparison.OrdinalIgnoreCase) && !name.Equals("es-ES", StringComparison.OrdinalIgnoreCase)) return Find("es-419")!;
|
||||
if (name.StartsWith("pt", StringComparison.OrdinalIgnoreCase)) return Find("pt-BR")!;
|
||||
var two = name.Split('-')[0].ToLowerInvariant();
|
||||
return All.FirstOrDefault(l => l.Code == two) ?? All[0];
|
||||
}
|
||||
}
|
||||
179
launcher/Logic/LinuxUpdate.cs
Normal file
179
launcher/Logic/LinuxUpdate.cs
Normal file
@@ -0,0 +1,179 @@
|
||||
// Linux builder updates (builder/linux/linux_update.py; research/12 section 5).
|
||||
//
|
||||
// !!! BROKEN ON CURRENT RELEASES (research/12 5.4, verified from the release files 11-19): the parts self-update cannot work
|
||||
// today. The Forgejo releases (v0.5.0, v0.5.1) carry only Triforce-Tools.zip, the Linux AppImage and TriforceSetup.exe: there
|
||||
// is NO triforce-linux.txt, so FetchManifestAsync gets a 404 and every "Update builder" ends in an error. And the part URLs that
|
||||
// scripts/linux/appimage.sh writes point at https://github.com/NotRexed/Hookshot/releases/download/linux-parts (no
|
||||
// GITHUB_REPOSITORY on the hand-built releases), which publish_parts.sh uploads to GitHub only. Until the release process
|
||||
// publishes parts and the list to Forgejo, a Linux player updates by downloading the new AppImage (Release.LinuxAppImageUrl),
|
||||
// which is what the launcher should offer. The parts INSTALLER (linux_update.install: clone unchanged parts with hard links,
|
||||
// download the rest, sha256 + size check, unzip with path and symlink guards, rebase the sysroot's links, versions/<tag>.part
|
||||
// -> versions/<tag>, current) is NOT ported: TODO once the parts are published again.
|
||||
//
|
||||
// What is ported, as pure logic (with tests/test_linux_update.py's cases in LogicTests): the list's format, release_key,
|
||||
// update_target, choose_mode, tools_tag, game_version, and where the installed builder is (current, versions/<tag>/AppRun),
|
||||
// which shipped games (host/hos_update.c) and folder scripts (hookshot-folder) read.
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
public sealed record LinuxPart(string Sha, long Size, string Dest, string Url, IReadOnlyList<string>? Files);
|
||||
|
||||
public sealed record LinuxManifest(string Tag, IReadOnlyList<LinuxPart> Parts);
|
||||
|
||||
/// <summary>A version to compare (linux_update.release_key): the numbers, then a prerelease before its release, then commits after
|
||||
/// a tag (or changes to it) after that tag and before the next.</summary>
|
||||
public sealed record ReleaseKey(IReadOnlyList<int> Numbers, bool Released, bool After) : IComparable<ReleaseKey>
|
||||
{
|
||||
public int CompareTo(ReleaseKey? o)
|
||||
{
|
||||
if (o == null) return 1;
|
||||
for (var i = 0; i < Math.Min(Numbers.Count, o.Numbers.Count); i++)
|
||||
if (Numbers[i] != o.Numbers[i]) return Numbers[i].CompareTo(o.Numbers[i]);
|
||||
if (Numbers.Count != o.Numbers.Count) return Numbers.Count.CompareTo(o.Numbers.Count);
|
||||
if (Released != o.Released) return Released ? 1 : -1;
|
||||
return After == o.After ? 0 : After ? 1 : -1;
|
||||
}
|
||||
}
|
||||
|
||||
public static class LinuxUpdate
|
||||
{
|
||||
public const string LatestList = BuildInfo.Downloads + "/releases/latest/download/" + BuildInfo.LinuxListAsset;
|
||||
static readonly Regex KeyPattern = new(@"^(?=v|\d+\.)v?(\d+(?:\.\d+)*)(?:-(?!\d+-g|dirty$)([0-9A-Za-z]+(?:\.[0-9A-Za-z]+)*))?(-\d+-g[0-9a-f]+)?(-dirty)?$");
|
||||
|
||||
/// <summary>A release tag (v2.0.5, v2.1.0-rc.1) or git describe's v2.0.5-3-g1a2b3c4[-dirty]; null for a build that names no
|
||||
/// release (a bare commit, dev, nothing).</summary>
|
||||
public static ReleaseKey? Key(string? tag)
|
||||
{
|
||||
var m = KeyPattern.Match((tag ?? "").Trim());
|
||||
if (!m.Success) return null;
|
||||
return new ReleaseKey(m.Groups[1].Value.Split('.').Select(int.Parse).ToList(), !m.Groups[2].Success, m.Groups[3].Success || m.Groups[4].Success);
|
||||
}
|
||||
|
||||
/// <summary>The newest version this builder knows of: the latest release when it is newer than these tools, else the tools'
|
||||
/// own (issue 902: a test build newer than the release is not taken back to it).</summary>
|
||||
public static string? UpdateTarget(string? latest, string? tools)
|
||||
{
|
||||
if (string.IsNullOrEmpty(latest) || string.IsNullOrEmpty(tools)) return string.IsNullOrEmpty(latest) ? tools : latest;
|
||||
var have = Key(tools);
|
||||
var outKey = Key(latest);
|
||||
return have != null && outKey != null && outKey.CompareTo(have) > 0 ? latest : tools;
|
||||
}
|
||||
|
||||
/// <summary>Is the release a newer builder than these tools?</summary>
|
||||
public static bool BuilderNewer(string? latest, string? tools) => !string.IsNullOrEmpty(latest) && !string.IsNullOrEmpty(tools) && UpdateTarget(latest, tools) != tools;
|
||||
|
||||
/// <summary>What the builder's button does (choose_mode): "update-game" (an older game that still has its files),
|
||||
/// "up-to-date" (play), "update-builder", or "build".</summary>
|
||||
public static string ChooseMode(string? game, string? tools, string? latest, bool sourcePicked, bool kept)
|
||||
{
|
||||
var target = UpdateTarget(latest, tools);
|
||||
if (kept && !string.IsNullOrEmpty(game) && !string.IsNullOrEmpty(target) && game != target && !sourcePicked) return "update-game";
|
||||
if (!string.IsNullOrEmpty(game) && !sourcePicked) return "up-to-date";
|
||||
if (!string.IsNullOrEmpty(latest) && !string.IsNullOrEmpty(tools) && target != tools) return "update-builder";
|
||||
return "build";
|
||||
}
|
||||
|
||||
/// <summary>The setup list (parse_list). local: a list from this PC, whose parts may be file:// links; a downloaded one's are
|
||||
/// https. Throws FormatException for anything else.</summary>
|
||||
public static LinuxManifest ParseList(string text, bool local = true)
|
||||
{
|
||||
var tag = "";
|
||||
var parts = new List<(string Sha, long Size, string Dest, string Url, List<string>? Files)>();
|
||||
int cur = -1;
|
||||
foreach (var raw in text.Replace("\r", "").Split('\n'))
|
||||
{
|
||||
var line = raw.Trim();
|
||||
if (line.Length == 0 || line.StartsWith('#')) continue;
|
||||
if (line.StartsWith("tag ", StringComparison.Ordinal)) tag = line.Substring(4).Trim();
|
||||
else if (line.StartsWith("part ", StringComparison.Ordinal))
|
||||
{
|
||||
var bits = line.Split(' ');
|
||||
if (bits.Length != 5 || !long.TryParse(bits[2], out var size)) throw new FormatException("a part line needs sha, size, directory and url");
|
||||
parts.Add((bits[1], size, bits[3], bits[4], new List<string>()));
|
||||
cur = parts.Count - 1;
|
||||
}
|
||||
else if (line == "tree")
|
||||
{
|
||||
if (cur < 0) throw new FormatException("tree with no part");
|
||||
parts[cur] = parts[cur] with { Files = null };
|
||||
}
|
||||
else if (line.StartsWith("file ", StringComparison.Ordinal))
|
||||
{
|
||||
if (cur < 0 || parts[cur].Files == null) throw new FormatException("file with no part");
|
||||
parts[cur].Files!.Add(line.Substring(5).Trim());
|
||||
}
|
||||
else throw new FormatException("unknown list line");
|
||||
}
|
||||
if (tag.Length == 0 || parts.Count == 0) throw new FormatException("the setup list has no release");
|
||||
// (the tag names a folder under versions/ that an update removes and remakes, and a part's names are paths in it)
|
||||
if (!Regex.IsMatch(tag, @"^[0-9A-Za-z._+-]{1,128}$") || tag == "." || tag == "..") throw new FormatException("the setup list's tag is not a version name");
|
||||
foreach (var p in parts)
|
||||
{
|
||||
if (!Regex.IsMatch(p.Sha, "^[0-9a-f]{64}$") || !(p.Url.StartsWith("https://", StringComparison.Ordinal) || local && p.Url.StartsWith("file://", StringComparison.Ordinal)))
|
||||
throw new FormatException("a part line has a bad checksum or link");
|
||||
if (p.Dest != "." && SafeName(p.Dest) is { } why) throw new FormatException(why);
|
||||
foreach (var n in p.Files ?? new List<string>())
|
||||
if (SafeName(n) is { } why2) throw new FormatException(why2);
|
||||
}
|
||||
return new LinuxManifest(tag, parts.Select(p => new LinuxPart(p.Sha, p.Size, p.Dest, p.Url, p.Files)).ToList());
|
||||
}
|
||||
|
||||
/// <summary>A relative path that stays inside the folder it names a place in (linux_update._safe_name), null when it does.</summary>
|
||||
static string? SafeName(string name)
|
||||
{
|
||||
if (name.Length == 0 || name.StartsWith('/') || name.Split('/').Contains("..")) return "the zip has a path outside its folder";
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The release these tools are, from VERSION or version.txt (tools_tag).</summary>
|
||||
public static string ToolsTag(string? root)
|
||||
{
|
||||
if (string.IsNullOrEmpty(root)) return "";
|
||||
foreach (var rel in new[] { "usr/share/hookshot/VERSION", "usr/share/hookshot/version.txt", "VERSION", "version.txt" })
|
||||
{
|
||||
try
|
||||
{
|
||||
var path = Path.Combine(root, rel);
|
||||
if (!File.Exists(path)) continue;
|
||||
var line = File.ReadLines(path).FirstOrDefault()?.Trim();
|
||||
if (!string.IsNullOrEmpty(line)) return line;
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/// <summary>The builder an update installed: data_root/versions/<current>/AppRun, null when none (hookshot-folder installed()).</summary>
|
||||
public static string? InstalledAppRun(string dataRoot)
|
||||
{
|
||||
try
|
||||
{
|
||||
var current = Path.Combine(dataRoot, "current");
|
||||
if (!File.Exists(current)) return null;
|
||||
var tag = File.ReadAllText(current).Replace(" ", "").Replace("\r", "").Replace("\n", "");
|
||||
var run = Path.Combine(dataRoot, "versions", tag, "AppRun");
|
||||
return tag.Length > 0 && File.Exists(run) ? run : null;
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
/// <summary>The newest release's own list, by its tag (so a pre-release is found), else releases/latest
|
||||
/// (fetch_manifest). HOOKSHOT_LINUX_LIST=<file> overrides. SEE THE NOTE AT THE TOP: no release has a list today.</summary>
|
||||
public static async Task<LinuxManifest> FetchManifestAsync(TriforceContext ctx, HttpClient http, Release? latest, CancellationToken token)
|
||||
{
|
||||
if (ctx.Env("HOOKSHOT_LINUX_LIST") is { Length: > 0 } local) return ParseList(await File.ReadAllTextAsync(local, token).ConfigureAwait(false));
|
||||
var tag = latest?.Tag ?? "";
|
||||
if (latest?.LinuxListUrl is { } listed && listed.StartsWith("https://", StringComparison.Ordinal))
|
||||
return ParseList(await http.GetStringAsync(listed, token).ConfigureAwait(false), local: false);
|
||||
if (tag.Length > 0 && tag.All(c => char.IsLetterOrDigit(c) || "._-".Contains(c)))
|
||||
{
|
||||
try
|
||||
{
|
||||
return ParseList(await http.GetStringAsync(BuildInfo.Downloads + "/releases/download/" + tag + "/" + BuildInfo.LinuxListAsset, token).ConfigureAwait(false), local: false);
|
||||
}
|
||||
catch (HttpRequestException) { }
|
||||
}
|
||||
return ParseList(await http.GetStringAsync(LatestList, token).ConfigureAwait(false), local: false);
|
||||
}
|
||||
}
|
||||
39
launcher/Logic/Log.cs
Normal file
39
launcher/Logic/Log.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>setup.log: what the launcher checked, downloaded and ran, for bug reports (old Setup.cs Program.Log). Windows: beside
|
||||
/// the installed launcher (<install>\setup.log, the old place); Linux: ${XDG_STATE_HOME}/triforce/setup.log. A line is
|
||||
/// "yyyy-MM-dd HH:mm:ss <text>"; the file is deleted once it is over 2 MiB. Nothing is written under NoWrites.</summary>
|
||||
public sealed class Log
|
||||
{
|
||||
readonly TriforceContext ctx;
|
||||
readonly object gate = new();
|
||||
internal Log(TriforceContext ctx) { this.ctx = ctx; }
|
||||
|
||||
/// <summary>Every line as it is written (the App may show them; a test reads them).</summary>
|
||||
public event Action<string>? Written;
|
||||
|
||||
public string FilePath => Path.Combine(ctx.Platform.LogFolder(ctx.Home), "setup.log");
|
||||
|
||||
public void Write(string line)
|
||||
{
|
||||
Written?.Invoke(line);
|
||||
if (ctx.NoWrites) return;
|
||||
try
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
var file = FilePath;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(file)!);
|
||||
if (File.Exists(file) && new FileInfo(file).Length > (2 << 20)) File.Delete(file);
|
||||
File.AppendAllText(file, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + line + Environment.NewLine);
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>The whole log, "" when there is none.</summary>
|
||||
public string ReadAll()
|
||||
{
|
||||
try { lock (gate) return File.Exists(FilePath) ? File.ReadAllText(FilePath) : ""; } catch (Exception) { return ""; }
|
||||
}
|
||||
}
|
||||
252
launcher/Logic/Mods/GameBanana.cs
Normal file
252
launcher/Logic/Mods/GameBanana.cs
Normal file
@@ -0,0 +1,252 @@
|
||||
// GameBanana's mods for this game (ported from the game's own Mods menu, gpu/vk/vk_mods.cpp; research/02 7.3):
|
||||
// the section https://gamebanana.com/apiv11/Game/26242/Subfeed?_sSort=default&_csvModelInclusions=Mod,Wip&_nPage=<n>
|
||||
// a search .../apiv11/Util/Search/Results?_sModelName=Mod&_idGameRow=26242&_sOrder=best_match&_nPage=<n>&_sSearchString=<q>
|
||||
// (+ the WiPs' first page, _sModelName=Wip: GameBanana's search takes one kind a request), and when the
|
||||
// whole-word search finds nothing, the section's name filter: Subfeed...&_nPage=<n>&_sName=<q> (3 letters at least)
|
||||
// the details .../apiv11/<Mod|Wip>/<id>/ProfilePage (_aFiles[]: _idRow, _sFile, _sDescription, _sDownloadUrl, _nFilesize,
|
||||
// _tsDateAdded; _sText the description as HTML; _nDownloadCount)
|
||||
// Mods and WiPs: a WiP with files is often a mod all the same, and the online co-op kit is posted as one. A WiP with nothing to
|
||||
// download (_bHasFiles false) is left out; a record of another game (_aGame._idRow) too. A page that fails with cards already
|
||||
// listed is tried again after 2, 4 and 8 s (the first page's failure is shown at once, as in the game).
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>A card: one mod or WiP of the section.</summary>
|
||||
public sealed record GbMod(int Id, bool Wip, string Name, string Author, string Category, string? Page, int Likes, int Views, long Updated, string? ThumbUrl)
|
||||
{
|
||||
/// <summary>A program of its own (Kits): installed into kits\<folder> and started, not put in mods.</summary>
|
||||
public bool IsKit => Kits.Find(Wip, Id) != null;
|
||||
}
|
||||
|
||||
public sealed record GbFile(int Id, string Name, string Description, string Url, long Bytes, long Added);
|
||||
|
||||
public sealed record GbDetails(int Id, bool Wip, string Text, int Downloads, IReadOnlyList<GbFile> Files)
|
||||
{
|
||||
/// <summary>The file to offer first: a kit's Windows file (Squadala posts a -windows and a -linux zip), else the first.</summary>
|
||||
public int DefaultFile(bool isKit)
|
||||
{
|
||||
if (isKit)
|
||||
for (var k = 0; k < Files.Count; k++)
|
||||
if (Files[k].Name.Contains(OperatingSystem.IsWindows() ? "windows" : "linux", StringComparison.OrdinalIgnoreCase)) return k;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record GbPage(IReadOnlyList<GbMod> Mods, int Page, int Total, bool Complete, bool NameFilter);
|
||||
|
||||
public sealed class GameBanana
|
||||
{
|
||||
/// <summary>GameBanana's game: The Legend of Zelda: Ocarina of Time (Switch 2).</summary>
|
||||
public const int GameId = 26242;
|
||||
const string Api = "https://gamebanana.com/apiv11";
|
||||
|
||||
readonly HttpClient http;
|
||||
public GameBanana(HttpClient? http = null)
|
||||
{
|
||||
this.http = http ?? Create();
|
||||
}
|
||||
|
||||
/// <summary>The waits before a failed page is asked again (old: 2, 4, 8 s).</summary>
|
||||
public TimeSpan[] RetryDelays { get; set; } = { TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(8) };
|
||||
|
||||
public static HttpClient Create()
|
||||
{
|
||||
// (GameBanana's /dl/ links send to its file server: redirects followed. 15 s to connect, 60 s for an answer as WinHTTP had)
|
||||
var h = new HttpClient(new SocketsHttpHandler { AllowAutoRedirect = true, ConnectTimeout = TimeSpan.FromSeconds(15), AutomaticDecompression = System.Net.DecompressionMethods.All })
|
||||
{ Timeout = Timeout.InfiniteTimeSpan };
|
||||
h.DefaultRequestHeaders.UserAgent.ParseAdd("Triforce-mod-browser/" + BuildInfo.Version);
|
||||
h.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
h.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*", 0.8));
|
||||
return h;
|
||||
}
|
||||
|
||||
public static string ListUrl(int page) => Api + "/Game/" + GameId + "/Subfeed?_sSort=default&_csvModelInclusions=Mod,Wip&_nPage=" + page;
|
||||
public static string SearchUrl(bool wip, int page, string query) =>
|
||||
Api + "/Util/Search/Results?_sModelName=" + (wip ? "Wip" : "Mod") + "&_idGameRow=" + GameId + "&_sOrder=best_match&_nPage=" + page + "&_sSearchString=" + UrlEncode(query);
|
||||
public static string NameFilterUrl(int page, string query) => ListUrl(page) + "&_sName=" + UrlEncode(query);
|
||||
public static string ProfileUrl(bool wip, int id) => Api + "/" + (wip ? "Wip" : "Mod") + "/" + id + "/ProfilePage";
|
||||
|
||||
/// <summary>A search's text in a URL: its UTF-8 bytes, letters, digits and - _ . ~ as they are, the rest %XX (sent in another
|
||||
/// code page GameBanana drops every filter, and & or + cut or change the query).</summary>
|
||||
public static string UrlEncode(string s)
|
||||
{
|
||||
var o = new StringBuilder();
|
||||
foreach (var b in Encoding.UTF8.GetBytes(s))
|
||||
{
|
||||
var c = (char)b;
|
||||
if (c is >= '0' and <= '9' or >= 'A' and <= 'Z' or >= 'a' and <= 'z' or '-' or '_' or '.' or '~') o.Append(c);
|
||||
else o.Append('%').Append(b.ToString("X2"));
|
||||
}
|
||||
return o.ToString();
|
||||
}
|
||||
|
||||
async Task<string> GetTextAsync(string url, CancellationToken token)
|
||||
{
|
||||
using var r = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false);
|
||||
if (!r.IsSuccessStatusCode) throw new HttpRequestException("GameBanana answered " + (int)r.StatusCode, null, r.StatusCode);
|
||||
return await r.Content.ReadAsStringAsync(token).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
async Task<string> GetWithRetriesAsync(string url, bool retry, CancellationToken token)
|
||||
{
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
try { return await GetTextAsync(url, token).ConfigureAwait(false); }
|
||||
catch (Exception) when (retry && attempt < RetryDelays.Length && !token.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(RetryDelays[attempt], token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One page of the section (15 records a page), newest activity first.</summary>
|
||||
public async Task<GbPage> ListAsync(int page, CancellationToken token = default) =>
|
||||
ParsePage(await GetWithRetriesAsync(ListUrl(page), page > 1, token).ConfigureAwait(false), null, page, false);
|
||||
|
||||
/// <summary>A search: GameBanana's own (whole words, best matches first, the WiPs' first page with the mods' first); when that
|
||||
/// finds nothing on its first page and the text has 3 letters or more, the section's name filter (a part of a name: "majora",
|
||||
/// "zeld"). nameFilter: ask the name filter's page directly (the next pages of a search that went there).</summary>
|
||||
public async Task<GbPage> SearchAsync(string query, int page, bool nameFilter = false, CancellationToken token = default)
|
||||
{
|
||||
query = query.Trim();
|
||||
if (nameFilter) return ParsePage(await GetWithRetriesAsync(NameFilterUrl(page, query), page > 1, token).ConfigureAwait(false), null, page, true);
|
||||
var mods = await GetWithRetriesAsync(SearchUrl(false, page, query), page > 1, token).ConfigureAwait(false);
|
||||
string? wips = null;
|
||||
if (page == 1)
|
||||
try { wips = await GetTextAsync(SearchUrl(true, 1, query), token).ConfigureAwait(false); }
|
||||
catch (Exception) when (!token.IsCancellationRequested) { } // (the WiPs could not be read: the mods alone)
|
||||
var got = ParsePage(mods, wips, page, false);
|
||||
if (page == 1 && got.Mods.Count == 0 && got.Complete && query.Length >= 3)
|
||||
return ParsePage(await GetWithRetriesAsync(NameFilterUrl(1, query), false, token).ConfigureAwait(false), null, 1, true);
|
||||
return got;
|
||||
}
|
||||
|
||||
/// <summary>A page's records as cards: mods and WiPs only, a WiP with nothing to download left out, another game's records
|
||||
/// left out, the same mod once. Total and Complete from _aMetadata.</summary>
|
||||
public static GbPage ParsePage(string json, string? wipJson, int page, bool nameFilter)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
using var wdoc = wipJson != null ? TryParse(wipJson) : null;
|
||||
var j = doc.RootElement;
|
||||
var meta = Get(j, "_aMetadata");
|
||||
var total = (int)Num(meta, "_nRecordCount") + (wdoc != null ? (int)Num(Get(wdoc.RootElement, "_aMetadata"), "_nRecordCount") : 0);
|
||||
var complete = meta.ValueKind == JsonValueKind.Object && meta.TryGetProperty("_bIsComplete", out var c) && c.ValueKind == JsonValueKind.True;
|
||||
var list = new List<GbMod>();
|
||||
var records = new List<JsonElement>();
|
||||
if (Get(j, "_aRecords") is { ValueKind: JsonValueKind.Array } a) records.AddRange(a.EnumerateArray());
|
||||
if (wdoc != null && Get(wdoc.RootElement, "_aRecords") is { ValueKind: JsonValueKind.Array } w) records.AddRange(w.EnumerateArray());
|
||||
foreach (var r in records)
|
||||
{
|
||||
if (r.ValueKind != JsonValueKind.Object) continue;
|
||||
var model = Str(r, "_sModelName");
|
||||
if (model != "Mod" && model != "Wip") continue; // (the section's requests, questions and tools: not mods)
|
||||
if (model == "Wip" && r.TryGetProperty("_bHasFiles", out var hf) && hf.ValueKind == JsonValueKind.False) continue;
|
||||
if (Get(r, "_aGame") is { ValueKind: JsonValueKind.Object } g && Num(g, "_idRow") != GameId) continue;
|
||||
var id = (int)Num(r, "_idRow");
|
||||
var wip = model == "Wip";
|
||||
if (list.Any(o => o.Id == id && o.Wip == wip)) continue;
|
||||
string? thumb = null;
|
||||
if (Get(Get(r, "_aPreviewMedia"), "_aImages") is { ValueKind: JsonValueKind.Array } imgs && imgs.GetArrayLength() > 0 && imgs[0] is { ValueKind: JsonValueKind.Object } img)
|
||||
{
|
||||
// (530 wide when GameBanana made that size: sharp in the details; the cards draw it smaller)
|
||||
var file = Str(img, "_sFile530") is { Length: > 0 } f530 ? f530 : Str(img, "_sFile220") is { Length: > 0 } f220 ? f220 : Str(img, "_sFile");
|
||||
thumb = Str(img, "_sBaseUrl") + "/" + file;
|
||||
}
|
||||
var updated = Num(r, "_tsDateModified") is var m && m != 0 ? m : Num(r, "_tsDateAdded");
|
||||
list.Add(new GbMod(id, wip, Str(r, "_sName"), Str(Get(r, "_aSubmitter"), "_sName"), Str(Get(r, "_aRootCategory"), "_sName"), Str(r, "_sProfileUrl") is { Length: > 0 } p ? p : null,
|
||||
(int)Num(r, "_nLikeCount"), (int)Num(r, "_nViewCount"), updated, thumb));
|
||||
}
|
||||
return new GbPage(list, page, total, complete, nameFilter);
|
||||
}
|
||||
|
||||
static JsonDocument? TryParse(string s) { try { return JsonDocument.Parse(s); } catch (Exception) { return null; } }
|
||||
static JsonElement Get(JsonElement o, string name) => o.ValueKind == JsonValueKind.Object && o.TryGetProperty(name, out var v) ? v : default;
|
||||
static string Str(JsonElement o, string name) => Get(o, name) is var v && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : v.ValueKind == JsonValueKind.Number ? v.GetRawText() : "";
|
||||
static long Num(JsonElement o, string name) => Get(o, name) is var v && v.ValueKind == JsonValueKind.Number ? (v.TryGetInt64(out var n) ? n : (long)v.GetDouble())
|
||||
: v.ValueKind == JsonValueKind.String && long.TryParse(v.GetString(), out var s) ? s : 0;
|
||||
|
||||
/// <summary>A mod's details: its files (those with a download link), its description as plain text, its downloads.</summary>
|
||||
public async Task<GbDetails> DetailsAsync(int id, bool wip, CancellationToken token = default)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(await GetTextAsync(ProfileUrl(wip, id), token).ConfigureAwait(false));
|
||||
return ParseDetails(doc.RootElement, id, wip);
|
||||
}
|
||||
|
||||
public static GbDetails ParseDetails(JsonElement j, int id, bool wip)
|
||||
{
|
||||
var files = new List<GbFile>();
|
||||
if (Get(j, "_aFiles") is { ValueKind: JsonValueKind.Array } a)
|
||||
foreach (var f in a.EnumerateArray())
|
||||
{
|
||||
var url = Str(f, "_sDownloadUrl");
|
||||
if (url.Length > 0) files.Add(new GbFile((int)Num(f, "_idRow"), Str(f, "_sFile"), Str(f, "_sDescription"), url, Num(f, "_nFilesize"), Num(f, "_tsDateAdded")));
|
||||
}
|
||||
return new GbDetails(id, wip, Plain(Str(j, "_sText")), (int)Num(j, "_nDownloadCount"), files);
|
||||
}
|
||||
|
||||
/// <summary>A card's picture's bytes (at most 8 MB); the App decodes it.</summary>
|
||||
public async Task<byte[]> ThumbnailAsync(string url, CancellationToken token = default)
|
||||
{
|
||||
if (!url.StartsWith("https://", StringComparison.Ordinal)) throw new ArgumentException("not an https link");
|
||||
using var r = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false);
|
||||
r.EnsureSuccessStatusCode();
|
||||
await using var s = await r.Content.ReadAsStreamAsync(token).ConfigureAwait(false);
|
||||
using var m = new MemoryStream();
|
||||
var buf = new byte[1 << 16];
|
||||
for (int n; (n = await s.ReadAsync(buf, token).ConfigureAwait(false)) > 0;)
|
||||
{
|
||||
m.Write(buf, 0, n);
|
||||
if (m.Length > 8 << 20) throw new InvalidDataException("the picture is larger than 8 MB");
|
||||
}
|
||||
return m.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>GameBanana's descriptions are HTML: the text alone, a line where a paragraph or a break was (vk_mods.cpp plain).</summary>
|
||||
public static string Plain(string html)
|
||||
{
|
||||
var o = new StringBuilder();
|
||||
string[][] ents =
|
||||
{
|
||||
new[] { "&", "&" }, new[] { "<", "<" }, new[] { ">", ">" }, new[] { """, "\"" }, new[] { "'", "'" }, new[] { "'", "'" },
|
||||
new[] { " ", " " }, new[] { "’", "’" }, new[] { "‘", "‘" }, new[] { "“", "“" }, new[] { "”", "”" },
|
||||
new[] { "…", "..." }, new[] { "—", "—" }, new[] { "–", "–" },
|
||||
};
|
||||
for (var i = 0; i < html.Length;)
|
||||
{
|
||||
if (html[i] == '<')
|
||||
{
|
||||
var end = html.IndexOf('>', i);
|
||||
if (end < 0) break;
|
||||
var tag = html.Substring(i + 1, end - i - 1).ToLowerInvariant();
|
||||
if (tag.StartsWith("br") || tag.StartsWith("/p") || tag.StartsWith("/li") || tag.StartsWith("/h") || tag.StartsWith("/div")) o.Append('\n');
|
||||
else if (tag.StartsWith("li")) o.Append("- ");
|
||||
i = end + 1;
|
||||
continue;
|
||||
}
|
||||
if (html[i] == '&')
|
||||
{
|
||||
var hit = ents.FirstOrDefault(e => string.CompareOrdinal(html, i, e[0], 0, e[0].Length) == 0);
|
||||
if (hit != null) { o.Append(hit[1]); i += hit[0].Length; continue; }
|
||||
}
|
||||
o.Append(html[i++]);
|
||||
}
|
||||
// (runs of blank lines and spaces: one each)
|
||||
var tidy = new StringBuilder();
|
||||
var newlines = 0;
|
||||
var space = false;
|
||||
foreach (var ch in o.ToString())
|
||||
{
|
||||
var c = ch == '\r' || ch == '\t' ? ' ' : ch;
|
||||
if (c == '\n') { if (++newlines <= 2 && tidy.Length > 0) tidy.Append('\n'); space = false; continue; }
|
||||
if (c == ' ') { if (!space && tidy.Length > 0 && tidy[^1] != '\n') tidy.Append(' '); space = true; continue; }
|
||||
newlines = 0;
|
||||
space = false;
|
||||
tidy.Append(c);
|
||||
}
|
||||
var s = tidy.ToString().TrimEnd('\n', ' ');
|
||||
return s.Length > 1400 ? s.Substring(0, 1400) + "..." : s;
|
||||
}
|
||||
}
|
||||
287
launcher/Logic/Mods/GameBananaInstaller.cs
Normal file
287
launcher/Logic/Mods/GameBananaInstaller.cs
Normal file
@@ -0,0 +1,287 @@
|
||||
// Installing what GameBanana offers (vk_mods.cpp run_install / run_kit), with the launcher's own checked unpacking (ModManager:
|
||||
// names, links, sizes, room) where the game used tar.exe as is.
|
||||
// a mod downloaded into mods\.triforce-download, unpacked there, each folder holding romfs (or exefs) found (five levels down;
|
||||
// a folder of the game's own RomFS folders with no romfs above them is wrapped in one), then moved into mods\NN-<name>
|
||||
// with triforce_mod.json beside it. A reinstall or an update replaces the folders this mod had and keeps the first one's
|
||||
// place in the order and its on/off; several roots are the mod's options: the first on, the others off (_).
|
||||
// a kit (Kits: an allow-list, never what a download holds) unpacked into kits\<folder>, its start file found (three levels
|
||||
// down), its files moved over what is there (the kit's own settings stay), triforce_kit.json written, then its start file
|
||||
// run in a console of its own. Windows only, as in the game.
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>A program of its own posted in the section, not a romfs mod.</summary>
|
||||
public sealed record Kit(bool Wip, int Id, string Folder, string Start);
|
||||
|
||||
public static class Kits
|
||||
{
|
||||
/// <summary>((Triforce) 11-18, "make sure the multiplayer mod is included": daurosk's Squadala!, online co-op,
|
||||
/// github.com/daurosk/oot-remake-multiplayer.) Only the ones named here: a download is never started because of what it holds.</summary>
|
||||
public static readonly IReadOnlyList<Kit> All = new[] { new Kit(true, 105323, "Squadala", "Start Squadala.bat") };
|
||||
|
||||
public static Kit? Find(bool wip, int id) => All.FirstOrDefault(k => k.Wip == wip && k.Id == id);
|
||||
}
|
||||
|
||||
/// <summary>A mod or kit that came from GameBanana, as its json says (id, WiP or Mod, the file's date).</summary>
|
||||
public sealed record InstalledMod(int Id, bool Wip, long FileDate, string Folder);
|
||||
|
||||
public sealed class GameBananaInstaller
|
||||
{
|
||||
readonly TriforceContext ctx;
|
||||
readonly ModManager mods;
|
||||
public GameBananaInstaller(TriforceContext ctx, ModManager? mods = null)
|
||||
{
|
||||
this.ctx = ctx;
|
||||
this.mods = mods ?? new ModManager(ctx);
|
||||
}
|
||||
|
||||
static readonly string[] RomfsDirs = { "Model", "UI", "Tex", "Pack", "Sound", "Event", "Banc", "Effect", "Mals", "Font2", "Logic", "Phive", "Scene", "System", "GameData", "Voice", "Movie", "AS", "AI", "Game", "Env" };
|
||||
|
||||
/// <summary>What came from GameBanana into this game folder: mods (triforce_mod.json) and kits (triforce_kit.json).</summary>
|
||||
public IReadOnlyList<InstalledMod> Installed(string game)
|
||||
{
|
||||
var o = new List<InstalledMod>();
|
||||
var root = Mods.FolderOf(game);
|
||||
if (Directory.Exists(root))
|
||||
foreach (var d in Directory.GetDirectories(root))
|
||||
{
|
||||
if (Path.GetFileName(d).StartsWith('.')) continue;
|
||||
if (ModManager.ReadInfo(d) is { GameBananaId: > 0 } i) o.Add(new InstalledMod((int)i.GameBananaId, i.Wip, i.FileDate, d));
|
||||
}
|
||||
foreach (var k in Kits.All)
|
||||
{
|
||||
var dir = Path.Combine(game, "kits", k.Folder);
|
||||
if (ReadJson(Path.Combine(dir, "triforce_kit.json")) is { } j && j.Id == k.Id) o.Add(new InstalledMod(k.Id, k.Wip, j.Date, dir));
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
/// <summary>Installed, and is there a newer file (an "Update" mark): newest file date > the one installed.</summary>
|
||||
public (bool Installed, bool Update) State(string game, GbMod m, GbDetails? d)
|
||||
{
|
||||
var hit = Installed(game).FirstOrDefault(i => i.Id == m.Id && i.Wip == m.Wip);
|
||||
if (hit == null) return (false, false);
|
||||
var newest = d?.Files.Count > 0 ? d.Files.Max(f => f.Added) : 0;
|
||||
return (true, newest > hit.FileDate && hit.FileDate > 0);
|
||||
}
|
||||
|
||||
static (long Id, long Date)? ReadJson(string file)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(file)) return null;
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(file));
|
||||
var r = doc.RootElement;
|
||||
long N(string n) => r.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out var x) ? x : 0;
|
||||
return (N("gamebanana_id"), N("file_date"));
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
/// <summary>A folder name: no characters Windows refuses, never "off" by its name, at most 60 characters (vk_mods.cpp safe_name).</summary>
|
||||
public static string SafeName(string name)
|
||||
{
|
||||
var s = new string(name.Where(c => c >= 32 && "<>:\"/\\|?*".IndexOf(c) < 0).ToArray());
|
||||
s = s.TrimEnd('.', ' ').TrimStart('_', '-', '.', ' ');
|
||||
if (s.Length > 60) s = s.Substring(0, 60);
|
||||
s = s.TrimEnd('.', ' ');
|
||||
return s.Length == 0 ? "mod" : s;
|
||||
}
|
||||
|
||||
static string InfoJson(string name, GbMod m, GbFile f, bool kit) => JsonSerializer.Serialize(new Dictionary<string, object?>
|
||||
{
|
||||
["name"] = name, ["author"] = m.Author, ["page"] = m.Page, ["gamebanana_id"] = m.Id,
|
||||
["gamebanana_model"] = kit || m.Wip ? (m.Wip ? "Wip" : "Mod") : null,
|
||||
["file"] = f.Name, ["file_date"] = f.Added, ["installed_by"] = "Triforce's launcher",
|
||||
}.Where(kv => kv.Value != null).ToDictionary(kv => kv.Key, kv => kv.Value), new JsonSerializerOptions { WriteIndented = true }) + "\n";
|
||||
|
||||
/// <summary>Downloads and installs one of a mod's files; a kit goes to kits and is started. Returns the sentence the App shows.
|
||||
/// Refused while the game runs.</summary>
|
||||
public async Task<string> InstallAsync(HttpClient http, GbMod m, GbFile f, string game, Action<DownloadProgress>? progress, CancellationToken token)
|
||||
{
|
||||
if (Kits.Find(m.Wip, m.Id) is { } kit) return await InstallKitAsync(http, m, f, game, kit, progress, token).ConfigureAwait(false);
|
||||
if (mods.GameRuns(game)) throw new ModsException("Close the game first. Mods are added, switched, ordered and removed only while it is not running.");
|
||||
var root = Mods.FolderOf(game);
|
||||
var stage = Path.Combine(root, ".triforce-download");
|
||||
ctx.Require(stage);
|
||||
var unpacked = await DownloadUnpackAsync(http, m, f, root, stage, progress, token).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var (roots, bare) = FindRoots(unpacked);
|
||||
if (roots.Count == 0 && bare.Count > 0) // (packed without a romfs folder: one made around the game's folders)
|
||||
{
|
||||
var made = Path.Combine(stage, "wrapped");
|
||||
Directory.CreateDirectory(made);
|
||||
Directory.Move(bare[0], Path.Combine(made, "romfs"));
|
||||
roots.Add(made);
|
||||
}
|
||||
if (roots.Count == 0)
|
||||
throw new ModsException("This download has no romfs folder in it, so it is not a mod Triforce can load (it may need its own installer, or be for another version of the game).");
|
||||
// (a reinstall or an update: the folders this mod had go, and the new one takes the first one's place and its on or off)
|
||||
var number = 0;
|
||||
var wasOff = false;
|
||||
var old = new List<string>();
|
||||
foreach (var d in Directory.GetDirectories(root).OrderBy(x => x, StringComparer.Ordinal))
|
||||
{
|
||||
var name = Path.GetFileName(d);
|
||||
if (name.StartsWith('.')) continue;
|
||||
if (ModManager.ReadInfo(d) is not { } info || info.GameBananaId != m.Id) continue;
|
||||
if (old.Count == 0)
|
||||
{
|
||||
var (off, num, _) = Mods.Parse(name);
|
||||
wasOff = off;
|
||||
number = num ?? 0;
|
||||
}
|
||||
old.Add(d);
|
||||
}
|
||||
var aside = new List<(string Was, string Gone)>();
|
||||
for (var k = 0; k < old.Count; k++) // (out of the way first: removed once the new one is in, put back if it fails)
|
||||
{
|
||||
var gone = Path.Combine(stage, "old-" + k);
|
||||
try { Directory.Move(old[k], gone); aside.Add((old[k], gone)); } catch (Exception e) { ctx.Log.Write("mods: the old " + old[k] + " could not be moved aside: " + e.Message); }
|
||||
}
|
||||
var label0 = SafeName(m.Name);
|
||||
if (number == 0) number = NextNumber(root);
|
||||
var placed = new List<string>();
|
||||
string? err = null;
|
||||
for (var i = 0; i < roots.Count; i++)
|
||||
{
|
||||
var label = label0;
|
||||
if (roots.Count > 1 && !TriforceContext.SamePath(roots[i], unpacked)) label += " - " + SafeName(Path.GetFileName(roots[i]));
|
||||
var prefix = (i > 0 || wasOff ? "_" : "") + (number++).ToString("00") + "-";
|
||||
var target = Path.Combine(root, prefix + label);
|
||||
for (var k = 2; Directory.Exists(target); k++) target = Path.Combine(root, prefix + label + " (" + k + ")");
|
||||
try { ctx.Require(target); Directory.Move(roots[i], target); }
|
||||
catch (Exception e) { err = "could not move it into " + target + " (" + e.Message + ")"; break; }
|
||||
File.WriteAllText(Path.Combine(target, "triforce_mod.json"), InfoJson(roots.Count > 1 ? label : m.Name, m, f, false));
|
||||
placed.Add(target);
|
||||
}
|
||||
if (placed.Count == 0)
|
||||
{
|
||||
foreach (var (was, gone) in aside) try { Directory.Move(gone, was); } catch (Exception) { }
|
||||
throw new ModsException("It could not be installed: " + err + "." + (aside.Count == 0 ? "" : " The one installed before is kept."));
|
||||
}
|
||||
if (placed.Select(p => mods.List(root).FirstOrDefault(x => TriforceContext.SamePath(x.Path, p))).Any(x => x is { Built: true }) && mods.BuiltMark(game) == null)
|
||||
mods.MarkChanged(game);
|
||||
ctx.Log.Write("mods: installed " + m.Name + " (" + m.Id + ") into " + placed.Count + " folder(s), the first " + placed[0]);
|
||||
var msg = "Installed into mods" + Path.DirectorySeparatorChar + Path.GetFileName(placed[0]) + ".";
|
||||
if (placed.Count > 1) msg += " It came with " + placed.Count + " options: the first is on, the others are off. Choose on the Mods page.";
|
||||
return msg;
|
||||
}
|
||||
finally { Partial.Remove(stage); }
|
||||
}
|
||||
|
||||
/// <summary>The file downloaded into stage (made anew) and unpacked into stage\unpacked with the checked unpacking.</summary>
|
||||
async Task<string> DownloadUnpackAsync(HttpClient http, GbMod m, GbFile f, string within, string stage, Action<DownloadProgress>? progress, CancellationToken token)
|
||||
{
|
||||
Partial.Remove(stage);
|
||||
Directory.CreateDirectory(stage);
|
||||
try { File.SetAttributes(stage, File.GetAttributes(stage) | FileAttributes.Hidden); } catch (Exception) { }
|
||||
var name = SafeName(f.Name.Length == 0 ? "mod.zip" : f.Name);
|
||||
var archive = Path.Combine(stage, name);
|
||||
ctx.Log.Write("mods: installing " + m.Name + " (" + m.Id + "), file " + f.Name + " (" + f.Bytes + " bytes) from " + f.Url);
|
||||
try
|
||||
{
|
||||
// (the size the server names: GameBanana's listed size is not trusted to the byte)
|
||||
await new Downloader(ctx).ToFileAsync(http, f.Url, archive, 0, progress, token).ConfigureAwait(false);
|
||||
var unpacked = Path.Combine(stage, "unpacked");
|
||||
await Task.Run(() => mods.Unpack(within, archive, unpacked, null), token).ConfigureAwait(false);
|
||||
return unpacked;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Partial.Remove(stage);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The folders holding romfs (or exefs) under dir, five levels down; a folder of the game's RomFS folders with no romfs
|
||||
/// above them counts as a romfs itself (bare).</summary>
|
||||
static (List<string> Roots, List<string> Bare) FindRoots(string dir)
|
||||
{
|
||||
var roots = new List<string>();
|
||||
var bare = new List<string>();
|
||||
void Look(string d, int depth)
|
||||
{
|
||||
if (Directory.Exists(Path.Combine(d, "romfs")) || Directory.Exists(Path.Combine(d, "exefs"))) { roots.Add(d); return; }
|
||||
var subs = Directory.GetDirectories(d).OrderBy(x => x, StringComparer.Ordinal).ToList();
|
||||
if (subs.Any(s => RomfsDirs.Any(r => string.Equals(Path.GetFileName(s), r, StringComparison.OrdinalIgnoreCase)))) { bare.Add(d); return; }
|
||||
if (depth >= 5) return;
|
||||
foreach (var s in subs) Look(s, depth + 1);
|
||||
}
|
||||
Look(dir, 0);
|
||||
return (roots, bare);
|
||||
}
|
||||
|
||||
/// <summary>After the highest "NN-" there: a new mod wins over those installed before.</summary>
|
||||
static int NextNumber(string root)
|
||||
{
|
||||
var hi = 0;
|
||||
foreach (var d in Directory.GetDirectories(root))
|
||||
if (Mods.Parse(Path.GetFileName(d)).Number is { } n) hi = Math.Max(hi, n);
|
||||
return hi + 1;
|
||||
}
|
||||
|
||||
async Task<string> InstallKitAsync(HttpClient http, GbMod m, GbFile f, string game, Kit k, Action<DownloadProgress>? progress, CancellationToken token)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) throw new ModsException(m.Name + " is not available on Linux from the launcher yet: download it from its page and follow its own steps.");
|
||||
var kits = Path.Combine(game, "kits");
|
||||
var dir = Path.Combine(kits, k.Folder);
|
||||
var stage = Path.Combine(kits, ".triforce-download");
|
||||
ctx.Require(stage);
|
||||
// (this file installed already, and its start file there: started again, nothing downloaded)
|
||||
var have = ReadJson(Path.Combine(dir, "triforce_kit.json")) is { } j && j.Id == k.Id && j.Date >= f.Added && File.Exists(Path.Combine(dir, k.Start));
|
||||
if (!have)
|
||||
{
|
||||
ctx.Log.Write("mods: " + m.Name + " is a kit: into " + dir);
|
||||
var unpacked = await DownloadUnpackAsync(http, m, f, kits, stage, progress, token).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var top = FindKitTop(unpacked, k.Start, 0)
|
||||
?? throw new ModsException("This download has no \"" + k.Start + "\" in it: GameBanana's file may have changed. Nothing was installed.");
|
||||
try { MoveOver(top, dir); }
|
||||
catch (Exception e) { throw new ModsException("It could not be put into kits\\" + k.Folder + ": " + e.Message + ". If " + m.Name + " is running, close it and try again."); }
|
||||
File.WriteAllText(Path.Combine(dir, "triforce_kit.json"), InfoJson(m.Name, m, f, true));
|
||||
}
|
||||
finally { Partial.Remove(stage); }
|
||||
}
|
||||
if (!ctx.Allowed(dir)) throw new ModsException(ctx.TestOnly);
|
||||
try
|
||||
{
|
||||
// (the kit's start file run in a console of its own, from its folder: cmd /c, a .bat or any start file Windows runs)
|
||||
var cmd = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "cmd.exe");
|
||||
Process.Start(new ProcessStartInfo(cmd, "/c \"\"" + Path.Combine(dir, k.Start) + "\"\"") { UseShellExecute = false, CreateNoWindow = false, WorkingDirectory = dir })?.Dispose();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new ModsException(k.Start + " could not be started (" + e.Message + "). It is in kits\\" + k.Folder + " beside the game: start it from there.");
|
||||
}
|
||||
ctx.Log.Write("mods: kit " + m.Name + " " + (have ? "installed already" : "installed") + ", started: " + Path.Combine(dir, k.Start));
|
||||
return (have ? "Started" : "Installed into kits\\" + k.Folder + " and started") + " in a window of its own. Follow its steps there.";
|
||||
}
|
||||
|
||||
/// <summary>The folder under dir (dir itself, or 3 levels down at most) whose files hold the kit's start file.</summary>
|
||||
static string? FindKitTop(string dir, string start, int depth)
|
||||
{
|
||||
if (Directory.GetFiles(dir).Any(f => string.Equals(Path.GetFileName(f), start, StringComparison.OrdinalIgnoreCase))) return dir;
|
||||
if (depth >= 3) return null;
|
||||
foreach (var d in Directory.GetDirectories(dir).OrderBy(x => x, StringComparer.Ordinal))
|
||||
if (FindKitTop(d, start, depth + 1) is { } t) return t;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>from's files moved over into's (folders made, files there replaced; what into has more stays: the kit's own settings).</summary>
|
||||
static void MoveOver(string from, string into)
|
||||
{
|
||||
Directory.CreateDirectory(into);
|
||||
foreach (var f in Directory.GetFiles(from))
|
||||
{
|
||||
var to = Path.Combine(into, Path.GetFileName(f));
|
||||
if (File.Exists(to)) File.SetAttributes(to, FileAttributes.Normal);
|
||||
File.Move(f, to, true);
|
||||
}
|
||||
foreach (var d in Directory.GetDirectories(from)) MoveOver(d, Path.Combine(into, Path.GetFileName(d)));
|
||||
}
|
||||
}
|
||||
640
launcher/Logic/Mods/ModManager.cs
Normal file
640
launcher/Logic/Mods/ModManager.cs
Normal file
@@ -0,0 +1,640 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO.Compression;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>A game folder's mods folder: list, on/off, order, remove, add from an archive, and the "Build again to apply" mark
|
||||
/// (old Mods.cs and Shell.Mods.cs, with their hooks as instance settings rather than statics).</summary>
|
||||
public sealed class ModManager
|
||||
{
|
||||
readonly TriforceContext ctx;
|
||||
public ModManager(TriforceContext ctx)
|
||||
{
|
||||
this.ctx = ctx;
|
||||
GameRuns = folder => new Game(ctx).IsRunning(folder);
|
||||
Tar = DefaultTar;
|
||||
}
|
||||
|
||||
/// <summary>The most an archive may unpack to, and the most files it may hold (the game's own RomFS is 12 GB in 18,000 files).</summary>
|
||||
public long MaxBytes { get; set; } = 32L << 30;
|
||||
public int MaxFiles { get; set; } = 200000;
|
||||
/// <summary>Does the game of this game folder run? Asked before every change (a test puts its own answer here).</summary>
|
||||
public Func<string, bool> GameRuns { get; set; }
|
||||
/// <summary>The tar that reads .7z and .rar: Windows' own System32\tar.exe (bsdtar), never whatever "tar" the PATH names; Linux
|
||||
/// bsdtar (libarchive) when installed: GNU tar reads neither. Null: none.</summary>
|
||||
public Func<string?> Tar { get; set; }
|
||||
|
||||
static string? DefaultTar()
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
var tar = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "tar.exe");
|
||||
return File.Exists(tar) ? tar : null;
|
||||
}
|
||||
foreach (var p in new[] { "/usr/bin/bsdtar", "/bin/bsdtar", "/usr/local/bin/bsdtar" })
|
||||
if (File.Exists(p)) return p;
|
||||
return null;
|
||||
}
|
||||
|
||||
static StringComparison PathCase => OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
static bool Same(string a, string b) => string.Equals(a, b, PathCase);
|
||||
static string Hex8() => Guid.NewGuid().ToString("N").Substring(0, 8);
|
||||
static string Full(string path) => Path.GetFullPath(path).TrimEnd('\\', '/');
|
||||
static char Sep => Path.DirectorySeparatorChar;
|
||||
|
||||
// ---- only inside the mods folder ----
|
||||
|
||||
/// <summary>Is the path the mods folder or inside it? Every folder made, renamed or written to is asked this first.</summary>
|
||||
public static bool Inside(string mods, string path) => TriforceContext.Inside(mods, path);
|
||||
|
||||
void Within(string mods, string path)
|
||||
{
|
||||
if (!Inside(mods, path)) throw new InvalidOperationException("The launcher would have written outside the mods folder (" + path + "), and did not.");
|
||||
ctx.Require(path);
|
||||
}
|
||||
|
||||
void MakeFolder(string mods, string dir)
|
||||
{
|
||||
Within(mods, dir);
|
||||
Directory.CreateDirectory(dir);
|
||||
}
|
||||
|
||||
void MoveFolder(string mods, string from, string to)
|
||||
{
|
||||
Within(mods, from);
|
||||
Within(mods, to);
|
||||
Directory.Move(from, to);
|
||||
}
|
||||
|
||||
void Refuse(string mods)
|
||||
{
|
||||
if (GameRuns(Path.GetDirectoryName(Full(mods)) ?? mods))
|
||||
throw new ModsException("Close the game first. Mods are added, switched, ordered and removed only while it is not running.");
|
||||
}
|
||||
|
||||
static string[] Folders(string dir)
|
||||
{
|
||||
try { return Directory.GetDirectories(dir); } catch (Exception) { return Array.Empty<string>(); }
|
||||
}
|
||||
|
||||
// ---- the list ----
|
||||
|
||||
/// <summary>The mods of a mods folder as the game finds them (host/mods.c find_mods), those that are off too, in the order the
|
||||
/// game loads them: the last one wins a file two of them carry. carried: false leaves out what each mod carries.</summary>
|
||||
public List<Mod> List(string mods, bool carried = true)
|
||||
{
|
||||
var found = new List<Mod>();
|
||||
if (Directory.Exists(mods)) Walk(mods, "", 0, null, found, carried);
|
||||
// (the game's order among the mods that are on; one that is off keeps the place it would have without its switch)
|
||||
found.Sort((a, b) =>
|
||||
{
|
||||
var c = Mods.Compare(Mods.Place(a.Rel), Mods.Place(b.Rel));
|
||||
return c != 0 ? c : string.CompareOrdinal(a.Rel, b.Rel);
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
/// <summary>The mods of a game folder.</summary>
|
||||
public List<Mod> ListGame(string game, bool carried = true) => List(Mods.FolderOf(game), carried);
|
||||
|
||||
static void Walk(string dir, string rel, int depth, string? offAbove, List<Mod> found, bool carried)
|
||||
{
|
||||
var folder = depth > 0 ? Path.GetFileName(dir) : "";
|
||||
var (isOff, number, name) = Mods.Parse(folder);
|
||||
// (romfs and exefs make a folder a mod for the game, whatever they are; a cheats folder for the build)
|
||||
bool Has(string part) => Directory.Exists(Path.Combine(dir, part)) || part != "cheats" && File.Exists(Path.Combine(dir, part));
|
||||
if (depth > 0 && Mods.Parts.Any(Has))
|
||||
{
|
||||
var m = new Mod
|
||||
{
|
||||
Path = dir, Rel = rel, Top = rel.Split('/')[0], Folder = folder, Name = name.Length > 0 ? name : folder, Number = number,
|
||||
On = offAbove == null && !isOff, OffAbove = offAbove, Info = ReadInfo(dir),
|
||||
};
|
||||
if (carried) Fill(m);
|
||||
found.Add(m);
|
||||
return;
|
||||
}
|
||||
if (depth >= 4) return;
|
||||
foreach (var sub in Folders(dir))
|
||||
{
|
||||
var child = Path.GetFileName(sub);
|
||||
if (child.Length == 0 || child[0] == '.') continue;
|
||||
Walk(sub, rel.Length > 0 ? rel + "/" + child : child, depth + 1, offAbove ?? (isOff ? folder : null), found, carried);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>triforce_mod.json beside a mod, when it came from GameBanana (the old Setup did not read it: vk_mods.h's mismatch).</summary>
|
||||
public static ModInfo? ReadInfo(string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
var file = Path.Combine(dir, "triforce_mod.json");
|
||||
if (!File.Exists(file)) return null;
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(file));
|
||||
var r = doc.RootElement;
|
||||
string? S(string n) => r.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null;
|
||||
long N(string n) => r.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out var x) ? x : 0;
|
||||
return new ModInfo(S("name"), S("author"), S("page"), N("gamebanana_id"), S("gamebanana_model") == "Wip", S("file"), N("file_date"));
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
/// <summary>The file the game reads for one of its RomFS paths ("Sound/Resource/x.bwav"): that of the last mod, among those that
|
||||
/// are on, that carries it (a link to a folder not followed, the romfs folder itself neither when it is one), else the game's
|
||||
/// own under <game>\romfs. Null when neither has it. (For the game's own sounds and music the App plays.)</summary>
|
||||
public string? RomfsFile(string game, string rel)
|
||||
{
|
||||
var parts = rel.Replace('\\', '/').Split('/').Where(p => p.Length > 0).ToArray();
|
||||
if (parts.Length == 0 || parts.Any(p => p == "." || p == ".." || p.IndexOf(':') >= 0)) return null;
|
||||
string? In(string romfs)
|
||||
{
|
||||
var at = romfs;
|
||||
for (var i = 0; ; i++)
|
||||
{
|
||||
if (!Directory.Exists(at) || Mods.IsLink(at)) return null;
|
||||
at = Path.Combine(at, parts[i]);
|
||||
if (i == parts.Length - 1) return File.Exists(at) ? at : null;
|
||||
}
|
||||
}
|
||||
try
|
||||
{
|
||||
foreach (var m in Enumerable.Reverse(List(Mods.FolderOf(game), false)).Where(m => m.On))
|
||||
if (In(Path.Combine(m.Path, "romfs")) is { } theirs) return theirs;
|
||||
var own = Path.Combine(new[] { game, "romfs" }.Concat(parts).ToArray());
|
||||
return File.Exists(own) ? own : null;
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
/// <summary>What a mod carries: its RomFS files as the game indexes them (32 folders deep, a link to a folder left out, the
|
||||
/// romfs folder itself too when it is one), and how many files its exefs and cheats folders hold.</summary>
|
||||
static void Fill(Mod m)
|
||||
{
|
||||
var romfs = Path.Combine(m.Path, "romfs");
|
||||
if (Directory.Exists(romfs))
|
||||
{
|
||||
if (Mods.IsLink(romfs)) m.RomfsIsLink = true;
|
||||
else Index(m, romfs, "", 0);
|
||||
}
|
||||
m.Files.Sort(string.CompareOrdinal);
|
||||
m.Patches = Count(Path.Combine(m.Path, "exefs"));
|
||||
m.Cheats = Count(Path.Combine(m.Path, "cheats"));
|
||||
}
|
||||
|
||||
static void Index(Mod m, string dir, string rel, int depth)
|
||||
{
|
||||
if (depth > 32) return;
|
||||
FileSystemInfo[] entries;
|
||||
try { entries = new DirectoryInfo(dir).GetFileSystemInfos(); } catch (Exception) { return; }
|
||||
foreach (var e in entries)
|
||||
{
|
||||
var isDir = (e.Attributes & FileAttributes.Directory) != 0;
|
||||
if (isDir && (e.Attributes & FileAttributes.ReparsePoint) != 0) continue;
|
||||
var path = rel.Length > 0 ? rel + "/" + e.Name : e.Name;
|
||||
if (isDir) Index(m, e.FullName, path, depth + 1);
|
||||
else
|
||||
{
|
||||
m.Files.Add(Mods.Key(path));
|
||||
try { m.Bytes += ((FileInfo)e).Length; } catch (Exception) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static int Count(string dir)
|
||||
{
|
||||
try { return Directory.Exists(dir) && !Mods.IsLink(dir) ? Directory.GetFiles(dir, "*", SearchOption.AllDirectories).Length : 0; }
|
||||
catch (Exception) { return 0; }
|
||||
}
|
||||
|
||||
// ---- what the game must be built again for ----
|
||||
|
||||
/// <summary>The mark of the mods' code the game folder was last built with (ModsBuilt "<game>|<mark>"), null when none is kept for it.</summary>
|
||||
public string? BuiltMark(string game) =>
|
||||
ctx.Settings.ModsBuilt is { } kept && kept.StartsWith(game + "|", StringComparison.OrdinalIgnoreCase) ? kept.Substring(game.Length + 1) : null;
|
||||
|
||||
/// <summary>A build of this game folder ended well: its mods' code patches are in it as they are now.</summary>
|
||||
public void MarkBuilt(string game) => ctx.Settings.ModsBuilt = game + "|" + Mods.CodeState(ListGame(game));
|
||||
|
||||
/// <summary>A mod with code patches changed before any build was marked: built in or not, the game is not as its mods are.</summary>
|
||||
public void MarkChanged(string game)
|
||||
{
|
||||
if (BuiltMark(game) == null) ctx.Settings.ModsBuilt = game + "|changed";
|
||||
}
|
||||
|
||||
/// <summary>"Build again to apply" (old Shell.Mods.cs ModsRefresh): the code patches of the mods that are on are not the ones of the
|
||||
/// last build. Then BuildRunner with BuildRequest.Update(game) (refused while the game runs).</summary>
|
||||
public bool NeedsRebuild(string game) => Mods.NeedsBuild(Mods.CodeState(ListGame(game)), BuiltMark(game));
|
||||
|
||||
// ---- on and off ----
|
||||
|
||||
/// <summary>Switches a mod on or off by its folder's name: "-" in front of it, or no - and _ there. Returns its folder now.</summary>
|
||||
public string SetOn(string mods, Mod mod, bool on)
|
||||
{
|
||||
Refuse(mods);
|
||||
if (!Directory.Exists(mod.Path)) throw new ModsException(mod.Name + " is no longer in the mods folder.");
|
||||
var (off, _, _) = Mods.Parse(mod.Folder);
|
||||
if (on && mod.OffAbove != null)
|
||||
throw new ModsException(mod.Name + " is inside the folder " + mod.OffAbove + ", whose name switches off everything in it. Take the - or _ off that folder's name.");
|
||||
if (on == !off) return mod.Path;
|
||||
var name = on ? mod.Folder.TrimStart('-', '_') : "-" + mod.Folder;
|
||||
if (name.Length == 0 || name[0] == '.') throw new ModsException("Without the " + mod.Folder[0] + " in front, the folder " + mod.Folder + " has no name the game looks at. Rename it by hand.");
|
||||
var target = Path.Combine(Path.GetDirectoryName(mod.Path)!, name);
|
||||
if (Directory.Exists(target) || File.Exists(target))
|
||||
throw new ModsException("There is already a folder named " + name + " in the mods folder. Rename or remove one of the two first.");
|
||||
try { MoveFolder(mods, mod.Path, target); }
|
||||
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
|
||||
{
|
||||
throw new ModsException(mod.Name + " could not be switched " + (on ? "on" : "off") + ": " + e.Message + " Close any window that shows its folder and try again.");
|
||||
}
|
||||
if (mod.Built) MarkChanged(Path.GetDirectoryName(Full(mods))!);
|
||||
ctx.Log.Write("mods: " + mod.Name + " switched " + (on ? "on" : "off"));
|
||||
return target;
|
||||
}
|
||||
|
||||
// ---- the order ----
|
||||
|
||||
/// <summary>Moves a mod one place: later (it then wins over the mod it passes) or earlier. The folders of the mods folder are
|
||||
/// numbered anew, 01- 02- ..., each keeping its own name and its switch; a mod deeper down moves with the folder of the mods
|
||||
/// folder it is in. False when it is at that end already.</summary>
|
||||
public bool Move(string mods, Mod mod, bool later)
|
||||
{
|
||||
Refuse(mods);
|
||||
var tops = Mods.Tops(List(mods));
|
||||
var at = tops.FindIndex(t => Same(t, mod.Top));
|
||||
if (at < 0) throw new ModsException(mod.Name + " is no longer in the mods folder.");
|
||||
var to = at + (later ? 1 : -1);
|
||||
if (to < 0 || to >= tops.Count) return false;
|
||||
(tops[at], tops[to]) = (tops[to], tops[at]);
|
||||
Number(mods, tops);
|
||||
if (mod.Built) MarkChanged(Path.GetDirectoryName(Full(mods))!);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The folders, in this order, under the numbers 01- 02- ... (three digits from a hundred folders on): all of them or,
|
||||
/// when one cannot be renamed, none.</summary>
|
||||
void Number(string mods, List<string> tops)
|
||||
{
|
||||
var digits = tops.Count >= 100 ? "000" : "00";
|
||||
var plan = new List<(string From, string To)>();
|
||||
for (var i = 0; i < tops.Count; i++)
|
||||
{
|
||||
var (_, _, name) = Mods.Parse(tops[i]);
|
||||
var switches = tops[i].Substring(0, tops[i].Length - tops[i].TrimStart('-', '_').Length);
|
||||
var to = switches + (i + 1).ToString(digits) + "-" + name;
|
||||
if (!string.Equals(tops[i], to, StringComparison.Ordinal)) plan.Add((tops[i], to));
|
||||
}
|
||||
var leaving = new HashSet<string>(plan.Select(p => p.From), StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var (_, to) in plan)
|
||||
{
|
||||
var path = Path.Combine(mods, to);
|
||||
if (!leaving.Contains(to) && (Directory.Exists(path) || File.Exists(path)))
|
||||
throw new ModsException("There is already something named " + to + " in the mods folder, where a mod's folder would be renamed to. Rename or remove it first. Nothing was changed.");
|
||||
}
|
||||
// (a new name that is another folder's old one, two mods of one name changing places: each goes through a name of its own
|
||||
// first, one the game does not look at)
|
||||
var steps = new List<(string From, string To)>();
|
||||
if (plan.Any(p => leaving.Contains(p.To)))
|
||||
{
|
||||
var aside = Mods.Moving + Hex8() + "-";
|
||||
steps.AddRange(plan.Select((p, i) => (p.From, aside + i)));
|
||||
steps.AddRange(plan.Select((p, i) => (aside + i, p.To)));
|
||||
}
|
||||
else steps.AddRange(plan);
|
||||
var done = new List<(string From, string To)>();
|
||||
try
|
||||
{
|
||||
foreach (var (from, to) in steps)
|
||||
{
|
||||
MoveFolder(mods, Path.Combine(mods, from), Path.Combine(mods, to));
|
||||
done.Add((from, to));
|
||||
}
|
||||
}
|
||||
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
|
||||
{
|
||||
var back = true;
|
||||
for (var i = done.Count - 1; i >= 0; i--)
|
||||
try { MoveFolder(mods, Path.Combine(mods, done[i].To), Path.Combine(mods, done[i].From)); }
|
||||
catch (Exception) { back = false; }
|
||||
throw new ModsException("The mods could not be put in that order: " + e.Message + (back ? " Nothing was changed." : " Some folders have their new names and some their old ones.") +
|
||||
" Close any window that shows a mod's folder and try again.");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- removing ----
|
||||
|
||||
/// <summary>Takes a mod out of the game's sight: its folder moves into mods\.removed (under a free name). Nothing is deleted.</summary>
|
||||
public string Remove(string mods, Mod mod)
|
||||
{
|
||||
Refuse(mods);
|
||||
if (!Directory.Exists(mod.Path)) throw new ModsException(mod.Name + " is no longer in the mods folder.");
|
||||
var bin = Path.Combine(mods, Mods.Removed);
|
||||
try
|
||||
{
|
||||
MakeFolder(mods, bin);
|
||||
var target = Free(bin, mod.Folder.TrimStart('-', '_') is { Length: > 0 } n ? n : "mod");
|
||||
MoveFolder(mods, mod.Path, target);
|
||||
if (mod.Built) MarkChanged(Path.GetDirectoryName(Full(mods))!);
|
||||
ctx.Log.Write("mods: " + mod.Name + " removed to " + target);
|
||||
return target;
|
||||
}
|
||||
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
|
||||
{
|
||||
throw new ModsException(mod.Name + " could not be removed: " + e.Message + " Close any window that shows its folder and try again.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>dir\name, or the first of "name (2)", "name (3)" ... that is not there.</summary>
|
||||
internal static string Free(string dir, string name)
|
||||
{
|
||||
for (var k = 1; ; k++)
|
||||
{
|
||||
var path = Path.Combine(dir, k == 1 ? name : name + " (" + k + ")");
|
||||
if (!Directory.Exists(path) && !File.Exists(path)) return path;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- adding from an archive ----
|
||||
|
||||
/// <summary>Adds a mod from a .zip, .7z or .rar file. The archive is unpacked into a folder of its own inside the mods folder
|
||||
/// (one the game does not look at), what lies there is checked, the folder that holds romfs, exefs or cheats is looked for,
|
||||
/// and only then does that folder move into the mods folder under the mod's name. Anything else ends with a sentence that says
|
||||
/// why, and with nothing added. Returns the new mod.</summary>
|
||||
public Mod Add(string mods, string archive, Action<double>? progress = null)
|
||||
{
|
||||
Refuse(mods);
|
||||
var kind = Path.GetExtension(archive).ToLowerInvariant();
|
||||
if (kind != ".zip" && kind != ".7z" && kind != ".rar") throw new ModsException("That is no .zip, .7z or .rar file.");
|
||||
if (!File.Exists(archive)) throw new ModsException("The file is not there: " + archive);
|
||||
string temp;
|
||||
try
|
||||
{
|
||||
MakeFolder(mods, mods);
|
||||
Sweep(mods);
|
||||
temp = Path.Combine(mods, Mods.Adding + Hex8());
|
||||
MakeFolder(mods, temp);
|
||||
}
|
||||
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
|
||||
{
|
||||
throw new ModsException("The mods folder could not be written to: " + e.Message);
|
||||
}
|
||||
try
|
||||
{
|
||||
var into = Path.Combine(temp, "x");
|
||||
Unpack(mods, archive, into, progress);
|
||||
var root = FindRoot(into);
|
||||
// (the mod's name: its own folder's in the archive, else the archive's)
|
||||
var given = Same(Full(root), Full(into)) || Mods.Generic(Path.GetFileName(root)) ? Path.GetFileNameWithoutExtension(archive) : Path.GetFileName(root);
|
||||
var name = Mods.Clean(given);
|
||||
// (where the folders are numbered, the new mod gets the next number: it loads last, and wins, wherever its name would sort)
|
||||
var numbers = Mods.Tops(List(mods)).Select(t => Mods.Parse(t).Number).Where(n => n != null).Select(n => n!.Value).ToList();
|
||||
if (numbers.Count > 0 && Mods.Parse(name).Number == null) name = (numbers.Max() + 1).ToString(numbers.Max() + 1 >= 100 ? "000" : "00") + "-" + name;
|
||||
var target = Free(mods, name);
|
||||
MoveFolder(mods, root, target);
|
||||
progress?.Invoke(1);
|
||||
var mod = List(mods).FirstOrDefault(m => Same(m.Path, target)) ?? throw new ModsException("The mod was unpacked into " + target + ", but the game would not find it there.");
|
||||
if (mod.Code) MarkChanged(Path.GetDirectoryName(Full(mods))!);
|
||||
ctx.Log.Write("mods: added " + mod.Rel + " from " + Path.GetFileName(archive));
|
||||
return mod;
|
||||
}
|
||||
catch (ModsException) { throw; }
|
||||
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException || e is InvalidDataException || e is NotSupportedException || e is ArgumentException)
|
||||
{
|
||||
throw new ModsException(ctx.Platform.IsDiskFull(e) ? "The disk filled while the archive was unpacked. Nothing was added." : "The archive could not be unpacked: " + e.Message + " Nothing was added.");
|
||||
}
|
||||
finally { Delete(mods, temp); }
|
||||
}
|
||||
|
||||
/// <summary>The archive unpacked into a folder and checked there (names, links, sizes, counts), before anything moves.</summary>
|
||||
internal void Unpack(string mods, string archive, string into, Action<double>? progress)
|
||||
{
|
||||
var kind = Path.GetExtension(archive).ToLowerInvariant();
|
||||
if (kind == ".zip") UnpackZip(mods, archive, into, progress);
|
||||
else UnpackWithTar(mods, archive, into, kind);
|
||||
Check(into, kind != ".zip");
|
||||
}
|
||||
|
||||
/// <summary>What an adding that was cut off left in the mods folder a day ago or longer.</summary>
|
||||
void Sweep(string mods)
|
||||
{
|
||||
foreach (var d in Folders(mods))
|
||||
try
|
||||
{
|
||||
if (Regex.IsMatch(Path.GetFileName(d), "^" + Regex.Escape(Mods.Adding) + "[0-9a-f]{8}$") && DateTime.UtcNow - Directory.GetLastWriteTimeUtc(d) > TimeSpan.FromDays(1))
|
||||
Delete(mods, d);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>Removes the folder an archive was unpacked into, with what is left in it. A link in it is removed as a link.</summary>
|
||||
void Delete(string mods, string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
Within(mods, dir);
|
||||
if (!Same(Path.GetDirectoryName(Full(dir)) ?? "", Full(mods)) || !Path.GetFileName(Full(dir)).StartsWith(Mods.Adding, StringComparison.Ordinal)) return;
|
||||
Empty(dir);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
internal static void Empty(string dir)
|
||||
{
|
||||
foreach (var e in new DirectoryInfo(dir).GetFileSystemInfos())
|
||||
{
|
||||
try
|
||||
{
|
||||
if ((e.Attributes & FileAttributes.ReadOnly) != 0) e.Attributes &= ~FileAttributes.ReadOnly;
|
||||
if ((e.Attributes & FileAttributes.Directory) != 0 && (e.Attributes & FileAttributes.ReparsePoint) == 0) Empty(e.FullName);
|
||||
else if ((e.Attributes & FileAttributes.Directory) != 0) Directory.Delete(e.FullName, false);
|
||||
else File.Delete(e.FullName);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
try { Directory.Delete(dir, false); } catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>A zip, with .NET's own reader. Its list is checked whole before the first file is written: every name, no links, no
|
||||
/// two files of one name, what it says it unpacks to against the bound and against the room on the disk. A file that turns out
|
||||
/// longer than its entry said stops the unpacking.</summary>
|
||||
void UnpackZip(string mods, string archive, string into, Action<double>? progress)
|
||||
{
|
||||
ZipArchive zip;
|
||||
try { zip = ZipFile.OpenRead(archive); }
|
||||
catch (Exception e) when (e is InvalidDataException || e is IOException || e is UnauthorizedAccessException || e is NotSupportedException)
|
||||
{
|
||||
throw new ModsException("That is not a zip file the launcher can read (" + e.Message + "). Nothing was added.");
|
||||
}
|
||||
using (zip)
|
||||
{
|
||||
System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> entries;
|
||||
try { entries = zip.Entries; }
|
||||
catch (ArgumentException) { throw new ModsException("The archive holds a name with a character Windows does not allow. Nothing was unpacked."); }
|
||||
catch (InvalidDataException e) { throw new ModsException("That is not a zip file the launcher can read (" + e.Message + "). Nothing was added."); }
|
||||
if (entries.Count > MaxFiles) throw new ModsException("The archive holds " + entries.Count + " files, more than the " + MaxFiles + " a mod may have. Nothing was added.");
|
||||
long total = 0;
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var e in entries)
|
||||
{
|
||||
if (Mods.Unsafe(e.FullName, true) is { } why) throw new ModsException("The archive holds " + why + ": \"" + Mods.Short(e.FullName) + "\". Nothing was unpacked.");
|
||||
// (how the zip marks what an entry is: Unix's file type in the high half of its attributes, Windows' in the low)
|
||||
var type = (e.ExternalAttributes >> 16) & 0xF000;
|
||||
if (type == 0xA000 || (e.ExternalAttributes & 0x400) != 0) throw new ModsException("The archive holds a link (\"" + Mods.Short(e.FullName) + "\"), which could point anywhere on this PC. Nothing was unpacked.");
|
||||
if (type != 0 && type != 0x8000 && type != 0x4000) throw new ModsException("The archive holds something that is neither a file nor a folder (\"" + Mods.Short(e.FullName) + "\"). Nothing was unpacked.");
|
||||
var plain = string.Join("/", e.FullName.Replace('\\', '/').Split('/').Where(p => p.Length > 0 && p != "."));
|
||||
if (plain.Length == 0) continue;
|
||||
if (!seen.Add(plain)) throw new ModsException("The archive holds two files of one name (\"" + Mods.Short(e.FullName) + "\"). Nothing was unpacked.");
|
||||
if (e.Length < 0 || e.Length > MaxBytes || (total += e.Length) > MaxBytes) throw new ModsException(TooBig());
|
||||
}
|
||||
if (ctx.SpaceProblem("this mod", total + entries.Count * 4096L, mods) is { } none) throw new ModsException(none);
|
||||
MakeFolder(mods, into);
|
||||
var root = Full(into) + Sep;
|
||||
long written = 0;
|
||||
var buffer = new byte[1 << 16];
|
||||
for (var i = 0; i < entries.Count; i++)
|
||||
{
|
||||
var e = entries[i];
|
||||
var name = e.FullName.Replace('\\', '/');
|
||||
var dest = Path.GetFullPath(Path.Combine(into, name.Replace('/', Sep)));
|
||||
if (!(dest + Sep).StartsWith(root, PathCase)) throw new ModsException("The archive holds a path that leaves its own folder: \"" + Mods.Short(e.FullName) + "\".");
|
||||
Within(mods, dest);
|
||||
if (name.EndsWith('/')) { Directory.CreateDirectory(dest); continue; }
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(dest)!);
|
||||
long size = 0;
|
||||
using (var from = e.Open())
|
||||
using (var to = new FileStream(dest, FileMode.CreateNew, FileAccess.Write, FileShare.None))
|
||||
for (int n; (n = from.Read(buffer, 0, buffer.Length)) > 0;)
|
||||
{
|
||||
if ((size += n) > e.Length || (written += n) > MaxBytes) throw new ModsException("The archive unpacks to more than it says (\"" + Mods.Short(e.FullName) + "\"). Nothing was added.");
|
||||
to.Write(buffer, 0, n);
|
||||
}
|
||||
try { File.SetLastWriteTime(dest, e.LastWriteTime.DateTime); } catch (Exception) { }
|
||||
if ((i & 31) == 0) progress?.Invoke(0.95 * i / entries.Count);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
string TooBig() => "The archive unpacks to more than " + (MaxBytes >> 30) + " GB, the most a mod may take. Nothing was added.";
|
||||
|
||||
static string ByHand(string kind) => " Unpack the " + kind + " file yourself and put the mod's folder (the one that holds romfs) into the mods folder.";
|
||||
|
||||
/// <summary>A .7z or .rar, with the system's bsdtar (Windows' own tar.exe). Its list is asked for first, twice: the names
|
||||
/// (checked as a zip's are) and the long form, whose first letter says what each entry is (a link is refused) and whose fifth
|
||||
/// word is its size (counted against the bound and the room on the disk). tar then unpacks into the folder, without -P: it
|
||||
/// refuses paths that leave it. What lies there afterwards is checked again, as files (Check).</summary>
|
||||
void UnpackWithTar(string mods, string archive, string into, string kind)
|
||||
{
|
||||
var tar = Tar();
|
||||
if (tar == null)
|
||||
throw new ModsException(OperatingSystem.IsWindows()
|
||||
? "This PC has no tar.exe in its System32 folder (Windows 10 and 11 bring one), and the launcher opens " + kind + " files with nothing else." + ByHand(kind)
|
||||
: "This PC has no bsdtar (libarchive's tar; GNU tar does not read " + kind + " files)." + ByHand(kind));
|
||||
MakeFolder(mods, into);
|
||||
var (code, names, error) = Run(tar, new[] { "-tf", archive }, into, MaxFiles + 1);
|
||||
if (code != 0) throw new ModsException("This PC's tar could not read the " + kind + " file (" + Reason(error, code) + ")." + ByHand(kind));
|
||||
if (names.Count > MaxFiles) throw new ModsException("The archive holds more than the " + MaxFiles + " files a mod may have. Nothing was added.");
|
||||
foreach (var n in names)
|
||||
if (Mods.Unsafe(n, false) is { } why) throw new ModsException("The archive holds " + why + ": \"" + Mods.Short(n) + "\". Nothing was unpacked.");
|
||||
var (code2, lines, error2) = Run(tar, new[] { "-tvf", archive }, into, MaxFiles + 1);
|
||||
if (code2 != 0 || lines.Count != names.Count) throw new ModsException("This PC's tar could not list the " + kind + " file (" + Reason(error2, code2) + ")." + ByHand(kind));
|
||||
long total = 0;
|
||||
for (var i = 0; i < lines.Count; i++)
|
||||
{
|
||||
var words = lines[i].Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (words.Length < 6 || words[0].Length < 10 || !long.TryParse(words[4], out var size) || size < 0)
|
||||
throw new ModsException("This PC's tar lists the " + kind + " file in a way the launcher cannot read, so it was not unpacked." + ByHand(kind));
|
||||
if (words[0][0] == 'l' || words[0][0] == 'h') throw new ModsException("The archive holds a link (\"" + Mods.Short(names[i]) + "\"), which could point anywhere on this PC. Nothing was unpacked.");
|
||||
if (words[0][0] != '-' && words[0][0] != 'd') throw new ModsException("The archive holds something that is neither a file nor a folder (\"" + Mods.Short(names[i]) + "\"). Nothing was unpacked.");
|
||||
if (size > MaxBytes || (total += size) > MaxBytes) throw new ModsException(TooBig());
|
||||
}
|
||||
if (ctx.SpaceProblem("this mod", total + names.Count * 4096L, mods) is { } none) throw new ModsException(none);
|
||||
Within(mods, into);
|
||||
var (code3, _, error3) = Run(tar, new[] { "-xf", archive, "-C", into }, into, 0);
|
||||
if (code3 != 0) throw new ModsException("This PC's tar could not unpack the " + kind + " file (" + Reason(error3, code3) + "). Nothing was added." + ByHand(kind));
|
||||
}
|
||||
|
||||
static string Reason(string error, int code)
|
||||
{
|
||||
var line = error.Replace("\r", "").Split('\n').Select(l => l.Trim()).FirstOrDefault(l => l.Length > 0);
|
||||
return line != null ? Mods.Short(line) : "exit code " + code;
|
||||
}
|
||||
|
||||
/// <summary>tar with these words, its lines (at most so many: one more and it is stopped) and what it said of errors.</summary>
|
||||
static (int Code, List<string> Lines, string Error) Run(string exe, string[] arguments, string dir, int most)
|
||||
{
|
||||
var si = new ProcessStartInfo(exe)
|
||||
{
|
||||
UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = dir,
|
||||
};
|
||||
foreach (var a in arguments) si.ArgumentList.Add(a);
|
||||
using var p = Process.Start(si)!;
|
||||
var error = p.StandardError.ReadToEndAsync();
|
||||
var lines = new List<string>();
|
||||
for (string? line; (line = p.StandardOutput.ReadLine()) != null;)
|
||||
{
|
||||
if (line.Length == 0) continue;
|
||||
lines.Add(line);
|
||||
if (lines.Count > most && most > 0)
|
||||
{
|
||||
try { p.Kill(); } catch (Exception) { }
|
||||
break;
|
||||
}
|
||||
}
|
||||
p.WaitForExit();
|
||||
string said;
|
||||
try { said = error.Result; } catch (Exception) { said = ""; }
|
||||
return (lines.Count > most && most > 0 ? 0 : p.ExitCode, lines, said);
|
||||
}
|
||||
|
||||
/// <summary>What an archive unpacked to, looked at as it lies on the disk before any of it moves into the mods folder: no link of
|
||||
/// any kind, nothing under a device's name, not more files or bytes than a mod may have.</summary>
|
||||
void Check(string into, bool links)
|
||||
{
|
||||
var files = 0;
|
||||
long bytes = 0;
|
||||
void Look(string dir, int depth)
|
||||
{
|
||||
if (depth > Mods.MaxDepth) throw new ModsException("The archive's folders go more than " + Mods.MaxDepth + " deep. Nothing was added.");
|
||||
foreach (var e in new DirectoryInfo(dir).GetFileSystemInfos())
|
||||
{
|
||||
var shown = Mods.Short(e.FullName.Substring(Full(into).Length + 1));
|
||||
if ((e.Attributes & FileAttributes.ReparsePoint) != 0 || e.LinkTarget != null) throw new ModsException("The archive holds a link (\"" + shown + "\"), which could point anywhere on this PC. Nothing was added.");
|
||||
if (Mods.IsDevice(e.Name)) throw new ModsException("The archive holds a name Windows keeps for a device (\"" + shown + "\"). Nothing was added.");
|
||||
if ((e.Attributes & FileAttributes.Directory) != 0) { Look(e.FullName, depth + 1); continue; }
|
||||
if (links && ctx.Platform.HasOtherName(e.FullName)) throw new ModsException("The archive holds a link (\"" + shown + "\"), which could point anywhere on this PC. Nothing was added.");
|
||||
if (++files > MaxFiles) throw new ModsException("The archive holds more than the " + MaxFiles + " files a mod may have. Nothing was added.");
|
||||
if ((bytes += ((FileInfo)e).Length) > MaxBytes) throw new ModsException(TooBig());
|
||||
}
|
||||
}
|
||||
Look(into, 0);
|
||||
}
|
||||
|
||||
/// <summary>The folder of what was unpacked that is the mod: the one that holds romfs, exefs or cheats, looked for four folders
|
||||
/// down as the game looks. None, several (a download with versions to choose from) or one for another game are said so.</summary>
|
||||
static string FindRoot(string into)
|
||||
{
|
||||
var found = new List<string>();
|
||||
void Look(string dir, int depth)
|
||||
{
|
||||
if (Mods.Parts.Any(p => Directory.Exists(Path.Combine(dir, p)))) { found.Add(dir); return; }
|
||||
if (depth >= 4) return;
|
||||
foreach (var sub in Folders(dir)) Look(sub, depth + 1);
|
||||
}
|
||||
Look(into, 0);
|
||||
if (found.Count == 0)
|
||||
throw new ModsException("The archive holds no romfs, exefs or cheats folder, so the launcher cannot tell where the mod's files belong. Nothing was added. " +
|
||||
"(A mod's files go into mods\\<name>\\romfs, laid out as the game's own files are.)");
|
||||
if (found.Count > 1)
|
||||
{
|
||||
var names = found.Select(f => Path.GetFileName(f)).Take(4).ToList();
|
||||
throw new ModsException("The archive holds " + found.Count + " mods (" + string.Join(", ", names) + (found.Count > 4 ? ", ..." : "") + "), most likely versions to choose from. Nothing was added. " +
|
||||
"Unpack it yourself and put the one you want into the mods folder.");
|
||||
}
|
||||
// (an emulator's layout, ...\contents\<title id>\romfs: made for the game of that number)
|
||||
var title = Path.GetFileName(found[0]);
|
||||
if (!Same(Full(found[0]), Full(into)) && Regex.IsMatch(title, "^[0-9A-Fa-f]{16}$") && !string.Equals(title, Mods.TitleId, StringComparison.OrdinalIgnoreCase))
|
||||
throw new ModsException("The archive holds a mod for another game (title " + title.ToUpperInvariant() + "), not for this one (" + Mods.TitleId + "). Nothing was added.");
|
||||
return found[0];
|
||||
}
|
||||
}
|
||||
245
launcher/Logic/Mods/Mods.cs
Normal file
245
launcher/Logic/Mods/Mods.cs
Normal file
@@ -0,0 +1,245 @@
|
||||
// (Triforce) The mods of a game folder as they lie on the disk (old setup/Mods.cs, Shell.Mods.cs). The rules are the game's
|
||||
// (host/mods.c). Nothing here changes them or keeps a list of its own, so a player who arranges the folders by hand and one who
|
||||
// uses the launcher see the same thing:
|
||||
// <game>\mods\<name>\romfs\... a mod is a folder, up to four levels down, that holds romfs, exefs or cheats
|
||||
// a name that starts with - or _ switches the folder off, and every mod in it (a name that starts with a dot is not looked at)
|
||||
// the name that sorts last wins among the mods that carry the same file (compared without case, as the game does)
|
||||
// On and off is a rename: with a "-" in front, or without. The order is a number in front of the name ("01-", "02-"), kept apart
|
||||
// from the mod's own name, so "-02-Tall grass" is the mod Tall grass, second, switched off. RomFS files and cheats are read when the
|
||||
// game starts; code patches (exefs) are built into the game, so a change of those waits for the next build (CodeState).
|
||||
//
|
||||
// Every change is a rename or a new folder inside the mods folder and nowhere else (Within), and none is made while the game runs
|
||||
// (GameRuns). A mod that is removed goes to mods\.removed, which the game does not look at: nothing is ever deleted but what an
|
||||
// archive's own unpacking left in its temporary folder.
|
||||
using System.Diagnostics;
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>What the Mods page tells the player when something cannot be done: a whole sentence, in plain words.</summary>
|
||||
public sealed class ModsException : Exception
|
||||
{
|
||||
public ModsException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
/// <summary>One mod as the game would find it.</summary>
|
||||
public sealed class Mod
|
||||
{
|
||||
public string Path { get; set; } = ""; // (its folder, in full)
|
||||
public string Rel { get; set; } = ""; // (its place under the mods folder, "/" between folders: what the game sorts by)
|
||||
public string Top { get; set; } = ""; // (the folder of the mods folder it is, or is in)
|
||||
public string Folder { get; set; } = ""; // (its folder's name as it is on the disk)
|
||||
public string Name { get; set; } = ""; // (its own name: the folder's without the switch and the number)
|
||||
public int? Number { get; set; } // (the number its folder's name starts with, "01-", when it has one)
|
||||
public bool On { get; set; }
|
||||
public string? OffAbove { get; set; } // (the folder above it whose name switches it off, when it is not its own name that does)
|
||||
public List<string> Files { get; } = new(); // (its RomFS files as the game looks them up: lower case, "/" between folders)
|
||||
public long Bytes { get; set; }
|
||||
public int Patches { get; set; } // (the files in its exefs)
|
||||
public int Cheats { get; set; } // (the files in its cheats folder)
|
||||
public bool RomfsIsLink { get; set; } // (its romfs folder is a link, which the game leaves out)
|
||||
/// <summary>What GameBanana said of it (triforce_mod.json beside it), when it came from there.</summary>
|
||||
public ModInfo? Info { get; set; }
|
||||
|
||||
public bool Deep => Rel.IndexOf('/') >= 0;
|
||||
public bool Code => Patches > 0 || Cheats > 0;
|
||||
/// <summary>It carries code patches: what is built into the game (its cheats are read when the game starts: host/mod_cheats.c).</summary>
|
||||
public bool Built => Patches > 0;
|
||||
public override string ToString() => Rel;
|
||||
}
|
||||
|
||||
/// <summary>triforce_mod.json (written by the game's Mods menu and the launcher's GameBanana install): name, author, page, id.</summary>
|
||||
public sealed record ModInfo(string? Name, string? Author, string? Page, long GameBananaId, bool Wip, string? File, long FileDate);
|
||||
|
||||
/// <summary>A file more than one of the mods that are on carry: the last of them, in the order the game loads them, wins.</summary>
|
||||
public sealed class Conflict
|
||||
{
|
||||
public string File { get; set; } = "";
|
||||
public List<Mod> Mods { get; } = new();
|
||||
public Mod Winner => Mods[Mods.Count - 1];
|
||||
}
|
||||
|
||||
/// <summary>The rules that need no folder: names, order, the safety of an archive's names, the build mark.</summary>
|
||||
public static class Mods
|
||||
{
|
||||
/// <summary>The game this is built for: a mod in an emulator's layout names the game it is made for by this number.</summary>
|
||||
public const string TitleId = "0400486024DEC000";
|
||||
public const string BuildAgain = "Build again to apply";
|
||||
/// <summary>Where removed mods go, and where an archive is unpacked and checked before its mod moves in. Both names start with a
|
||||
/// dot: the game does not look at such folders (host/mods.c find_mods).</summary>
|
||||
public const string Removed = ".removed", Adding = ".adding-", Moving = ".moving-";
|
||||
internal static readonly string[] Parts = { "romfs", "exefs", "cheats" };
|
||||
/// <summary>How deep a path in an archive may go (the game follows a RomFS 32 folders down).</summary>
|
||||
public const int MaxDepth = 40;
|
||||
|
||||
public static string FolderOf(string game) => Path.Combine(game, "mods");
|
||||
|
||||
/// <summary>A folder's name taken apart: switched off (it starts with - or _), its number ("01-": two or three digits and a
|
||||
/// hyphen, so that "4K-grass" and "2024-pack" keep their names whole) and the mod's own name.</summary>
|
||||
public static (bool Off, int? Number, string Name) Parse(string folder)
|
||||
{
|
||||
var off = folder.Length > 0 && (folder[0] == '-' || folder[0] == '_');
|
||||
var rest = folder.TrimStart('-', '_');
|
||||
var m = Regex.Match(rest, @"^(\d{2,3})-(.+)$", RegexOptions.Singleline);
|
||||
return m.Success ? (off, int.Parse(m.Groups[1].Value), m.Groups[2].Value) : (off, null, rest);
|
||||
}
|
||||
|
||||
/// <summary>As the game compares names (host/mods.c mod_cmp, _stricmp): byte by byte, the letters A to Z without case.</summary>
|
||||
public static int Compare(string a, string b)
|
||||
{
|
||||
byte[] x = Encoding.UTF8.GetBytes(a), y = Encoding.UTF8.GetBytes(b);
|
||||
for (var i = 0; i < x.Length && i < y.Length; i++)
|
||||
{
|
||||
int p = x[i] >= 'A' && x[i] <= 'Z' ? x[i] + 32 : x[i], q = y[i] >= 'A' && y[i] <= 'Z' ? y[i] + 32 : y[i];
|
||||
if (p != q) return p - q;
|
||||
}
|
||||
return x.Length - y.Length;
|
||||
}
|
||||
|
||||
/// <summary>A RomFS path as the game looks it up (host/mods.c lower_slash): "/" between folders, A to Z in lower case.</summary>
|
||||
internal static string Key(string rel)
|
||||
{
|
||||
var s = new StringBuilder(rel.Length);
|
||||
foreach (var c in rel) s.Append(c == '\\' ? '/' : c >= 'A' && c <= 'Z' ? (char)(c + 32) : c);
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
/// <summary>A mod's place in the list: its path as the game sorts it, read without the switches.</summary>
|
||||
internal static string Place(string rel) => string.Join("/", rel.Split('/').Select(p => p.TrimStart('-', '_')));
|
||||
|
||||
/// <summary>What a mod carries, in words: "1,204 game files, 2 code patch files, 1 cheat file".</summary>
|
||||
public static string Carries(Mod m)
|
||||
{
|
||||
string Some(int n, string one, string many) => n.ToString("N0", System.Globalization.CultureInfo.InvariantCulture) + " " + (n == 1 ? one : many);
|
||||
var parts = new List<string>();
|
||||
if (m.Files.Count > 0 || !m.Code) parts.Add(m.RomfsIsLink ? "a romfs folder that is a link (the game leaves it out)" : Some(m.Files.Count, "game file", "game files"));
|
||||
if (m.Patches > 0) parts.Add(Some(m.Patches, "code patch file", "code patch files"));
|
||||
if (m.Cheats > 0) parts.Add(Some(m.Cheats, "cheat file", "cheat files"));
|
||||
return string.Join(", ", parts);
|
||||
}
|
||||
|
||||
/// <summary>The files more than one of the mods that are on carry, each with its mods in the order the game loads them.</summary>
|
||||
public static List<Conflict> Conflicts(IEnumerable<Mod> mods)
|
||||
{
|
||||
var by = new Dictionary<string, Conflict>(StringComparer.Ordinal);
|
||||
foreach (var m in mods.Where(m => m.On))
|
||||
foreach (var f in m.Files)
|
||||
{
|
||||
if (!by.TryGetValue(f, out var c)) by[f] = c = new Conflict { File = f };
|
||||
if (!c.Mods.Contains(m)) c.Mods.Add(m);
|
||||
}
|
||||
return by.Values.Where(c => c.Mods.Count > 1).OrderBy(c => c.File, StringComparer.Ordinal).ToList();
|
||||
}
|
||||
|
||||
/// <summary>For one mod: each other mod it shares files with, how many, and whether this one wins them (it loads later).</summary>
|
||||
public static List<(Mod Other, int Files, bool Wins)> Shared(Mod mod, IList<Mod> all, IEnumerable<Conflict> conflicts)
|
||||
{
|
||||
var count = new Dictionary<Mod, int>();
|
||||
foreach (var c in conflicts.Where(c => c.Mods.Contains(mod)))
|
||||
foreach (var other in c.Mods.Where(o => o != mod))
|
||||
count[other] = count.TryGetValue(other, out var n) ? n + 1 : 1;
|
||||
return count.OrderBy(p => all.IndexOf(p.Key)).Select(p => (p.Key, p.Value, all.IndexOf(mod) > all.IndexOf(p.Key))).ToList();
|
||||
}
|
||||
|
||||
/// <summary>Every conflict as text, for the clipboard: the file, the mods that carry it, and which one the game takes.</summary>
|
||||
public static string ConflictText(IEnumerable<Conflict> conflicts)
|
||||
{
|
||||
var s = new StringBuilder();
|
||||
foreach (var c in conflicts)
|
||||
s.AppendLine(c.File + " <- " + c.Winner.Rel + " wins over " + string.Join(", ", c.Mods.Take(c.Mods.Count - 1).Select(m => m.Rel)));
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
/// <summary>The code patches of the mods that are on, as one short mark: it changes when such a mod is added, removed, switched
|
||||
/// or edited, or when their order changes, and stays when only RomFS mods or cheats change or the folders are numbered anew.
|
||||
/// "" when no mod that is on carries any. FNV-1a 64 over the UTF-16 units of the lines joined by \n, as 16 hex digits.</summary>
|
||||
public static string CodeState(IEnumerable<Mod> mods)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
foreach (var m in mods.Where(m => m.On && m.Built))
|
||||
{
|
||||
lines.Add("mod " + m.Name);
|
||||
foreach (var part in new[] { "exefs" }) // (not "cheats": the game reads those itself, at its start)
|
||||
{
|
||||
var dir = Path.Combine(m.Path, part);
|
||||
string[] files = { };
|
||||
try { if (Directory.Exists(dir) && !IsLink(dir)) files = Directory.GetFiles(dir, "*", SearchOption.AllDirectories); } catch (Exception) { }
|
||||
foreach (var f in files.OrderBy(f => f, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
var info = new FileInfo(f);
|
||||
// (the relative path as the old Setup wrote it, with \ on Windows: a mark kept by an old Setup still matches)
|
||||
lines.Add(part + f.Substring(dir.Length).ToLowerInvariant() + "|" + info.Length + "|" + info.LastWriteTimeUtc.Ticks);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (lines.Count == 0) return "";
|
||||
return InstanceLock.Fnv1a64(string.Join("\n", lines)).ToString("x16");
|
||||
}
|
||||
|
||||
/// <summary>Is the game to be built again for its mods? built is the mark kept at the last build: null when none (then any code
|
||||
/// a mod that is on carries is news), and anything that is no mark ("changed") never matches.</summary>
|
||||
public static bool NeedsBuild(string state, string? built) => built == null ? state.Length > 0 : state != built;
|
||||
|
||||
/// <summary>The folders of the mods folder that are mods or hold them, in the order the game loads them.</summary>
|
||||
public static List<string> Tops(IEnumerable<Mod> mods) => mods.Select(m => m.Top).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
|
||||
|
||||
internal static bool IsLink(string path)
|
||||
{
|
||||
try { return (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0; } catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
static readonly HashSet<string> Devices = new(StringComparer.OrdinalIgnoreCase) { "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$" };
|
||||
|
||||
/// <summary>Is this a name Windows keeps for a device, with or without an extension (NUL, con.txt)? Kept on Linux too: mods and
|
||||
/// saves move between systems.</summary>
|
||||
public static bool IsDevice(string name)
|
||||
{
|
||||
var dot = name.IndexOf('.');
|
||||
var stem = (dot >= 0 ? name.Substring(0, dot) : name).TrimEnd(' ');
|
||||
// (COM1 to COM9 and LPT1 to LPT9; Windows takes the raised digits 1, 2 and 3 for digits there too)
|
||||
if (stem.Length == 4 && (stem.StartsWith("COM", StringComparison.OrdinalIgnoreCase) || stem.StartsWith("LPT", StringComparison.OrdinalIgnoreCase)))
|
||||
return stem[3] >= '1' && stem[3] <= '9' || stem[3] == (char)0xB9 || stem[3] == (char)0xB2 || stem[3] == (char)0xB3;
|
||||
return Devices.Contains(stem);
|
||||
}
|
||||
|
||||
/// <summary>Why a file of an archive must not be unpacked under its name, null when it may be: a path that leaves the folder
|
||||
/// it is unpacked into (from the disk's root, with a drive's letter, through ..), a device's name, a colon (a hidden stream of
|
||||
/// another file) and, where the name is known exactly (exact: a zip's own list), what Windows would drop or refuse.</summary>
|
||||
public static string? Unsafe(string name, bool exact)
|
||||
{
|
||||
var n = name.Replace('\\', '/');
|
||||
if (n.Trim().Length == 0) return "a file without a name";
|
||||
if (n[0] == '/') return "a path that starts at the disk's root";
|
||||
if (n.IndexOf(':') >= 0) return "a name with a colon or a drive's letter";
|
||||
var parts = n.Split('/').Where(p => p.Length > 0 && p != ".").ToArray();
|
||||
if (parts.Length > MaxDepth) return "folders more than " + MaxDepth + " deep";
|
||||
foreach (var p in parts)
|
||||
{
|
||||
if (p == "..") return "a path that leaves its own folder (..)";
|
||||
if (p.All(c => c == '.' || c == ' ')) return "a name of dots and spaces only";
|
||||
if (IsDevice(p)) return "a name Windows keeps for a device (" + p + ")";
|
||||
if (!exact) continue;
|
||||
if (p[p.Length - 1] == '.' || p[p.Length - 1] == ' ') return "a name that ends in a dot or a space, which Windows drops";
|
||||
if (p.Any(c => c < 32 || "<>\"|?*".IndexOf(c) >= 0)) return "a name with a character Windows does not allow";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>A name for the mod's folder from an archive's or a folder's name: what Windows allows, and nothing in front that
|
||||
/// would switch the mod off or hide it from the game.</summary>
|
||||
public static string Clean(string name)
|
||||
{
|
||||
var s = new string(name.Where(c => c >= 32 && "<>:\"/\\|?*".IndexOf(c) < 0).ToArray()).Trim();
|
||||
s = s.TrimStart('-', '_', '.', ' ').TrimEnd('.', ' ');
|
||||
if (s.Length > 80) s = s.Substring(0, 80).TrimEnd('.', ' ');
|
||||
return s.Length == 0 || IsDevice(s) ? "Mod" : s;
|
||||
}
|
||||
|
||||
/// <summary>A folder's name in an archive that says nothing about the mod: an emulator's layout, or the part itself.</summary>
|
||||
internal static bool Generic(string name) =>
|
||||
Regex.IsMatch(name, "^[0-9A-Fa-f]{16}$") || new[] { "contents", "atmosphere", "mods", "mod" }.Any(g => string.Equals(g, name, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
internal static string Short(string name) => name.Length > 120 ? name.Substring(0, 117) + "..." : name;
|
||||
}
|
||||
89
launcher/Logic/Platform/IPlatform.cs
Normal file
89
launcher/Logic/Platform/IPlatform.cs
Normal file
@@ -0,0 +1,89 @@
|
||||
// What differs between Windows and Linux, behind one face (DESIGN.md 8: "the Windows-only parts behind an IPlatform";
|
||||
// research/02 section 11 lists each Windows mechanism and its Linux equivalent). Everything else in Triforce.Logic is
|
||||
// plain .NET and the same on both.
|
||||
//
|
||||
// TRIFORCE_TEST_ROOT=<folder> (old Setup.cs Install.TestRoot) keeps a whole install inside one folder on both systems: the
|
||||
// settings are <root>\registry.txt, the shortcuts, the build's work folder, the default game folder, the emulators' saves
|
||||
// and Steam are folders inside it, and nothing outside it is written (TriforceContext.Allowed). A test run never reads or
|
||||
// writes the real registry, the real shortcuts, the real Steam or the real game.
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>Where a shortcut to the launcher goes.</summary>
|
||||
public enum ShortcutPlace
|
||||
{
|
||||
/// <summary>Windows: the desktop's Triforce.lnk. Linux: ~/Desktop/triforce-launcher.desktop when there is a desktop folder.</summary>
|
||||
Desktop,
|
||||
/// <summary>Windows: Start menu\Programs\Triforce\Triforce.lnk. Linux: ~/.local/share/applications/triforce-launcher.desktop.</summary>
|
||||
StartMenu,
|
||||
}
|
||||
|
||||
/// <summary>A shortcut's contents.</summary>
|
||||
public sealed record Shortcut(string Target, string Arguments, string WorkingDirectory, string Icon, string Description, string Name = "Triforce");
|
||||
|
||||
/// <summary>Something the App shows as a system notification (a build finished while the window was not in front, DESIGN 6).</summary>
|
||||
public sealed record LauncherNotification(string Title, string Text);
|
||||
|
||||
/// <summary>A running program: its process id, name and, when it can be read, the full path of its executable.</summary>
|
||||
public sealed record RunningProcess(int Id, string Name, string? Exe);
|
||||
|
||||
public interface IPlatform
|
||||
{
|
||||
bool IsWindows { get; }
|
||||
/// <summary>TRIFORCE_TEST_ROOT, as a full path, or null.</summary>
|
||||
string? TestRoot { get; }
|
||||
/// <summary>An environment variable as this context sees it (a test's own values first).</summary>
|
||||
string? Env(string name);
|
||||
/// <summary>The settings: HKCU\Software\Triforce (Windows), ~/.config/triforce/builder.ini (Linux), registry.txt (test run).</summary>
|
||||
ISettingsStore Settings { get; }
|
||||
|
||||
// ---- paths ----
|
||||
/// <summary>Windows %LOCALAPPDATA%\Programs\Triforce; Linux the self-update root ${XDG_DATA_HOME}/triforce/builder.</summary>
|
||||
string DefaultInstallDir { get; }
|
||||
/// <summary>make_game.py's work folder (its default --work): build_times.json, objcache, sa... (research/02 1.1, 12 section 2).</summary>
|
||||
string WorkFolder { get; }
|
||||
string DefaultGameFolder { get; }
|
||||
/// <summary>Where setup.log is written for an install folder (Windows: the folder itself; Linux ${XDG_STATE_HOME}/triforce).</summary>
|
||||
string LogFolder(string home);
|
||||
/// <summary>Where NVIDIA's DLSS SDK is fetched to: beside the tools, never inside them (an update replaces those whole).</summary>
|
||||
string NgxSdkFolder(string home);
|
||||
/// <summary>The save folder of a game folder: Windows <game>\user\save\<uid>; Linux ${XDG_DATA_HOME}/hookshot/save/<uid>.</summary>
|
||||
string SaveFolder(string game, string uid);
|
||||
/// <summary>The folders emulators keep their data in: (Roaming, Local) on Windows; (data, config) on Linux.</summary>
|
||||
(string Roaming, string Local) EmulatorDataRoots { get; }
|
||||
/// <summary>Steam folders to look in, in order (test run: <root>\Steam only).</summary>
|
||||
IReadOnlyList<string> SteamRoots();
|
||||
|
||||
// ---- shortcuts and the shell ----
|
||||
string ShortcutPath(ShortcutPlace place);
|
||||
void CreateShortcut(ShortcutPlace place, Shortcut shortcut);
|
||||
/// <summary>Removes the launcher's shortcuts (both places); quietly when one cannot be.</summary>
|
||||
void RemoveShortcuts();
|
||||
/// <summary>Explorer / xdg-open on a folder. Not in a test run (nothing opens a window there).</summary>
|
||||
void OpenFolder(string folder);
|
||||
/// <summary>The App listens and shows it (a toast, a desktop notification).</summary>
|
||||
event EventHandler<LauncherNotification>? NotificationRequested;
|
||||
void Notify(string title, string text);
|
||||
|
||||
// ---- processes ----
|
||||
/// <summary>Starts a program so that it and every program it starts can be stopped together (KillTree). Linux: setsid, its
|
||||
/// own process group; Windows: as is (taskkill /T walks the tree).</summary>
|
||||
Process StartTree(ProcessStartInfo info);
|
||||
/// <summary>Stops a program and its children, waiting up to 5 s: taskkill /PID n /T /F; kill(-pgid, SIGTERM) then SIGKILL.</summary>
|
||||
void KillTree(Process process);
|
||||
/// <summary>The running programs of these names (case-insensitive), with their executables where they can be read.</summary>
|
||||
IReadOnlyList<RunningProcess> FindProcesses(params string[] names);
|
||||
|
||||
// ---- disks ----
|
||||
/// <summary>Free bytes for this user on the disk of a folder (the nearest existing folder above it); null when unknown.</summary>
|
||||
long? FreeBytes(string folder);
|
||||
/// <summary>The disk as the player knows it: C:\ on Windows, the mount point on Linux.</summary>
|
||||
string Disk(string folder);
|
||||
/// <summary>Is this the error of a disk that filled while it was written to? (ERROR_DISK_FULL / ENOSPC)</summary>
|
||||
bool IsDiskFull(Exception? e);
|
||||
/// <summary>from over to in one step (MoveFileExW REPLACE_EXISTING|WRITE_THROUGH; rename(2)).</summary>
|
||||
void ReplaceFile(string from, string to);
|
||||
/// <summary>Does a file have a second name (a hard link)? Writing one writes the other.</summary>
|
||||
bool HasOtherName(string file);
|
||||
}
|
||||
256
launcher/Logic/Platform/LinuxPlatform.cs
Normal file
256
launcher/Logic/Platform/LinuxPlatform.cs
Normal file
@@ -0,0 +1,256 @@
|
||||
// Linux (the AppImage, the Steam Deck): the Tk builder's layout (research/12 section 2) and the equivalents research/02
|
||||
// section 11 names for each Windows mechanism. NOT run on this PC (Windows): every Linux path here is ported from the
|
||||
// Python/shell it replaces and should be checked on a real Linux machine or a Deck before release.
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
public sealed class LinuxPlatform : PlatformBase
|
||||
{
|
||||
public LinuxPlatform(IReadOnlyDictionary<string, string?>? env = null) : base(env)
|
||||
{
|
||||
Settings = TestRoot != null ? new TestRootSettingsStore(TestRoot) : new IniSettingsStore(Path.Combine(ConfigHome, "triforce", "builder.ini"));
|
||||
}
|
||||
|
||||
public override bool IsWindows => false;
|
||||
public override ISettingsStore Settings { get; }
|
||||
|
||||
string HomeDir => TestRoot ?? Env("HOME") ?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
|
||||
// (XDG, honoured as the Tk builder does: config, data, cache; the game's own saves_dir takes XDG_DATA_HOME only when absolute)
|
||||
string Xdg(string name, string fallback, string testSub)
|
||||
{
|
||||
if (TestRoot != null) return Path.Combine(TestRoot, testSub);
|
||||
return Env(name) is { Length: > 0 } v && v.StartsWith('/') ? v : Path.Combine(HomeDir, fallback);
|
||||
}
|
||||
|
||||
public string ConfigHome => Xdg("XDG_CONFIG_HOME", ".config", "config");
|
||||
public string DataHome => Xdg("XDG_DATA_HOME", Path.Combine(".local", "share"), "data");
|
||||
string CacheHome => Xdg("XDG_CACHE_HOME", ".cache", "cache");
|
||||
string StateHome => Xdg("XDG_STATE_HOME", Path.Combine(".local", "state"), "state");
|
||||
|
||||
/// <summary>linux_update.data_root(): ${HOOKSHOT_BUILDER_HOME:-${XDG_DATA_HOME:-~/.local/share}}/triforce/builder: the self-update
|
||||
/// root (current, versions/<tag>), read by the game (host/hos_update.c) and the folder launcher (hookshot-folder).</summary>
|
||||
public override string DefaultInstallDir =>
|
||||
Path.Combine(TestRoot == null && Env("HOOKSHOT_BUILDER_HOME") is { Length: > 0 } b ? b : DataHome, "triforce", "builder");
|
||||
|
||||
public override string WorkFolder => Path.Combine(CacheHome, "triforce-build");
|
||||
public override string DefaultGameFolder => Path.Combine(HomeDir, "Games", "Triforce");
|
||||
public override string LogFolder(string home) => Path.Combine(StateHome, "triforce");
|
||||
// (hookshot_builder.py ngx_sdk_dir: beside the builder's versions, kept across updates)
|
||||
public override string NgxSdkFolder(string home) => Path.Combine(DefaultInstallDir, "ngx-sdk");
|
||||
// (host/hos_main.c saves_dir: $XDG_DATA_HOME/hookshot, outside the game folder so a rebuild keeps them)
|
||||
public override string SaveFolder(string game, string uid) => Path.Combine(DataHome, "hookshot", "save", uid);
|
||||
public override (string Roaming, string Local) EmulatorDataRoots => (DataHome, ConfigHome);
|
||||
|
||||
public override IReadOnlyList<string> SteamRoots()
|
||||
{
|
||||
if (TestRoot != null) return new[] { Path.Combine(TestRoot, "Steam") };
|
||||
// (research/12 section 6, guess-level: verify on a Deck. ~/.steam/steam is a link to the real folder)
|
||||
return new[]
|
||||
{
|
||||
Path.Combine(HomeDir, ".steam", "steam"), Path.Combine(HomeDir, ".local", "share", "Steam"),
|
||||
Path.Combine(HomeDir, ".var", "app", "com.valvesoftware.Steam", ".local", "share", "Steam"),
|
||||
};
|
||||
}
|
||||
|
||||
// ---- shortcuts: .desktop files ----
|
||||
|
||||
public override string ShortcutPath(ShortcutPlace place) => place == ShortcutPlace.Desktop
|
||||
? Path.Combine(HomeDir, "Desktop", "triforce-launcher.desktop")
|
||||
: Path.Combine(DataHome, "applications", "triforce-launcher.desktop");
|
||||
|
||||
public override void CreateShortcut(ShortcutPlace place, Shortcut s)
|
||||
{
|
||||
var file = ShortcutPath(place);
|
||||
if (place == ShortcutPlace.Desktop && !Directory.Exists(Path.GetDirectoryName(file))) return; // (no desktop folder: none made)
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(file)!);
|
||||
File.WriteAllText(file, DesktopEntry(s.Name, s.Description, s.Target, s.Arguments, s.WorkingDirectory, s.Icon), new UTF8Encoding(false));
|
||||
if (!OperatingSystem.IsWindows()) try { File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | UnixFileMode.GroupRead | UnixFileMode.OtherRead); } catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>A desktop entry. Refuses CR, LF and NUL in any value (a line break would start another key: hookshot_builder.py add_to_menu).</summary>
|
||||
public static string DesktopEntry(string name, string comment, string target, string arguments, string workDir, string icon, string? wmClass = null)
|
||||
{
|
||||
foreach (var v in new[] { name, comment, target, arguments, workDir, icon, wmClass ?? "" })
|
||||
if (v.IndexOfAny(new[] { '\r', '\n', '\0' }) >= 0) throw new ArgumentException("A path or name with a line break cannot go into a menu entry.");
|
||||
var exec = DesktopExec(target) + (arguments.Length > 0 ? " " + arguments : "");
|
||||
return "[Desktop Entry]\nType=Application\nName=" + name + "\nComment=" + comment + "\nExec=" + exec + "\nPath=" + workDir + "\nIcon=" + icon +
|
||||
"\nCategories=Game;\nTerminal=false\n" + (wmClass != null ? "StartupWMClass=" + wmClass + "\n" : "");
|
||||
}
|
||||
|
||||
/// <summary>One Exec argument (hookshot_builder.py desktop_exec): a % is a field code, so it is doubled; inside the quotes the
|
||||
/// Desktop Entry spec wants " ` $ \ each preceded by a backslash, and every backslash written twice because the file's string
|
||||
/// escaping is applied first (so a literal backslash is four, and a dollar two backslashes and the dollar).</summary>
|
||||
public static string DesktopExec(string path)
|
||||
{
|
||||
var escaped = path.Replace("\\", "\\\\\\\\");
|
||||
foreach (var c in new[] { "\"", "`", "$" }) escaped = escaped.Replace(c, "\\\\" + c);
|
||||
return "\"" + escaped.Replace("%", "%%") + "\"";
|
||||
}
|
||||
|
||||
public override void RemoveShortcuts()
|
||||
{
|
||||
foreach (var p in new[] { ShortcutPlace.Desktop, ShortcutPlace.StartMenu })
|
||||
try { var f = ShortcutPath(p); if (File.Exists(f)) File.Delete(f); } catch (Exception) { }
|
||||
}
|
||||
|
||||
protected override void OpenFolderNow(string folder) =>
|
||||
Process.Start(new ProcessStartInfo("xdg-open") { ArgumentList = { folder }, UseShellExecute = false })?.Dispose();
|
||||
|
||||
// ---- processes ----
|
||||
|
||||
[DllImport("libc", SetLastError = true)]
|
||||
static extern int kill(int pid, int sig);
|
||||
const int SIGTERM = 15, SIGKILL = 9;
|
||||
|
||||
static string? Which(string name)
|
||||
{
|
||||
foreach (var dir in (Environment.GetEnvironmentVariable("PATH") ?? "/usr/bin:/bin").Split(':'))
|
||||
if (dir.Length > 0 && File.Exists(Path.Combine(dir, name))) return Path.Combine(dir, name);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Through setsid, so the program leads a process group of its own and Stop reaches the clang and lift workers too
|
||||
/// (research/12 4.6: Process cannot start a child in a new session). A child .NET starts is no group leader, so setsid
|
||||
/// calls setsid() and execs in place: the process id is the group's id. -w: should it have to fork, it waits.</summary>
|
||||
public override Process StartTree(ProcessStartInfo info)
|
||||
{
|
||||
if (Which("setsid") is { } setsid)
|
||||
{
|
||||
var wrapped = new ProcessStartInfo(setsid)
|
||||
{
|
||||
UseShellExecute = false, WorkingDirectory = info.WorkingDirectory, CreateNoWindow = info.CreateNoWindow,
|
||||
RedirectStandardOutput = info.RedirectStandardOutput, RedirectStandardError = info.RedirectStandardError,
|
||||
RedirectStandardInput = info.RedirectStandardInput,
|
||||
StandardOutputEncoding = info.StandardOutputEncoding, StandardErrorEncoding = info.StandardErrorEncoding,
|
||||
};
|
||||
wrapped.ArgumentList.Add("-w");
|
||||
wrapped.ArgumentList.Add(info.FileName);
|
||||
foreach (var a in info.ArgumentList) wrapped.ArgumentList.Add(a);
|
||||
wrapped.Environment.Clear();
|
||||
foreach (var kv in info.Environment) wrapped.Environment[kv.Key] = kv.Value;
|
||||
return Process.Start(wrapped) ?? throw new InvalidOperationException("setsid did not start.");
|
||||
}
|
||||
return Process.Start(info) ?? throw new InvalidOperationException(info.FileName + " did not start.");
|
||||
}
|
||||
|
||||
/// <summary>kill(-pgid, SIGTERM), then SIGKILL after 5 s (the Tk builder's killpg; make_game reports an outside SIGTERM as
|
||||
/// "out of memory", but a Stop is told apart by the runner, which knows it asked).</summary>
|
||||
public override void KillTree(Process process)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (process.HasExited) return;
|
||||
if (kill(-process.Id, SIGTERM) != 0) kill(process.Id, SIGTERM);
|
||||
if (!process.WaitForExit(5000))
|
||||
{
|
||||
kill(-process.Id, SIGKILL);
|
||||
try { process.Kill(entireProcessTree: true); } catch (Exception) { }
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
try { process.Kill(entireProcessTree: true); } catch (Exception) { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>/proc/<pid>/comm (the first 15 characters of the name) and /proc/<pid>/exe.</summary>
|
||||
public override IReadOnlyList<RunningProcess> FindProcesses(params string[] names)
|
||||
{
|
||||
var found = new List<RunningProcess>();
|
||||
string[] dirs;
|
||||
try { dirs = Directory.GetDirectories("/proc"); } catch (Exception) { return found; }
|
||||
foreach (var d in dirs)
|
||||
{
|
||||
if (!int.TryParse(Path.GetFileName(d), out var pid)) continue;
|
||||
string comm;
|
||||
try { comm = File.ReadAllText(Path.Combine(d, "comm")).Trim(); } catch (Exception) { continue; }
|
||||
string? exe = null;
|
||||
try { exe = new FileInfo(Path.Combine(d, "exe")).LinkTarget; } catch (Exception) { }
|
||||
var exeName = exe != null ? Path.GetFileName(exe) : null;
|
||||
foreach (var n in names)
|
||||
if (string.Equals(comm, n.Length > 15 ? n.Substring(0, 15) : n, StringComparison.OrdinalIgnoreCase) ||
|
||||
exeName != null && string.Equals(exeName, n, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
found.Add(new RunningProcess(pid, n, exe));
|
||||
break;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
// ---- disks ----
|
||||
|
||||
// (struct statvfs, x86_64 and aarch64 glibc: eleven unsigned longs then six ints of padding)
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct StatVfs
|
||||
{
|
||||
public ulong bsize, frsize, blocks, bfree, bavail, files, ffree, favail, fsid, flag, namemax;
|
||||
public int s0, s1, s2, s3, s4, s5;
|
||||
}
|
||||
|
||||
[DllImport("libc", SetLastError = true, CharSet = CharSet.Ansi)]
|
||||
static extern int statvfs(string path, out StatVfs buf);
|
||||
|
||||
public override long? FreeBytes(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
for (var d = Path.GetFullPath(folder); !string.IsNullOrEmpty(d); d = Path.GetDirectoryName(d))
|
||||
if (Directory.Exists(d))
|
||||
return statvfs(d, out var s) == 0 ? (long)Math.Min(s.bavail * s.frsize, (ulong)long.MaxValue) : null;
|
||||
}
|
||||
catch (Exception) { }
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The mount point that holds the folder (the longest one that is a prefix of it).</summary>
|
||||
public override string Disk(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
var full = Path.GetFullPath(folder);
|
||||
var best = "/";
|
||||
foreach (var d in DriveInfo.GetDrives())
|
||||
{
|
||||
var root = d.RootDirectory.FullName.TrimEnd('/') + "/";
|
||||
if ((full + "/").StartsWith(root, StringComparison.Ordinal) && root.Length > best.Length) best = d.RootDirectory.FullName;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
catch (Exception) { return folder; }
|
||||
}
|
||||
|
||||
public override bool IsDiskFull(Exception? e)
|
||||
{
|
||||
for (; e != null; e = e.InnerException)
|
||||
if (e is IOException)
|
||||
{
|
||||
var code = e.HResult & 0xFFFF;
|
||||
if (code == 28 || code == 122 || code == 112 || code == 39) return true; // (ENOSPC, EDQUOT, and the Windows codes .NET may map them to)
|
||||
if (e.Message.Contains("No space left", StringComparison.OrdinalIgnoreCase) || e.Message.Contains("quota", StringComparison.OrdinalIgnoreCase)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public override void ReplaceFile(string from, string to) => File.Move(from, to, true); // (rename(2): one step)
|
||||
|
||||
[DllImport("libc", SetLastError = true, CharSet = CharSet.Ansi)]
|
||||
static extern int lstat(string path, byte[] buf);
|
||||
|
||||
/// <summary>st_nlink > 1 (x86_64 glibc layout: st_dev 8, st_ino 8, st_nlink 8 at offset 16; the AppImage is x86_64 only).
|
||||
/// Elsewhere unknown: false.</summary>
|
||||
public override bool HasOtherName(string file)
|
||||
{
|
||||
if (RuntimeInformation.ProcessArchitecture != Architecture.X64) return false;
|
||||
try
|
||||
{
|
||||
var buf = new byte[256];
|
||||
return lstat(file, buf) == 0 && BitConverter.ToUInt64(buf, 16) > 1;
|
||||
}
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
}
|
||||
60
launcher/Logic/Platform/PlatformBase.cs
Normal file
60
launcher/Logic/Platform/PlatformBase.cs
Normal file
@@ -0,0 +1,60 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>What both platforms share: the environment (with a test's own values first), TRIFORCE_TEST_ROOT, notifications.</summary>
|
||||
public abstract class PlatformBase : IPlatform
|
||||
{
|
||||
readonly IReadOnlyDictionary<string, string?>? env;
|
||||
|
||||
protected PlatformBase(IReadOnlyDictionary<string, string?>? env)
|
||||
{
|
||||
this.env = env;
|
||||
// (old Setup.cs Install.TestRoot: TRIFORCE_TEST_ROOT=<folder> keeps a whole install inside that folder)
|
||||
TestRoot = Env("TRIFORCE_TEST_ROOT") is { Length: > 0 } t ? Path.GetFullPath(t) : null;
|
||||
}
|
||||
|
||||
public string? TestRoot { get; }
|
||||
|
||||
public string? Env(string name) =>
|
||||
env != null && env.TryGetValue(name, out var v) ? v : Environment.GetEnvironmentVariable(name);
|
||||
|
||||
public abstract bool IsWindows { get; }
|
||||
public abstract ISettingsStore Settings { get; }
|
||||
public abstract string DefaultInstallDir { get; }
|
||||
public abstract string WorkFolder { get; }
|
||||
public abstract string DefaultGameFolder { get; }
|
||||
public abstract string LogFolder(string home);
|
||||
public abstract string NgxSdkFolder(string home);
|
||||
public abstract string SaveFolder(string game, string uid);
|
||||
public abstract (string Roaming, string Local) EmulatorDataRoots { get; }
|
||||
public abstract IReadOnlyList<string> SteamRoots();
|
||||
public abstract string ShortcutPath(ShortcutPlace place);
|
||||
public abstract void CreateShortcut(ShortcutPlace place, Shortcut shortcut);
|
||||
public abstract void RemoveShortcuts();
|
||||
|
||||
public void OpenFolder(string folder)
|
||||
{
|
||||
// (a test run opens no window: the old Setup skipped Explorer under a UI script too)
|
||||
if (TestRoot != null) return;
|
||||
try { OpenFolderNow(folder); } catch (Exception) { }
|
||||
}
|
||||
|
||||
protected abstract void OpenFolderNow(string folder);
|
||||
|
||||
public event EventHandler<LauncherNotification>? NotificationRequested;
|
||||
public void Notify(string title, string text) => NotificationRequested?.Invoke(this, new LauncherNotification(title, text));
|
||||
|
||||
public abstract Process StartTree(ProcessStartInfo info);
|
||||
public abstract void KillTree(Process process);
|
||||
public abstract IReadOnlyList<RunningProcess> FindProcesses(params string[] names);
|
||||
public abstract long? FreeBytes(string folder);
|
||||
public abstract string Disk(string folder);
|
||||
public abstract bool IsDiskFull(Exception? e);
|
||||
public abstract void ReplaceFile(string from, string to);
|
||||
public abstract bool HasOtherName(string file);
|
||||
|
||||
/// <summary>The platform this program runs on.</summary>
|
||||
public static IPlatform Create(IReadOnlyDictionary<string, string?>? env = null) =>
|
||||
OperatingSystem.IsWindows() ? new WindowsPlatform(env) : new LinuxPlatform(env);
|
||||
}
|
||||
226
launcher/Logic/Platform/Settings.cs
Normal file
226
launcher/Logic/Platform/Settings.cs
Normal file
@@ -0,0 +1,226 @@
|
||||
// The launcher's small settings, and the Apps-list entry that says where it is installed.
|
||||
// Windows HKCU\Software\Triforce (REG_SZ strings) and HKCU\...\Uninstall\Triforce (old Setup.cs:219-259)
|
||||
// test run <TRIFORCE_TEST_ROOT>\registry.txt: one line per value, "<key>\<name>=<value>", the last line for a name wins.
|
||||
// The same file the old Setup's test runs write, on every system
|
||||
// Linux ${XDG_CONFIG_HOME:-~/.config}/triforce/builder.ini: flat key=value lines, rewritten whole (the Tk builder's file,
|
||||
// builder/linux/hookshot_builder.py load_config/save_config, which keeps keys it does not know). The names the
|
||||
// Tk builder and hookshot-launch read are written under their names there (out, language, dlss)
|
||||
using System.Runtime.Versioning;
|
||||
using System.Text;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>The values the launcher keeps between runs (old research/02 1.2 names).</summary>
|
||||
public static class SettingNames
|
||||
{
|
||||
public const string Desktop = "Desktop", StartMenu = "StartMenu", Language = "Language", GameFolder = "GameFolder", Dlss = "Dlss",
|
||||
SetupSkip = "SetupSkip", Sounds = "Sounds", ModsBuilt = "ModsBuilt";
|
||||
// (DESIGN 10: kept per user)
|
||||
public const string MusicVolume = "MusicVolume", SoundVolume = "SoundVolume", Muted = "Muted";
|
||||
}
|
||||
|
||||
/// <summary>Where the settings are kept. Get/Set work on the settings; the Uninstall* calls on the Apps-list entry (Windows,
|
||||
/// and a test run's registry.txt; nothing elsewhere).</summary>
|
||||
public interface ISettingsStore
|
||||
{
|
||||
string? Get(string name);
|
||||
void Set(string name, string value);
|
||||
/// <summary>Every setting gone (uninstall).</summary>
|
||||
void RemoveAll();
|
||||
string? GetUninstall(string name);
|
||||
void SetUninstall(string name, string value);
|
||||
void SetUninstallNumber(string name, int value);
|
||||
void RemoveUninstall();
|
||||
}
|
||||
|
||||
/// <summary>The keys as the old Setup named them.</summary>
|
||||
static class Keys
|
||||
{
|
||||
public const string Uninstall = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\Triforce";
|
||||
public const string Settings = @"Software\Triforce";
|
||||
}
|
||||
|
||||
/// <summary>HKCU, as the old Setup kept it. Only HKCU: no admin rights, nothing in HKLM.</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
sealed class RegistrySettingsStore : ISettingsStore
|
||||
{
|
||||
static string? Read(string key, string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var k = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(key);
|
||||
return k?.GetValue(name) as string;
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
static void Write(string key, string name, object value)
|
||||
{
|
||||
using var k = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(key);
|
||||
if (value is int n) k.SetValue(name, n, Microsoft.Win32.RegistryValueKind.DWord); else k.SetValue(name, value);
|
||||
}
|
||||
|
||||
static void Remove(string key)
|
||||
{
|
||||
try { Microsoft.Win32.Registry.CurrentUser.DeleteSubKeyTree(key, false); } catch (Exception) { }
|
||||
}
|
||||
|
||||
public string? Get(string name) => Read(Keys.Settings, name);
|
||||
public void Set(string name, string value) => Write(Keys.Settings, name, value);
|
||||
public void RemoveAll() => Remove(Keys.Settings);
|
||||
public string? GetUninstall(string name) => Read(Keys.Uninstall, name);
|
||||
public void SetUninstall(string name, string value) => Write(Keys.Uninstall, name, value);
|
||||
public void SetUninstallNumber(string name, int value) => Write(Keys.Uninstall, name, value);
|
||||
public void RemoveUninstall() => Remove(Keys.Uninstall);
|
||||
}
|
||||
|
||||
/// <summary>(testing: TRIFORCE_TEST_ROOT) what would go to the registry, as a text file in the test folder (old Setup.cs:228-259):
|
||||
/// "<key>\<name>=<value>", the last line for a name wins, a write rewrites the file without the name's older lines.</summary>
|
||||
sealed class TestRootSettingsStore : ISettingsStore
|
||||
{
|
||||
readonly string root, file;
|
||||
readonly object gate = new();
|
||||
public TestRootSettingsStore(string root) { this.root = root; file = Path.Combine(root, "registry.txt"); }
|
||||
|
||||
string? Read(string key, string name)
|
||||
{
|
||||
var start = key + "\\" + name + "=";
|
||||
lock (gate)
|
||||
return File.Exists(file) ? File.ReadAllLines(file).LastOrDefault(l => l.StartsWith(start, StringComparison.Ordinal))?.Substring(start.Length) : null;
|
||||
}
|
||||
|
||||
void Write(string key, string name, string value)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
Directory.CreateDirectory(root);
|
||||
var start = key + "\\" + name + "=";
|
||||
var lines = File.Exists(file) ? File.ReadAllLines(file).Where(l => !l.StartsWith(start, StringComparison.Ordinal)).ToList() : new List<string>();
|
||||
lines.Add(start + value);
|
||||
File.WriteAllLines(file, lines);
|
||||
}
|
||||
}
|
||||
|
||||
void Remove(string key)
|
||||
{
|
||||
lock (gate)
|
||||
if (File.Exists(file)) File.WriteAllLines(file, File.ReadAllLines(file).Where(l => !l.StartsWith(key + "\\", StringComparison.Ordinal)).ToList());
|
||||
}
|
||||
|
||||
public string? Get(string name) => Read(Keys.Settings, name);
|
||||
public void Set(string name, string value) => Write(Keys.Settings, name, value);
|
||||
public void RemoveAll() => Remove(Keys.Settings);
|
||||
public string? GetUninstall(string name) => Read(Keys.Uninstall, name);
|
||||
public void SetUninstall(string name, string value) => Write(Keys.Uninstall, name, value);
|
||||
public void SetUninstallNumber(string name, int value) => Write(Keys.Uninstall, name, value.ToString());
|
||||
public void RemoveUninstall() => Remove(Keys.Uninstall);
|
||||
}
|
||||
|
||||
/// <summary>Linux: builder.ini, the Tk builder's own file (flat key=value, split on the first =, rewritten whole). The values
|
||||
/// both read share a name: GameFolder is "out" (hookshot-launch starts the last out= line's game), Language "language",
|
||||
/// Dlss "dlss". Other keys are kept as they are, the Tk builder's too (kind, nup, romfs, exefs, prepare).</summary>
|
||||
sealed class IniSettingsStore : ISettingsStore
|
||||
{
|
||||
readonly string file;
|
||||
readonly object gate = new();
|
||||
public IniSettingsStore(string file) { this.file = file; }
|
||||
public string FilePath => file;
|
||||
|
||||
static string KeyOf(string name) => name switch
|
||||
{
|
||||
SettingNames.GameFolder => "out",
|
||||
SettingNames.Language => "language",
|
||||
SettingNames.Dlss => "dlss",
|
||||
_ => name,
|
||||
};
|
||||
|
||||
List<(string Key, string Value)> Load()
|
||||
{
|
||||
var all = new List<(string, string)>();
|
||||
try
|
||||
{
|
||||
foreach (var line in File.ReadAllLines(file, Encoding.UTF8))
|
||||
{
|
||||
var eq = line.IndexOf('=');
|
||||
if (eq < 0) continue;
|
||||
var key = line.Substring(0, eq);
|
||||
all.RemoveAll(kv => kv.Item1 == key); // (a dict in the Tk builder: the last line for a key wins)
|
||||
all.Add((key, line.Substring(eq + 1)));
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
return all;
|
||||
}
|
||||
|
||||
void Save(List<(string Key, string Value)> all)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(file)!);
|
||||
var tmp = file + ".new";
|
||||
File.WriteAllText(tmp, string.Concat(all.Select(kv => kv.Key + "=" + kv.Value + "\n")), new UTF8Encoding(false));
|
||||
File.Move(tmp, file, true);
|
||||
}
|
||||
|
||||
public string? Get(string name)
|
||||
{
|
||||
lock (gate) { var key = KeyOf(name); var hit = Load().LastOrDefault(kv => kv.Key == key); return hit.Key == null ? null : hit.Value; }
|
||||
}
|
||||
|
||||
public void Set(string name, string value)
|
||||
{
|
||||
if (value.IndexOfAny(new[] { '\n', '\r' }) >= 0) throw new ArgumentException("A setting cannot hold a line break.");
|
||||
lock (gate)
|
||||
{
|
||||
var key = KeyOf(name);
|
||||
var all = Load();
|
||||
var at = all.FindIndex(kv => kv.Key == key);
|
||||
if (at >= 0) all[at] = (key, value); else all.Add((key, value));
|
||||
Save(all);
|
||||
}
|
||||
}
|
||||
|
||||
public void RemoveAll()
|
||||
{
|
||||
lock (gate) try { if (File.Exists(file)) File.Delete(file); } catch (Exception) { }
|
||||
}
|
||||
|
||||
// (no Apps list on Linux: the launcher is the AppImage the player keeps where they like)
|
||||
public string? GetUninstall(string name) => null;
|
||||
public void SetUninstall(string name, string value) { }
|
||||
public void SetUninstallNumber(string name, int value) { }
|
||||
public void RemoveUninstall() { }
|
||||
}
|
||||
|
||||
/// <summary>The settings with their names and meanings. Writes are dropped while the context says NoWrites (old --snapshot).</summary>
|
||||
public sealed class Settings
|
||||
{
|
||||
readonly ISettingsStore store;
|
||||
readonly Func<bool> noWrites;
|
||||
internal Settings(ISettingsStore store, Func<bool> noWrites) { this.store = store; this.noWrites = noWrites; }
|
||||
|
||||
public ISettingsStore Store => store;
|
||||
public string? Get(string name) => store.Get(name);
|
||||
public void Set(string name, string value) { if (!noWrites()) store.Set(name, value); }
|
||||
|
||||
/// <summary>The game folder the last good build wrote (its @@done line).</summary>
|
||||
public string? GameFolder { get => Get(SettingNames.GameFolder) is { Length: > 0 } g ? g : null; set => Set(SettingNames.GameFolder, value ?? ""); }
|
||||
/// <summary>The game's language code (Languages.All), null when never chosen.</summary>
|
||||
public string? Language { get => Get(SettingNames.Language); set => Set(SettingNames.Language, value ?? ""); }
|
||||
/// <summary>NVIDIA DLSS chosen, its licence accepted ("1").</summary>
|
||||
public bool Dlss { get => Get(SettingNames.Dlss) == "1"; set => Set(SettingNames.Dlss, value ? "1" : "0"); }
|
||||
/// <summary>A release tag whose launcher could not start on this PC: never fetched again (research/02 2.4a).</summary>
|
||||
public string? SetupSkip { get => Get(SettingNames.SetupSkip); set => Set(SettingNames.SetupSkip, value ?? ""); }
|
||||
/// <summary>Shortcut choices, re-used when a downloaded copy reinstalls over an install (default on).</summary>
|
||||
public bool Desktop { get => Get(SettingNames.Desktop) != "0"; set => Set(SettingNames.Desktop, value ? "1" : "0"); }
|
||||
public bool StartMenu { get => Get(SettingNames.StartMenu) != "0"; set => Set(SettingNames.StartMenu, value ? "1" : "0"); }
|
||||
/// <summary>"<gameFolder>|<16 hex CodeState>" or "<gameFolder>|changed" (Mods.CodeState).</summary>
|
||||
public string? ModsBuilt { get => Get(SettingNames.ModsBuilt); set => Set(SettingNames.ModsBuilt, value ?? ""); }
|
||||
/// <summary>The old sound level: off / low / medium / high.</summary>
|
||||
public string? Sounds { get => Get(SettingNames.Sounds); set => Set(SettingNames.Sounds, value ?? ""); }
|
||||
/// <summary>DESIGN 10: 0..100, default 40.</summary>
|
||||
public int MusicVolume { get => Percent(SettingNames.MusicVolume, 40); set => Set(SettingNames.MusicVolume, Math.Clamp(value, 0, 100).ToString()); }
|
||||
/// <summary>DESIGN 10: 0..100, default 70.</summary>
|
||||
public int SoundVolume { get => Percent(SettingNames.SoundVolume, 70); set => Set(SettingNames.SoundVolume, Math.Clamp(value, 0, 100).ToString()); }
|
||||
public bool Muted { get => Get(SettingNames.Muted) == "1"; set => Set(SettingNames.Muted, value ? "1" : "0"); }
|
||||
|
||||
int Percent(string name, int fallback) => int.TryParse(Get(name), out var v) && v >= 0 && v <= 100 ? v : fallback;
|
||||
}
|
||||
199
launcher/Logic/Platform/WindowsPlatform.cs
Normal file
199
launcher/Logic/Platform/WindowsPlatform.cs
Normal file
@@ -0,0 +1,199 @@
|
||||
// Windows: what the old WPF Setup did, without its window (research/02 sections 1, 5, 11).
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Versioning;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
public sealed class WindowsPlatform : PlatformBase
|
||||
{
|
||||
public WindowsPlatform(IReadOnlyDictionary<string, string?>? env = null) : base(env)
|
||||
{
|
||||
Settings = TestRoot != null ? new TestRootSettingsStore(TestRoot) : new RegistrySettingsStore();
|
||||
}
|
||||
|
||||
public override bool IsWindows => true;
|
||||
public override ISettingsStore Settings { get; }
|
||||
|
||||
/// <summary>%LOCALAPPDATA%, or the test folder (old Setup.cs Install.LocalData).</summary>
|
||||
string LocalData => TestRoot ?? Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
|
||||
public override string DefaultInstallDir => Path.Combine(LocalData, "Programs", "Triforce");
|
||||
// (make_game.py's own default --work is %LOCALAPPDATA%\Triforce\build; a test run passes --work <root>\build)
|
||||
public override string WorkFolder => TestRoot != null ? Path.Combine(TestRoot, "build") : Path.Combine(LocalData, "Triforce", "build");
|
||||
public override string DefaultGameFolder => Path.Combine(TestRoot ?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Games", "Triforce");
|
||||
public override string LogFolder(string home) => home;
|
||||
public override string NgxSdkFolder(string home) => Path.Combine(home, "ngx-sdk");
|
||||
public override string SaveFolder(string game, string uid) => Path.Combine(game, "user", "save", uid);
|
||||
public override (string Roaming, string Local) EmulatorDataRoots => TestRoot != null
|
||||
? (Path.Combine(TestRoot, "Roaming"), Path.Combine(TestRoot, "Local"))
|
||||
: (Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
|
||||
|
||||
public override IReadOnlyList<string> SteamRoots()
|
||||
{
|
||||
if (TestRoot != null) return new[] { Path.Combine(TestRoot, "Steam") };
|
||||
// (Steam's folder as Steam wrote it into the registry (read, never written), else the usual one: old Steam.cs FromRegistry)
|
||||
string? folder = null;
|
||||
try
|
||||
{
|
||||
using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Valve\Steam", false);
|
||||
folder = key?.GetValue("SteamPath") as string;
|
||||
}
|
||||
catch (Exception) { }
|
||||
var list = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(folder)) try { list.Add(Path.GetFullPath(folder.Replace('/', '\\'))); } catch (Exception) { }
|
||||
list.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Steam"));
|
||||
return list;
|
||||
}
|
||||
|
||||
// ---- shortcuts ----
|
||||
|
||||
public override string ShortcutPath(ShortcutPlace place) => place == ShortcutPlace.Desktop
|
||||
? Path.Combine(TestRoot != null ? Path.Combine(TestRoot, "Desktop") : Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "Triforce.lnk")
|
||||
: Path.Combine(StartFolder, "Triforce.lnk");
|
||||
|
||||
string StartFolder => Path.Combine(TestRoot != null ? Path.Combine(TestRoot, "Start Menu") : Environment.GetFolderPath(Environment.SpecialFolder.Programs), "Triforce");
|
||||
|
||||
/// <summary>A .lnk through the WScript.Shell COM object (old Setup.cs Shortcut).</summary>
|
||||
public override void CreateShortcut(ShortcutPlace place, Shortcut s)
|
||||
{
|
||||
var link = ShortcutPath(place);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(link)!);
|
||||
var type = Type.GetTypeFromProgID("WScript.Shell") ?? throw new InvalidOperationException("WScript.Shell is not on this PC.");
|
||||
var shell = Activator.CreateInstance(type)!;
|
||||
try
|
||||
{
|
||||
var lnk = type.InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shell, new object[] { link })!;
|
||||
var t = lnk.GetType();
|
||||
t.InvokeMember("TargetPath", BindingFlags.SetProperty, null, lnk, new object[] { s.Target });
|
||||
t.InvokeMember("Arguments", BindingFlags.SetProperty, null, lnk, new object[] { s.Arguments });
|
||||
t.InvokeMember("WorkingDirectory", BindingFlags.SetProperty, null, lnk, new object[] { s.WorkingDirectory });
|
||||
t.InvokeMember("IconLocation", BindingFlags.SetProperty, null, lnk, new object[] { s.Icon + ",0" });
|
||||
t.InvokeMember("Description", BindingFlags.SetProperty, null, lnk, new object[] { s.Description });
|
||||
t.InvokeMember("Save", BindingFlags.InvokeMethod, null, lnk, null);
|
||||
Marshal.FinalReleaseComObject(lnk);
|
||||
}
|
||||
finally { Marshal.FinalReleaseComObject(shell); }
|
||||
}
|
||||
|
||||
public override void RemoveShortcuts()
|
||||
{
|
||||
try { var f = ShortcutPath(ShortcutPlace.Desktop); if (File.Exists(f)) File.Delete(f); } catch (Exception) { }
|
||||
try { if (Directory.Exists(StartFolder)) Directory.Delete(StartFolder, true); } catch (Exception) { }
|
||||
}
|
||||
|
||||
protected override void OpenFolderNow(string folder) =>
|
||||
Process.Start(new ProcessStartInfo("explorer.exe", "\"" + folder + "\"") { UseShellExecute = true })?.Dispose();
|
||||
|
||||
// ---- processes ----
|
||||
|
||||
public override Process StartTree(ProcessStartInfo info) => Process.Start(info) ?? throw new InvalidOperationException(info.FileName + " did not start.");
|
||||
|
||||
/// <summary>taskkill /PID n /T /F, waiting up to 5 s (old Setup.cs Runner.Cancel).</summary>
|
||||
public override void KillTree(Process process)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (process.HasExited) return;
|
||||
using var k = Process.Start(new ProcessStartInfo("taskkill", "/PID " + process.Id + " /T /F") { CreateNoWindow = true, UseShellExecute = false });
|
||||
k?.WaitForExit(5000);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
try { process.Kill(entireProcessTree: true); } catch (Exception) { }
|
||||
}
|
||||
}
|
||||
|
||||
public override IReadOnlyList<RunningProcess> FindProcesses(params string[] names)
|
||||
{
|
||||
var found = new List<RunningProcess>();
|
||||
foreach (var n in names)
|
||||
foreach (var p in Process.GetProcessesByName(n))
|
||||
using (p)
|
||||
{
|
||||
string? exe = null;
|
||||
try { exe = p.MainModule?.FileName; } catch (Exception) { }
|
||||
found.Add(new RunningProcess(p.Id, n, exe));
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
// ---- disks ----
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
static extern bool GetDiskFreeSpaceExW(string folder, out ulong forCaller, out ulong total, out ulong free);
|
||||
|
||||
public override long? FreeBytes(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
for (var d = Path.GetFullPath(folder); !string.IsNullOrEmpty(d); d = Path.GetDirectoryName(d))
|
||||
if (Directory.Exists(d))
|
||||
return GetDiskFreeSpaceExW(d, out var mine, out _, out _) ? (long)Math.Min(mine, (ulong)long.MaxValue) : null;
|
||||
}
|
||||
catch (Exception) { }
|
||||
return null;
|
||||
}
|
||||
|
||||
public override string Disk(string folder)
|
||||
{
|
||||
try { return Path.GetPathRoot(Path.GetFullPath(folder)) is { Length: > 0 } root ? root : folder; }
|
||||
catch (Exception) { return folder; }
|
||||
}
|
||||
|
||||
public override bool IsDiskFull(Exception? e)
|
||||
{
|
||||
for (; e != null; e = e.InnerException)
|
||||
if (e is IOException && (uint)e.HResult >> 16 == 0x8007 && ((e.HResult & 0xFFFF) == 112 || (e.HResult & 0xFFFF) == 39))
|
||||
return true; // (ERROR_DISK_FULL, ERROR_HANDLE_DISK_FULL)
|
||||
return false;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
static extern bool MoveFileExW(string from, string to, int flags);
|
||||
|
||||
public override void ReplaceFile(string from, string to)
|
||||
{
|
||||
if (!MoveFileExW(from, to, 1 | 8)) // (MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)
|
||||
throw new IOException("Could not put " + to + " in place (Windows error " + Marshal.GetLastWin32Error() + ").");
|
||||
}
|
||||
|
||||
// (BY_HANDLE_FILE_INFORMATION: its three times are pairs of 32-bit numbers, so nothing in it is aligned to 8 bytes)
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
struct FileInformation
|
||||
{
|
||||
public uint Attributes;
|
||||
public long Created, Accessed, Written;
|
||||
public uint Volume, SizeHigh, SizeLow, Links, IndexHigh, IndexLow;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
static extern bool GetFileInformationByHandle(Microsoft.Win32.SafeHandles.SafeFileHandle file, out FileInformation information);
|
||||
|
||||
public override bool HasOtherName(string file)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var f = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
return GetFileInformationByHandle(f.SafeFileHandle, out var information) && information.Links > 1;
|
||||
}
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
||||
static extern uint GetShortPathNameW(string path, System.Text.StringBuilder into, uint size);
|
||||
|
||||
/// <summary>A folder's short name (C:\Users\LONGNA~1), which programs print for temporary files, when it has another one.</summary>
|
||||
public static string? ShortName(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
var into = new System.Text.StringBuilder(1024);
|
||||
var n = GetShortPathNameW(folder, into, (uint)into.Capacity);
|
||||
return n > 0 && n < into.Capacity && !string.Equals(into.ToString(), folder, StringComparison.OrdinalIgnoreCase) ? into.ToString() : null;
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
}
|
||||
151
launcher/Logic/Release.cs
Normal file
151
launcher/Logic/Release.cs
Normal file
@@ -0,0 +1,151 @@
|
||||
// What the newest release offers (old Setup.cs Release): Forgejo's release list at triforceproject.com, newest first,
|
||||
// pre-releases included, with GitHub's field names. TRIFORCE_RELEASE_API replaces the address (testing against a local copy).
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
public sealed record ReleaseAsset(string Name, string? Url, long Size);
|
||||
|
||||
/// <summary>One "New in <version>" item on Home: a title and one line (DESIGN 6 Home, 7).</summary>
|
||||
public sealed record NewInItem(string Title, string Text);
|
||||
|
||||
public sealed class Release
|
||||
{
|
||||
public string Tag { get; set; } = "";
|
||||
public string Name { get; set; } = "";
|
||||
/// <summary>The release notes (Markdown).</summary>
|
||||
public string Body { get; set; } = "";
|
||||
public bool Prerelease { get; set; }
|
||||
public DateTimeOffset? Published { get; set; }
|
||||
/// <summary>The release's own page ("All changes").</summary>
|
||||
public string? PageUrl { get; set; }
|
||||
public IReadOnlyList<ReleaseAsset> Assets { get; set; } = Array.Empty<ReleaseAsset>();
|
||||
|
||||
public string? SetupUrl { get; set; }
|
||||
public long SetupSize { get; set; }
|
||||
public string? ToolsUrl { get; set; }
|
||||
public long ToolsSize { get; set; }
|
||||
/// <summary>((Triforce) the tools in parts, when the release has them: ToolsInstaller.)</summary>
|
||||
public string? ToolsCodeUrl { get; set; }
|
||||
public long ToolsCodeSize { get; set; }
|
||||
public string? ToolsBaseUrl { get; set; }
|
||||
public long ToolsBaseSize { get; set; }
|
||||
/// <summary>Linux: triforce-linux.txt when the release carries one (none does today: LinuxUpdate).</summary>
|
||||
public string? LinuxListUrl { get; set; }
|
||||
/// <summary>Linux: the AppImage (Triforce-<tag>[-linux-test]-x86_64.AppImage).</summary>
|
||||
public string? LinuxAppImageUrl { get; set; }
|
||||
public long LinuxAppImageSize { get; set; }
|
||||
|
||||
/// <summary>The first three "New in" items of the notes (ReleaseNotes.NewIn).</summary>
|
||||
public IReadOnlyList<NewInItem> NewIn => ReleaseNotes.NewIn(Body, 3);
|
||||
|
||||
/// <summary>The release list's answer, read with a real JSON parser: a list of releases (the newest first) or one release.
|
||||
/// Each asset's object holds a nested "uploader" object, so nothing simpler than a parser reads it right (v0.1.0 found no
|
||||
/// assets). Asset names are matched without case.</summary>
|
||||
public static Release Parse(string json)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
var root = doc.RootElement;
|
||||
var r = new Release();
|
||||
JsonElement release;
|
||||
if (root.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
if (root.GetArrayLength() == 0) return r;
|
||||
release = root[0];
|
||||
}
|
||||
else release = root;
|
||||
if (release.ValueKind != JsonValueKind.Object) return r;
|
||||
static string? Str(JsonElement o, string name) => o.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null;
|
||||
static long Num(JsonElement o, string name) => o.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out var n) ? n : 0;
|
||||
r.Tag = Str(release, "tag_name") ?? "";
|
||||
r.Name = Str(release, "name") ?? "";
|
||||
r.Body = Str(release, "body") ?? "";
|
||||
r.PageUrl = Str(release, "html_url");
|
||||
r.Prerelease = release.TryGetProperty("prerelease", out var pre) && pre.ValueKind == JsonValueKind.True;
|
||||
if (Str(release, "published_at") is { } when && DateTimeOffset.TryParse(when, out var t)) r.Published = t;
|
||||
var assets = new List<ReleaseAsset>();
|
||||
if (release.TryGetProperty("assets", out var list) && list.ValueKind == JsonValueKind.Array)
|
||||
foreach (var f in list.EnumerateArray())
|
||||
{
|
||||
if (f.ValueKind != JsonValueKind.Object) continue;
|
||||
var name = Str(f, "name") ?? "";
|
||||
var link = Str(f, "browser_download_url");
|
||||
var size = Num(f, "size");
|
||||
assets.Add(new ReleaseAsset(name, link, size));
|
||||
bool Is(string n) => string.Equals(name, n, StringComparison.OrdinalIgnoreCase);
|
||||
if (Is(BuildInfo.SetupAsset)) { r.SetupUrl = link; r.SetupSize = size; }
|
||||
if (Is(BuildInfo.ToolsAsset)) { r.ToolsUrl = link; r.ToolsSize = size; }
|
||||
if (Is(BuildInfo.ToolsCodeAsset)) { r.ToolsCodeUrl = link; r.ToolsCodeSize = size; }
|
||||
if (Is(BuildInfo.ToolsBaseAsset)) { r.ToolsBaseUrl = link; r.ToolsBaseSize = size; }
|
||||
if (Is(BuildInfo.LinuxListAsset)) r.LinuxListUrl = link;
|
||||
if (name.EndsWith("-x86_64.AppImage", StringComparison.OrdinalIgnoreCase) && name.StartsWith("Triforce", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
r.LinuxAppImageUrl = link;
|
||||
r.LinuxAppImageSize = size;
|
||||
}
|
||||
}
|
||||
r.Assets = assets;
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>The address asked: TRIFORCE_RELEASE_API, else the release list.</summary>
|
||||
public static string ApiUrl(TriforceContext ctx) => ctx.Env("TRIFORCE_RELEASE_API") is { Length: > 0 } o ? o : BuildInfo.ReleaseApi;
|
||||
|
||||
/// <summary>The latest release (20 s for the answer). 404, an empty list or an empty tag: NoReleaseException; another answer
|
||||
/// that is no success throws HttpRequestException.</summary>
|
||||
public static async Task<Release> LatestAsync(TriforceContext ctx, HttpClient http, CancellationToken token)
|
||||
{
|
||||
using var ask = new CancellationTokenSource(TimeSpan.FromSeconds(20));
|
||||
using var both = CancellationTokenSource.CreateLinkedTokenSource(token, ask.Token);
|
||||
using var response = await http.GetAsync(ApiUrl(ctx), both.Token).ConfigureAwait(false);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound) throw new NoReleaseException();
|
||||
response.EnsureSuccessStatusCode();
|
||||
var r = Parse(await response.Content.ReadAsStringAsync(both.Token).ConfigureAwait(false));
|
||||
if (r.Tag.Length == 0) throw new NoReleaseException(); // (an empty list: nothing published)
|
||||
return r;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The release notes' "New in" items.</summary>
|
||||
public static class ReleaseNotes
|
||||
{
|
||||
static readonly Regex BoldItem = new(@"^\s*(?:[-*+]\s+)?\*\*(?<t>.+?)\*\*\s*(?<r>.*)$", RegexOptions.Compiled);
|
||||
static readonly Regex Bullet = new(@"^\s*[-*+]\s+(?<b>.+)$", RegexOptions.Compiled);
|
||||
|
||||
/// <summary>The first items of the notes: lines that are "**Title.** One line" (bulleted or not), the release rule DESIGN 7
|
||||
/// asks for; when the notes have fewer than that many, their first bullet lines instead (a bullet's own bold start is its
|
||||
/// title). Markdown is taken out of the words.</summary>
|
||||
public static IReadOnlyList<NewInItem> NewIn(string? notes, int count = 3)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(notes)) return Array.Empty<NewInItem>();
|
||||
var lines = notes.Replace("\r", "").Split('\n');
|
||||
var bold = new List<NewInItem>();
|
||||
var bullets = new List<NewInItem>();
|
||||
foreach (var line in lines)
|
||||
{
|
||||
if (line.TrimStart().StartsWith('#') || line.TrimStart().StartsWith('>')) continue;
|
||||
if (BoldItem.Match(line) is { Success: true } m && bold.Count < count)
|
||||
bold.Add(new NewInItem(Title(m.Groups["t"].Value), Plain(m.Groups["r"].Value)));
|
||||
if (Bullet.Match(line) is { Success: true } b && bullets.Count < count)
|
||||
{
|
||||
var text = b.Groups["b"].Value;
|
||||
bullets.Add(BoldItem.Match(text) is { Success: true } bm ? new NewInItem(Title(bm.Groups["t"].Value), Plain(bm.Groups["r"].Value)) : new NewInItem(Plain(text), ""));
|
||||
}
|
||||
}
|
||||
if (bold.Count >= count) return bold;
|
||||
return bullets.Count > 0 ? bullets : bold;
|
||||
}
|
||||
|
||||
static string Title(string t) => Plain(t).TrimEnd('.', ':', ' ');
|
||||
|
||||
/// <summary>Markdown out: [text](link) -> text, `code` -> code, ** and __ gone, &amp; and the like read.</summary>
|
||||
public static string Plain(string s)
|
||||
{
|
||||
s = Regex.Replace(s, @"\[([^\]]*)\]\([^)]*\)", "$1");
|
||||
s = s.Replace("**", "").Replace("__", "").Replace("`", "");
|
||||
s = WebUtility.HtmlDecode(s);
|
||||
return Regex.Replace(s, @"\s+", " ").Trim();
|
||||
}
|
||||
}
|
||||
410
launcher/Logic/Saves.cs
Normal file
410
launcher/Logic/Saves.cs
Normal file
@@ -0,0 +1,410 @@
|
||||
// Saves of this game (Ocarina of Time, 0400486024DEC000), wherever they are (old setup/Saves.cs, Shell.Saves.cs): Triforce keeps
|
||||
// them in <game>\user\save\<uid> (Linux: ~/.local/share/hookshot/save/<uid>, host/hos_main.c saves_dir), emulators in their NAND
|
||||
// (Eden, yuzu, suyu, sudachi, citron, torzu, EvilOOT: nand\user\save\0000000000000000\<user>\0400486024DEC000) or Ryujinx's
|
||||
// bis\user\save\<index>\0, NX2navi in its game folder's profile (NaviSave). The files are the same everywhere (account.sav,
|
||||
// option.sav, slot_00..05\caption.sav + progress.sav), so bringing saves in or out is a copy, with what gets replaced backed up first.
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>A place that holds this game's saves (or, Empty, a place to copy them into).</summary>
|
||||
public sealed class SaveSet
|
||||
{
|
||||
public string Name { get; set; } = "";
|
||||
public string Folder { get; set; } = "";
|
||||
public int Slots { get; set; }
|
||||
public DateTime Last { get; set; }
|
||||
public bool Empty { get; set; }
|
||||
public override string ToString() => Name;
|
||||
}
|
||||
|
||||
/// <summary>One of the six files of the game (slot_00..slot_05 = File 1..6). Caption: slot_0N\caption.sav, whose JPEG (from the first
|
||||
/// FF D8 FF to the last FF D9) the App decodes for the picture (DESIGN 7); Written: when it was last saved.</summary>
|
||||
public sealed record SaveSlot(int Index, string Folder, bool Used, string? Caption, DateTime? Written)
|
||||
{
|
||||
/// <summary>"File 4": the game's own numbering.</summary>
|
||||
public int FileNumber => Index + 1;
|
||||
}
|
||||
|
||||
public sealed class SavesException : Exception
|
||||
{
|
||||
public SavesException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
public sealed class Saves
|
||||
{
|
||||
public const string TitleId = "0400486024DEC000";
|
||||
/// <summary>Triforce's save folder name (host/nn_applet.c user_uid, host/nn_fs.c: save\<uid hi><uid lo>).</summary>
|
||||
public const string TriforceUid = "5a3c9e1f0b7d24680000000000000001";
|
||||
public const int SlotCount = 6;
|
||||
static readonly string[] Emulators = { "eden", "EvilOOT", "yuzu", "suyu", "sudachi", "citron", "torzu", "eglantine", "Ryujinx" };
|
||||
|
||||
readonly TriforceContext ctx;
|
||||
public Saves(TriforceContext ctx) { this.ctx = ctx; }
|
||||
|
||||
/// <summary>Triforce's save folder for a game folder.</summary>
|
||||
public string TriforceFolder(string game) => ctx.Platform.SaveFolder(game, TriforceUid);
|
||||
|
||||
/// <summary>Triforce commits its save as a transaction (host/save_tx.h): a finished commit that could not be put in place yet
|
||||
/// (<user>\save-tx\<uid>\ready-<n>, the highest n) waits beside the save folder and is newer. The folder of that
|
||||
/// transaction for a save folder <user>\save\<uid>, or null when it is no such save folder.</summary>
|
||||
static string? TriforceTx(string save)
|
||||
{
|
||||
var parent = Path.GetDirectoryName(save.TrimEnd('\\', '/'));
|
||||
if (parent == null || !string.Equals(Path.GetFileName(parent), "save", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
var user = Path.GetDirectoryName(parent);
|
||||
return user == null ? null : Path.Combine(user, "save-tx", Path.GetFileName(save.TrimEnd('\\', '/')));
|
||||
}
|
||||
|
||||
/// <summary>The save Triforce would load at its next start: a finished commit still waiting, else the save folder.</summary>
|
||||
public string TriforceNewest(string game)
|
||||
{
|
||||
var folder = TriforceFolder(game);
|
||||
try
|
||||
{
|
||||
var tx = TriforceTx(folder);
|
||||
if (tx != null && Directory.Exists(tx))
|
||||
{
|
||||
var ready = Directory.GetDirectories(tx, "ready-*")
|
||||
.Select(d => (Dir: d, M: Regex.Match(Path.GetFileName(d), @"^ready-(\d{1,9})$")))
|
||||
.Where(r => r.M.Success && IsSaveSet(r.Dir))
|
||||
.OrderByDescending(r => int.Parse(r.M.Groups[1].Value)).FirstOrDefault();
|
||||
if (ready.Dir != null) return ready.Dir;
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
return folder;
|
||||
}
|
||||
|
||||
/// <summary>The six files of a game folder's save, as the game would load them (a waiting commit first).</summary>
|
||||
public IReadOnlyList<SaveSlot> Slots(string game) => SlotsIn(TriforceNewest(game));
|
||||
|
||||
/// <summary>The six files of any save folder.</summary>
|
||||
public static IReadOnlyList<SaveSlot> SlotsIn(string saveFolder)
|
||||
{
|
||||
var list = new List<SaveSlot>();
|
||||
for (var i = 0; i < SlotCount; i++)
|
||||
{
|
||||
var dir = Path.Combine(saveFolder, "slot_" + i.ToString("00"));
|
||||
var progress = Path.Combine(dir, "progress.sav");
|
||||
var caption = Path.Combine(dir, "caption.sav");
|
||||
var used = File.Exists(progress);
|
||||
DateTime? written = null;
|
||||
try
|
||||
{
|
||||
var times = new[] { progress, caption }.Where(File.Exists).Select(File.GetLastWriteTime).ToList();
|
||||
if (times.Count > 0) written = times.Max();
|
||||
}
|
||||
catch (Exception) { }
|
||||
list.Add(new SaveSlot(i, dir, used, File.Exists(caption) ? caption : null, written));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>The file saved last: the one whose caption.sav was written last (DESIGN 7 "Newest save"), null when none is used.</summary>
|
||||
public SaveSlot? Newest(string game) =>
|
||||
Slots(game).Where(s => s.Used).OrderByDescending(s => s.Caption != null ? File.GetLastWriteTime(s.Caption) : s.Written ?? DateTime.MinValue).FirstOrDefault();
|
||||
|
||||
/// <summary>A folder holding this game's saves.</summary>
|
||||
public static bool IsSaveSet(string dir) =>
|
||||
Directory.Exists(dir) && (File.Exists(Path.Combine(dir, "option.sav")) || File.Exists(Path.Combine(dir, "slot_00", "progress.sav"))
|
||||
|| File.Exists(Path.Combine(dir, "account.sav")));
|
||||
|
||||
public static SaveSet Describe(string name, string dir)
|
||||
{
|
||||
var s = new SaveSet { Name = name, Folder = dir };
|
||||
if (!Directory.Exists(dir)) { s.Empty = true; return s; }
|
||||
s.Slots = Directory.GetDirectories(dir, "slot_*").Count(d => File.Exists(Path.Combine(d, "progress.sav")));
|
||||
var files = Directory.GetFiles(dir, "*.sav", SearchOption.AllDirectories);
|
||||
s.Empty = files.Length == 0;
|
||||
s.Last = files.Length > 0 ? files.Max(f => File.GetLastWriteTime(f)) : DateTime.MinValue;
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>The save an NX2navi game would load, given its game folder or that folder's profile folder. NX2navi keeps the save in
|
||||
/// <game>\profile\save\<account> (32 hex digits) and commits through <game>\profile\save-tx: a finished commit there
|
||||
/// (ready-<n>, the highest n) is newer than the account folder until the game's next start swaps it in.</summary>
|
||||
public static string? NaviSave(string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var profile in new[] { Path.Combine(dir, "profile"), dir })
|
||||
{
|
||||
var saves = Path.Combine(profile, "save");
|
||||
if (!Directory.Exists(saves)) continue;
|
||||
var tx = Path.Combine(profile, "save-tx");
|
||||
if (Directory.Exists(tx))
|
||||
{
|
||||
// (the game names them with ten digits, ready-0000000001: its runtime/fs_host.c "ready-%010u", an unsigned 32-bit n)
|
||||
var ready = Directory.GetDirectories(tx, "ready-*")
|
||||
.Select(d => (Dir: d, M: Regex.Match(Path.GetFileName(d), @"^ready-(\d{1,10})$")))
|
||||
.Where(r => r.M.Success && IsSaveSet(r.Dir))
|
||||
.OrderByDescending(r => long.Parse(r.M.Groups[1].Value)).FirstOrDefault();
|
||||
if (ready.Dir != null) return ready.Dir;
|
||||
}
|
||||
var account = Directory.GetDirectories(saves)
|
||||
.Where(d => Regex.IsMatch(Path.GetFileName(d), "^[0-9a-fA-F]{32}$") && IsSaveSet(d))
|
||||
.OrderByDescending(d => Describe("", d).Last).FirstOrDefault();
|
||||
if (account != null) return account;
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The game folder NX2navi's launcher built into (<launcher>\data\launcher.json "game_dir").</summary>
|
||||
static string? NaviGameDir(string launcher)
|
||||
{
|
||||
try
|
||||
{
|
||||
var file = Path.Combine(launcher, "data", "launcher.json");
|
||||
if (!File.Exists(file)) return null;
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(file).TrimStart(''));
|
||||
return doc.RootElement.TryGetProperty("game_dir", out var g) && g.ValueKind == JsonValueKind.String && g.GetString() is { Length: > 0 } game ? game : null;
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
/// <summary>Every save of this game found on this PC, newest first: the emulators' usual folders, the folders of programs the
|
||||
/// desktop and Start menu start (portable emulators keep a "user" folder beside them), Ryujinx's numbered saves, and NX2navi's
|
||||
/// games. A test run looks only in its own Roaming and Local folders (no drives, no shortcuts).</summary>
|
||||
public List<SaveSet> FindEmulatorSaves()
|
||||
{
|
||||
var found = new List<SaveSet>();
|
||||
var seen = new HashSet<string>(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
|
||||
void Add(string name, string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!IsSaveSet(dir)) return;
|
||||
var full = Path.GetFullPath(dir).TrimEnd('\\', '/');
|
||||
if (seen.Add(full)) found.Add(Describe(name, full));
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
void Nand(string name, string root) // (root\nand\user\save\0000000000000000\<user>\<title>)
|
||||
{
|
||||
var users = Path.Combine(root, "nand", "user", "save", "0000000000000000");
|
||||
if (!Directory.Exists(users)) return;
|
||||
foreach (var u in SafeDirs(users)) Add(name, Path.Combine(u, TitleId));
|
||||
}
|
||||
void Ryujinx(string name, string root) // (root\bis\user\save\<index>\0; the title is not checked)
|
||||
{
|
||||
var saves = Path.Combine(root, "bis", "user", "save");
|
||||
if (!Directory.Exists(saves)) return;
|
||||
foreach (var s in SafeDirs(saves)) Add(name, Path.Combine(s, "0"));
|
||||
}
|
||||
void Navi(string game) { if (NaviSave(game) is { } save) Add("NX2navi", save); }
|
||||
void NaviLauncher(string launcher)
|
||||
{
|
||||
Navi(Path.Combine(launcher, "game"));
|
||||
if (NaviGameDir(launcher) is { } game) Navi(game);
|
||||
}
|
||||
var (roaming, local) = ctx.Platform.EmulatorDataRoots;
|
||||
if (ctx.IsWindows)
|
||||
{
|
||||
NaviLauncher(Path.Combine(local, "Programs", "NX2navi"));
|
||||
if (ctx.TestRoot == null)
|
||||
foreach (var drive in DriveInfo.GetDrives())
|
||||
try { if (drive.DriveType == DriveType.Fixed && drive.IsReady) Navi(Path.Combine(drive.RootDirectory.FullName, "Games", "NX2navi")); }
|
||||
catch (Exception) { }
|
||||
foreach (var e in Emulators)
|
||||
{
|
||||
var root = Path.Combine(roaming, e);
|
||||
if (e == "Ryujinx") Ryujinx("Ryujinx", root); else Nand(Pretty(e), root);
|
||||
}
|
||||
// (portable copies: the programs the shortcuts start)
|
||||
foreach (var exe in ctx.TestRoot != null ? Enumerable.Empty<string>() : ShortcutTargets())
|
||||
{
|
||||
var dir = Path.GetDirectoryName(exe);
|
||||
if (dir == null) continue;
|
||||
var name = Path.GetFileNameWithoutExtension(exe) + " (" + dir + ")";
|
||||
Nand(name, Path.Combine(dir, "user"));
|
||||
Ryujinx(name, Path.Combine(dir, "portable"));
|
||||
Navi(dir);
|
||||
NaviLauncher(dir);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// (Linux, docs/saves.md: ~/.local/share/<emu>, ~/.config/Ryujinx, the Flatpaks' own folders; NX2navi's AppImage builds
|
||||
// into ~/Games/Ocarina. Guess-level beyond docs/saves.md: check on a Deck)
|
||||
var home = ctx.TestRoot ?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
foreach (var e in Emulators.Where(e => e != "Ryujinx"))
|
||||
{
|
||||
Nand(Pretty(e), Path.Combine(roaming, e));
|
||||
Nand(Pretty(e), Path.Combine(roaming, e.ToLowerInvariant()));
|
||||
}
|
||||
Ryujinx("Ryujinx", Path.Combine(local, "Ryujinx"));
|
||||
if (ctx.TestRoot == null)
|
||||
{
|
||||
var flat = Path.Combine(home, ".var", "app");
|
||||
foreach (var (id, emu) in new[] { ("dev.eden_emu.eden", "eden"), ("org.yuzu_emu.yuzu", "yuzu"), ("org.suyu_emu.suyu", "suyu"), ("org.citron_emu.citron", "citron") })
|
||||
Nand(Pretty(emu) + " (Flatpak)", Path.Combine(flat, id, "data", emu));
|
||||
Ryujinx("Ryujinx (Flatpak)", Path.Combine(flat, "org.ryujinx.Ryujinx", "config", "Ryujinx"));
|
||||
}
|
||||
Navi(Path.Combine(home, "Games", "Ocarina"));
|
||||
}
|
||||
return found.OrderByDescending(s => s.Last).ToList();
|
||||
}
|
||||
|
||||
static string Pretty(string e) => e.ToLowerInvariant() switch
|
||||
{
|
||||
"eden" => "Eden", "yuzu" => "yuzu", "suyu" => "suyu", "sudachi" => "Sudachi", "citron" => "Citron", "torzu" => "torzu", "eglantine" => "Eglantine",
|
||||
"eviloot" => "EvilOOT", _ => e,
|
||||
};
|
||||
|
||||
static IEnumerable<string> SafeDirs(string d)
|
||||
{
|
||||
try { return Directory.GetDirectories(d); } catch (Exception) { return Array.Empty<string>(); }
|
||||
}
|
||||
|
||||
/// <summary>The .exe files the desktop and Start menu shortcuts start (WScript.Shell reads the .lnk), at most 400 per folder.</summary>
|
||||
static IEnumerable<string> ShortcutTargets()
|
||||
{
|
||||
var exes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
if (!OperatingSystem.IsWindows()) return exes;
|
||||
var places = new[]
|
||||
{
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory),
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.Programs), Environment.GetFolderPath(Environment.SpecialFolder.CommonPrograms),
|
||||
};
|
||||
var type = Type.GetTypeFromProgID("WScript.Shell");
|
||||
if (type == null) return exes;
|
||||
object? shell = null;
|
||||
try
|
||||
{
|
||||
shell = Activator.CreateInstance(type);
|
||||
foreach (var p in places.Where(p => p.Length > 0 && Directory.Exists(p)))
|
||||
{
|
||||
IEnumerable<string> links;
|
||||
try { links = Directory.GetFiles(p, "*.lnk", p.EndsWith("Programs", StringComparison.OrdinalIgnoreCase) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); }
|
||||
catch (Exception) { continue; }
|
||||
foreach (var l in links.Take(400))
|
||||
{
|
||||
try
|
||||
{
|
||||
var lnk = type.InvokeMember("CreateShortcut", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { l })!;
|
||||
var target = lnk.GetType().InvokeMember("TargetPath", System.Reflection.BindingFlags.GetProperty, null, lnk, null) as string;
|
||||
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(lnk);
|
||||
if (target != null && target.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && File.Exists(target)) exes.Add(target);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
finally { if (shell != null) System.Runtime.InteropServices.Marshal.FinalReleaseComObject(shell); }
|
||||
return exes;
|
||||
}
|
||||
|
||||
/// <summary>A chosen folder: the save set it is, an NX2navi save inside it, or the first one inside it (breadth first, 7 levels,
|
||||
/// at most 4000 folders).</summary>
|
||||
public static string? FindIn(string dir)
|
||||
{
|
||||
if (IsSaveSet(dir)) return dir;
|
||||
if (NaviSave(dir) is { } navi) return navi;
|
||||
var queue = new Queue<(string, int)>();
|
||||
queue.Enqueue((dir, 0));
|
||||
var looked = 0;
|
||||
while (queue.Count > 0 && looked++ < 4000)
|
||||
{
|
||||
var (d, depth) = queue.Dequeue();
|
||||
foreach (var s in SafeDirs(d))
|
||||
{
|
||||
if (IsSaveSet(s)) return s;
|
||||
if (depth < 7) queue.Enqueue((s, depth + 1));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>A game or emulator that has these saves open (it would write over the copy when it closes): its name, or null.
|
||||
/// In a test run only a program started from inside the test folder counts.</summary>
|
||||
public string? RunningGame()
|
||||
{
|
||||
// ("ocarina" is the program NX2navi builds)
|
||||
var names = new[] { "Triforce", "hookshot", "EvilOOT", "eden", "yuzu", "suyu", "sudachi", "citron", "torzu", "Ryujinx", "ocarina" };
|
||||
foreach (var p in ctx.Platform.FindProcesses(names))
|
||||
if (ctx.TestRoot == null || p.Exe != null && TriforceContext.Inside(ctx.TestRoot, p.Exe))
|
||||
return p.Name == "ocarina" ? "NX2navi" : p.Name;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Copies one save set over another: the destination's old files are copied to the backup folder first (nothing is
|
||||
/// merged slot by slot: the copy is exactly the source). Returns the backup folder, or null when there was nothing to back up.
|
||||
/// The games' save locks are held across all of it (SaveLock), and the copy is made as <save>.partial and swapped in once
|
||||
/// complete (Partial): a copy that fails or is cut off leaves the destination as it was. TRIFORCE_SAVE_LOCK=0: no lock.</summary>
|
||||
public string? Copy(string from, string to, string backupRoot, string label)
|
||||
{
|
||||
var src = Path.GetFullPath(from).TrimEnd('\\', '/');
|
||||
var dst = Path.GetFullPath(to).TrimEnd('\\', '/');
|
||||
ctx.Require(dst);
|
||||
if (TriforceContext.SamePath(src, dst)) throw new InvalidOperationException("That is the same save folder.");
|
||||
var locking = ctx.Env("TRIFORCE_SAVE_LOCK") != "0";
|
||||
using var dstLock = locking ? SaveLock.Take(dst) : null;
|
||||
using var srcLock = locking && !string.Equals(SaveLock.PathOf(src), SaveLock.PathOf(dst), StringComparison.OrdinalIgnoreCase) ? SaveLock.Take(src) : null;
|
||||
var partial = new Partial(ctx.Platform);
|
||||
Partial.Recover(dst);
|
||||
var staged = partial.Stage(src, dst);
|
||||
string? backup = null;
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(dst) && Directory.EnumerateFileSystemEntries(dst).Any())
|
||||
{
|
||||
var safe = string.Concat(label.Select(c => Path.GetInvalidFileNameChars().Contains(c) || c == ' ' ? '-' : c));
|
||||
backup = Path.Combine(backupRoot, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_" + safe);
|
||||
Directory.CreateDirectory(backup);
|
||||
CopyTree(dst, backup);
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Partial.Remove(staged);
|
||||
throw;
|
||||
}
|
||||
partial.SwapIn(staged, dst);
|
||||
// (into Triforce: its working copy and any finished commit still waiting belong to the save that was replaced, and the game
|
||||
// would put such a commit over the copy at its next start)
|
||||
if (TriforceTx(dst) is { } tx && Directory.Exists(tx))
|
||||
try { Directory.Delete(tx, true); } catch (Exception) { }
|
||||
return backup;
|
||||
}
|
||||
|
||||
static void CopyTree(string from, string to)
|
||||
{
|
||||
Directory.CreateDirectory(to);
|
||||
foreach (var f in Directory.GetFiles(from)) File.Copy(f, Path.Combine(to, Path.GetFileName(f)), true);
|
||||
foreach (var d in Directory.GetDirectories(from)) CopyTree(d, Path.Combine(to, Path.GetFileName(d)));
|
||||
}
|
||||
|
||||
void Refuse()
|
||||
{
|
||||
if (RunningGame() is { } running)
|
||||
throw new SavesException("Close " + running + " first: it would write its own saves back over the copy when it closes.");
|
||||
}
|
||||
|
||||
/// <summary>Bring saves in: a found (or chosen) save set becomes Triforce's; Triforce's own are backed up first, into
|
||||
/// <install>\save-backups\<date>_Triforce-before-<name>. Refused while a game or emulator runs. Returns the backup folder.</summary>
|
||||
public Task<string?> ImportAsync(SaveSet from, string game) => Task.Run(() =>
|
||||
{
|
||||
Refuse();
|
||||
if (from.Empty || !IsSaveSet(from.Folder)) throw new SavesException("That folder has no saves to bring in.");
|
||||
var backup = Copy(from.Folder, TriforceFolder(game), ctx.SaveBackupsFolder, "Triforce before " + from.Name);
|
||||
ctx.Log.Write("saves: " + from.Folder + " -> Triforce" + (backup != null ? " (backup " + backup + ")" : ""));
|
||||
return backup;
|
||||
});
|
||||
|
||||
/// <summary>Copy saves out: Triforce's newest save becomes the target's; the target's are backed up first. Returns the backup folder.</summary>
|
||||
public Task<string?> ExportAsync(string game, SaveSet to) => Task.Run(() =>
|
||||
{
|
||||
Refuse();
|
||||
var source = TriforceNewest(game);
|
||||
if (!IsSaveSet(source)) throw new SavesException("Triforce has no saves yet to take out.");
|
||||
var backup = Copy(source, to.Folder, ctx.SaveBackupsFolder, to.Name + " before Triforce");
|
||||
ctx.Log.Write("saves: Triforce -> " + to.Folder + (backup != null ? " (backup " + backup + ")" : ""));
|
||||
return backup;
|
||||
});
|
||||
}
|
||||
234
launcher/Logic/Startup.cs
Normal file
234
launcher/Logic/Startup.cs
Normal file
@@ -0,0 +1,234 @@
|
||||
// The start of a launcher run: its arguments, the one-launcher-per-install lock, the clean-up after a self-update, and which
|
||||
// screen the App opens. This is the contract old installs update onto (research/02 2.4 and 2.8; research/12 1.3):
|
||||
// Windows TriforceSetup.exe (shortcut: the update check, then Home or the build)
|
||||
// TriforceSetup.exe --relaunched --merge (an old Setup replaced itself with this exe)
|
||||
// TriforceSetup.exe --update "<dir>" --relaunched (the same, when the game had started the update)
|
||||
// TriforceSetup.exe --update "<dir>" --tag "<tag>" (the game's own update offer, host/hos_update.c)
|
||||
// TriforceSetup.exe --merge (an install relaunching the installed copy)
|
||||
// TriforceSetup.exe --uninstall [--quiet] (the Apps list)
|
||||
// TriforceSetup.exe --install-to <dir> [--no-desktop] [--no-startmenu]
|
||||
// Linux AppRun --launch <dir> (the game folder's "triforce" script)
|
||||
// AppRun --update <dir> [--tag T] [--fetched] (the game, host/hos_update.c execl)
|
||||
// AppRun (the menu entry)
|
||||
// (AppRun keeps --cli, --play and "<dir>" for itself: they never start a window)
|
||||
// Unknown arguments are ignored, never fatal.
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>The arguments of a start, as the old Setup, the game and AppRun pass them.</summary>
|
||||
public sealed record StartArgs
|
||||
{
|
||||
public bool Relaunched { get; init; }
|
||||
/// <summary>Update & merge straight away: Setup itself, then the tools, then the game folder built again.</summary>
|
||||
public bool Merge { get; init; }
|
||||
/// <summary>--update <dir>: the game folder to build again (the game's offer; it also sets Merge).</summary>
|
||||
public string? UpdateFolder { get; init; }
|
||||
/// <summary>--tag <tag>: the release the game saw (the old Setup ignored it).</summary>
|
||||
public string? Tag { get; init; }
|
||||
public bool Uninstall { get; init; }
|
||||
public bool Quiet { get; init; }
|
||||
public string? InstallTo { get; init; }
|
||||
public bool NoDesktop { get; init; }
|
||||
public bool NoStartMenu { get; init; }
|
||||
/// <summary>Linux --launch <dir>: the game folder's launcher page (Play, and Update when a newer release is out).</summary>
|
||||
public string? LaunchFolder { get; init; }
|
||||
/// <summary>Linux --fetched: the builder re-executed itself after its own update.</summary>
|
||||
public bool Fetched { get; init; }
|
||||
/// <summary>Linux --play [dir] when it reaches the launcher at all (AppRun normally handles it): start the game, no window.</summary>
|
||||
public bool Play { get; init; }
|
||||
public string? PlayFolder { get; init; }
|
||||
public IReadOnlyList<string> Unknown { get; init; } = Array.Empty<string>();
|
||||
|
||||
/// <summary>Reads the arguments. A value with a quote in it is repaired: a folder that ends in a backslash, passed as
|
||||
/// --update "C:\Games\Triforce\" by a command line, reaches a program as `C:\Games\Triforce" --tag v0.5.2` (the \" is an
|
||||
/// escaped quote under the MSVC rules); the part after the quote is read as the arguments it was meant to be.</summary>
|
||||
public static StartArgs Parse(IReadOnlyList<string> raw)
|
||||
{
|
||||
var args = Repair(raw);
|
||||
var a = new StartArgs();
|
||||
var unknown = new List<string>();
|
||||
string? Next(ref int i) => i + 1 < args.Count && !args[i + 1].StartsWith("--", StringComparison.Ordinal) ? args[++i] : null;
|
||||
for (var i = 0; i < args.Count; i++)
|
||||
{
|
||||
switch (args[i])
|
||||
{
|
||||
case "--update":
|
||||
if (Next(ref i) is { } u) a = a with { UpdateFolder = u, Merge = true };
|
||||
break;
|
||||
case "--tag": a = a with { Tag = Next(ref i) }; break;
|
||||
case "--merge": a = a with { Merge = true }; break;
|
||||
case "--relaunched": a = a with { Relaunched = true }; break;
|
||||
case "--uninstall": a = a with { Uninstall = true }; break;
|
||||
case "--quiet": a = a with { Quiet = true }; break;
|
||||
case "--install-to": a = a with { InstallTo = Next(ref i) }; break;
|
||||
case "--no-desktop": a = a with { NoDesktop = true }; break;
|
||||
case "--no-startmenu": a = a with { NoStartMenu = true }; break;
|
||||
case "--launch": a = a with { LaunchFolder = Next(ref i) }; break;
|
||||
case "--fetched": a = a with { Fetched = true }; break;
|
||||
case "--play": a = a with { Play = true, PlayFolder = Next(ref i) }; break;
|
||||
default: unknown.Add(args[i]); break;
|
||||
}
|
||||
}
|
||||
return a with { Unknown = unknown };
|
||||
}
|
||||
|
||||
static List<string> Repair(IReadOnlyList<string> raw)
|
||||
{
|
||||
var o = new List<string>();
|
||||
foreach (var arg in raw)
|
||||
{
|
||||
var q = arg.IndexOf('"');
|
||||
if (q < 0) { o.Add(arg); continue; }
|
||||
// (what was meant: the value up to the quote, a backslash given back; the rest split as a command line would be)
|
||||
var value = arg.Substring(0, q);
|
||||
if (value.Length > 0 && !value.EndsWith('\\') && !value.EndsWith('/') && value.Length >= 2 && value[1] == ':') value += "\\";
|
||||
if (value.Length > 0) o.Add(value);
|
||||
foreach (var w in arg.Substring(q + 1).Split(' ', StringSplitOptions.RemoveEmptyEntries)) o.Add(w.Trim('"'));
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
/// <summary>What a launcher passes on when it hands over to another copy (old Shell.cs Relaunch): --update "<dir>" when it had
|
||||
/// it, --relaunched after a self-update, --merge when merging without a folder named.</summary>
|
||||
public IReadOnlyList<string> PassOn(bool afterSelfUpdate)
|
||||
{
|
||||
var a = new List<string>();
|
||||
if (UpdateFolder != null) { a.Add("--update"); a.Add(UpdateFolder); }
|
||||
if (Tag != null && UpdateFolder != null) { a.Add("--tag"); a.Add(Tag); }
|
||||
if (afterSelfUpdate) a.Add("--relaunched");
|
||||
if (Merge && UpdateFolder == null) a.Add("--merge");
|
||||
return a;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the App opens.</summary>
|
||||
public enum StartScreen
|
||||
{
|
||||
/// <summary>Nothing: the process ends with ExitCode (another launcher is open, a silent install, the hand-over to the installed copy).</summary>
|
||||
Exit,
|
||||
/// <summary>The first run's Install page (Windows, not installed yet).</summary>
|
||||
Install,
|
||||
/// <summary>Ask the release server (Updater.CheckAsync), then Updater.Decide says Home, Merge or Failed.</summary>
|
||||
Check,
|
||||
/// <summary>Linux --launch <dir>: Home for that game folder (the check runs too, quietly).</summary>
|
||||
Launch,
|
||||
/// <summary>--uninstall: ask (unless Quiet), then Uninstaller.Run, then exit 0 (1 when the player says no).</summary>
|
||||
Uninstall,
|
||||
}
|
||||
|
||||
public sealed class StartupResult
|
||||
{
|
||||
public required StartArgs Args { get; init; }
|
||||
public StartScreen Screen { get; init; }
|
||||
/// <summary>Set when Screen is Exit: the process's exit code.</summary>
|
||||
public int ExitCode { get; init; }
|
||||
/// <summary>A sentence for the player (only for a message box the App shows before it exits; never with --quiet).</summary>
|
||||
public string? Message { get; init; }
|
||||
/// <summary>The install's lock, held for as long as the launcher runs: Release it when the window has closed.</summary>
|
||||
public InstanceLock? Lock { get; init; }
|
||||
/// <summary>The game folder this start is about (--update or --launch).</summary>
|
||||
public string? GameFolder { get; init; }
|
||||
/// <summary>Call Startup.SignalUp once the window is up (started by an old Setup that waits for that sign).</summary>
|
||||
public bool SignalUpWhenShown { get; init; }
|
||||
}
|
||||
|
||||
public static class Startup
|
||||
{
|
||||
/// <summary>The start: what runs before any window. Ordered as the old Program.Main and Shell.Begin.</summary>
|
||||
public static StartupResult Run(TriforceContext ctx, IReadOnlyList<string> args)
|
||||
{
|
||||
var a = StartArgs.Parse(args);
|
||||
var home = ctx.IsWindows ? ctx.InstalledDir ?? ctx.SelfDir : ctx.Home;
|
||||
if (a.Unknown.Count > 0) ctx.Log.Write("start: arguments not known, ignored: " + string.Join(" ", a.Unknown));
|
||||
|
||||
// (the Setup this one replaced still runs for a moment, until it has heard that this window is up: again once it is gone)
|
||||
RemoveOld(ctx);
|
||||
if (a.Relaunched) _ = Task.Delay(5000).ContinueWith(_ => RemoveOld(ctx));
|
||||
|
||||
if (a.Uninstall)
|
||||
{
|
||||
// (not under a launcher that is open: its tools and its build's work folder would go while it uses them)
|
||||
var l = InstanceLock.TryTake(home, ctx.TestRoot);
|
||||
if (l == null)
|
||||
{
|
||||
ctx.Log.Write("not uninstalled: Triforce is open for " + home);
|
||||
InstanceLock.CallForward(home, ctx.TestRoot);
|
||||
return new StartupResult { Args = a, Screen = StartScreen.Exit, ExitCode = 1, Message = a.Quiet ? null : "Triforce is open. Close it, then uninstall again." };
|
||||
}
|
||||
return new StartupResult { Args = a, Screen = StartScreen.Uninstall, Lock = l };
|
||||
}
|
||||
|
||||
// (silent install: --install-to <folder> [--no-desktop] [--no-startmenu]; the installed launcher then starts as usual)
|
||||
if (a.InstallTo != null)
|
||||
{
|
||||
var exe = new Installer(ctx).Run(Path.GetFullPath(a.InstallTo), !a.NoDesktop, !a.NoStartMenu);
|
||||
ctx.Log.Write("installed " + BuildInfo.Version + " to " + Path.GetDirectoryName(exe) + " (silent)");
|
||||
if (ctx.Allowed(exe)) Installer.Start(exe, Array.Empty<string>())?.Dispose();
|
||||
return new StartupResult { Args = a, Screen = StartScreen.Exit, ExitCode = 0 };
|
||||
}
|
||||
|
||||
// (a second start for the same install must not fetch, build, update or convert saves beside the first: it asks the first
|
||||
// one's window to the front and ends; nobody to ask yet: the first is only just starting or closing, tried 30 times)
|
||||
InstanceLock? held = null;
|
||||
for (var tries = 0; (held = InstanceLock.TryTake(home, ctx.TestRoot)) == null; tries++)
|
||||
{
|
||||
if (InstanceLock.CallForward(home, ctx.TestRoot))
|
||||
{
|
||||
ctx.Log.Write("Triforce is already open for " + home + ": its window was asked to the front, and this start ends");
|
||||
return new StartupResult { Args = a, Screen = StartScreen.Exit, ExitCode = 0 };
|
||||
}
|
||||
if (tries >= 30)
|
||||
{
|
||||
ctx.Log.Write("Triforce is already running for " + home + " and does not answer: this start ends");
|
||||
return new StartupResult
|
||||
{
|
||||
Args = a, Screen = StartScreen.Exit, ExitCode = 1,
|
||||
Message = "Triforce is already running, but its window could not be brought to the front.\n\nClose it (in Task Manager: TriforceSetup.exe) and start Triforce again.",
|
||||
};
|
||||
}
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
|
||||
var result = new StartupResult { Args = a, Screen = StartScreen.Check, Lock = held, GameFolder = a.UpdateFolder ?? a.LaunchFolder, SignalUpWhenShown = a.Relaunched };
|
||||
if (!ctx.IsWindows)
|
||||
return a.LaunchFolder != null && a.UpdateFolder == null ? Same(result, StartScreen.Launch) : result;
|
||||
|
||||
// (TRIFORCE_DEV=1: run in place, without installing, for testing)
|
||||
if (ctx.RunningInstalled || ctx.Env("TRIFORCE_DEV") == "1") return result;
|
||||
if (ctx.InstalledDir is { } dir)
|
||||
{
|
||||
// (installed already: this download becomes the installed launcher, which then carries on with what it was asked)
|
||||
try
|
||||
{
|
||||
var exe = new Installer(ctx).Run(dir, ctx.Settings.Desktop, ctx.Settings.StartMenu);
|
||||
held.Release(); // (the launcher started here takes this install over: it must find the folder free)
|
||||
if (!ctx.Allowed(exe)) throw new InvalidOperationException(ctx.TestOnly);
|
||||
Installer.Start(exe, a.PassOn(afterSelfUpdate: false))?.Dispose();
|
||||
return new StartupResult { Args = a, Screen = StartScreen.Exit, ExitCode = 0 };
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ctx.Log.Write("the installed copy could not be replaced (" + e.Message + "): this one carries on");
|
||||
held.TakeAgain();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
return Same(result, StartScreen.Install);
|
||||
}
|
||||
|
||||
static StartupResult Same(StartupResult r, StartScreen screen) => new()
|
||||
{
|
||||
Args = r.Args, Screen = screen, Lock = r.Lock, GameFolder = r.GameFolder, SignalUpWhenShown = r.SignalUpWhenShown,
|
||||
};
|
||||
|
||||
/// <summary>TriforceSetup.old.exe beside the install: the launcher a self-update replaced (it may still run for a few seconds).</summary>
|
||||
public static void RemoveOld(TriforceContext ctx)
|
||||
{
|
||||
var before = Path.Combine(ctx.IsWindows ? ctx.InstalledDir ?? ctx.SelfDir : ctx.Home, "TriforceSetup.old.exe");
|
||||
try { if (File.Exists(before) && ctx.Allowed(before)) File.Delete(before); } catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>The sign an old Setup waits for after it replaced itself with this one: call once the window is up. Without it
|
||||
/// the old one waits 30 s hidden, then quits.</summary>
|
||||
public static void SignalUp(TriforceContext ctx) =>
|
||||
Handover.Up(ctx.IsWindows ? ctx.InstalledDir ?? ctx.SelfDir : ctx.Home, ctx.TestRoot);
|
||||
}
|
||||
528
launcher/Logic/Steam.cs
Normal file
528
launcher/Logic/Steam.cs
Normal file
@@ -0,0 +1,528 @@
|
||||
// (Triforce) Add to Steam: the game as a "non-Steam game" in the player's Steam library (old setup/Steam.cs, Shell.Steam.cs).
|
||||
// Steam's folder is always handed in; a test run has only <root>\Steam (Platform.SteamRoots), never the PC's real Steam.
|
||||
//
|
||||
// Steam keeps an account's shortcuts in <Steam>\userdata\<account>\config\shortcuts.vdf, a binary file of named values:
|
||||
// 00 name 00 ... 08 a map (its values, then 08)
|
||||
// 01 name 00 text 00 a text
|
||||
// 02 name 00 4 bytes a number (03, 04 and 06 are four bytes too; 07 and 0A are eight)
|
||||
// The whole file is one map, "shortcuts", of one map for each shortcut, named "0", "1", ...; then one more 08 ends the file.
|
||||
// This file is another program's: it is read whole, every shortcut and every value in it that is not ours goes back byte for
|
||||
// byte, a file that does not read to its very end as such a file is refused and left alone, the new file is written beside the
|
||||
// old one and takes its name in one step, and the file as it was is kept (shortcuts.vdf.triforce-backup: before the last change;
|
||||
// shortcuts.vdf.before-triforce: before the first).
|
||||
//
|
||||
// Steam reads the file when it starts and writes its own list back when it closes: a shortcut written while Steam runs would not
|
||||
// show and would be gone at Steam's next exit. So nothing is written while Steam runs: "Close Steam first".
|
||||
//
|
||||
// The pictures (config\grid\<appid><suffix>): the old Setup drew them from its crest with WPF (SteamArt.cs). That drawing is
|
||||
// the App's now: it hands Add the PNG bytes for each kind of Pictures. Linux (the Steam Deck): the same file and the same appid
|
||||
// algorithm (research/02 section 11); the shortcut starts the folder's "triforce" launcher script.
|
||||
using System.Text;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
public sealed class SteamException : Exception
|
||||
{
|
||||
public SteamException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
/// <summary>An account that signed in to Steam on this PC.</summary>
|
||||
public sealed class SteamUser
|
||||
{
|
||||
public string Root { get; set; } = "";
|
||||
public string Id { get; set; } = "";
|
||||
public string Name { get; set; } = "";
|
||||
public bool Recent { get; set; }
|
||||
public long Seen;
|
||||
public string Config => Path.Combine(Root, "userdata", Id, "config");
|
||||
public string Shortcuts => Path.Combine(Config, "shortcuts.vdf");
|
||||
public string Grid => Path.Combine(Config, "grid");
|
||||
}
|
||||
|
||||
/// <summary>The binary shortcuts file, byte-exact (old Steam.cs, unchanged in its rules).</summary>
|
||||
public static class SteamVdf
|
||||
{
|
||||
/// <summary>The shortcut's name in the library.</summary>
|
||||
public const string Name = "Triforce";
|
||||
/// <summary>The game's program, by any of its names (Windows Triforce.exe / hookshot.exe; Linux the folder's triforce script).</summary>
|
||||
public static readonly string[] GameExes = { "Triforce.exe", "hookshot.exe", "triforce", "hookshot" };
|
||||
|
||||
/// <summary>The pictures of a shortcut: what each is, the end of its file's name after the shortcut's number in config\grid, and
|
||||
/// the size Steam's library shows it at.</summary>
|
||||
public static readonly (string Kind, string File, int Width, int Height)[] Pictures =
|
||||
{
|
||||
("portrait", "p.png", 600, 900), ("wide", ".png", 920, 430), ("hero", "_hero.png", 1920, 620), ("logo", "_logo.png", 640, 360), ("icon", "_icon.png", 256, 256),
|
||||
};
|
||||
|
||||
sealed class Node
|
||||
{
|
||||
public byte Type;
|
||||
public string Name = "";
|
||||
public int Start, Value, End;
|
||||
public List<Node>? Values;
|
||||
}
|
||||
|
||||
static SteamException Bad(string why) => new("Steam's shortcuts file is not as Steam writes it (" + why + "), so the launcher left it alone. Nothing was changed.");
|
||||
|
||||
static List<Node> Read(byte[] b)
|
||||
{
|
||||
var at = 0;
|
||||
var top = Map(b, ref at, 0);
|
||||
if (at != b.Length) throw Bad("it goes on after its end");
|
||||
return top;
|
||||
}
|
||||
|
||||
static List<Node> Map(byte[] b, ref int at, int depth)
|
||||
{
|
||||
if (depth > 16) throw Bad("its maps are nested too deep");
|
||||
var values = new List<Node>();
|
||||
for (;;)
|
||||
{
|
||||
if (at >= b.Length) throw Bad("it is cut off");
|
||||
var n = new Node { Start = at, Type = b[at++] };
|
||||
if (n.Type == 8) return values;
|
||||
var end = Array.IndexOf(b, (byte)0, at);
|
||||
if (end < 0) throw Bad("it is cut off");
|
||||
n.Name = Encoding.UTF8.GetString(b, at, end - at);
|
||||
n.Value = at = end + 1;
|
||||
switch (n.Type)
|
||||
{
|
||||
case 0: n.Values = Map(b, ref at, depth + 1); break;
|
||||
case 1:
|
||||
end = Array.IndexOf(b, (byte)0, at);
|
||||
if (end < 0) throw Bad("it is cut off");
|
||||
at = end + 1;
|
||||
break;
|
||||
case 2: case 3: case 4: case 6: at += 4; break;
|
||||
case 7: case 10: at += 8; break;
|
||||
default: throw Bad("it holds a value of a kind the launcher does not know, " + n.Type);
|
||||
}
|
||||
if (at > b.Length) throw Bad("it is cut off");
|
||||
n.End = at;
|
||||
values.Add(n);
|
||||
}
|
||||
}
|
||||
|
||||
static Node? Named(IEnumerable<Node> values, string name, int type) =>
|
||||
values.FirstOrDefault(v => v.Type == type && string.Equals(v.Name, name, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
static string Text(byte[] b, Node n) => Encoding.UTF8.GetString(b, n.Value, n.End - 1 - n.Value);
|
||||
|
||||
static byte[] Cut(byte[] b, int from, int to) => b.AsSpan(from, to - from).ToArray();
|
||||
|
||||
static void PutText(List<byte> o, string name, string text)
|
||||
{
|
||||
if (text.IndexOf('\0') >= 0) throw new SteamException("A path with a zero in it cannot be written into Steam's shortcuts file.");
|
||||
o.Add(1);
|
||||
o.AddRange(Encoding.UTF8.GetBytes(name));
|
||||
o.Add(0);
|
||||
o.AddRange(Encoding.UTF8.GetBytes(text));
|
||||
o.Add(0);
|
||||
}
|
||||
|
||||
static void PutNumber(List<byte> o, string name, uint number)
|
||||
{
|
||||
o.Add(2);
|
||||
o.AddRange(Encoding.UTF8.GetBytes(name));
|
||||
o.Add(0);
|
||||
o.AddRange(BitConverter.GetBytes(number));
|
||||
}
|
||||
|
||||
/// <summary>The number Steam knows a shortcut by, and names its pictures by: the CRC-32 of its Exe and AppName as they stand in
|
||||
/// the file (Exe quoted), with the top bit set.</summary>
|
||||
public static uint Id(string exe, string name)
|
||||
{
|
||||
var crc = 0xFFFFFFFFu;
|
||||
foreach (var x in Encoding.UTF8.GetBytes(exe + name))
|
||||
{
|
||||
crc ^= x;
|
||||
for (var k = 0; k < 8; k++) crc = (crc & 1) != 0 ? (crc >> 1) ^ 0xEDB88320u : crc >> 1;
|
||||
}
|
||||
return ~crc | 0x80000000u;
|
||||
}
|
||||
|
||||
static Node Shortcuts(List<Node> top) => Named(top, "shortcuts", 0) ?? throw Bad("it has no list of shortcuts");
|
||||
|
||||
/// <summary>Is this shortcut ours? By its number (this game folder's), or by the name Triforce on a program called as the game is
|
||||
/// (a game folder that was moved): another program the player named Triforce is not.</summary>
|
||||
static bool Ours(byte[] b, Node shortcut, uint id)
|
||||
{
|
||||
if (shortcut.Values == null) return false;
|
||||
if (Named(shortcut.Values, "appid", 2) is { } number && BitConverter.ToUInt32(b, number.Value) == id) return true;
|
||||
if (Named(shortcut.Values, "AppName", 1) is not { } name || Text(b, name) != Name) return false;
|
||||
if (Named(shortcut.Values, "Exe", 1) is not { } exe) return false;
|
||||
var file = Text(b, exe).Trim().Trim('"').Replace('/', '\\');
|
||||
file = file.Substring(file.LastIndexOf('\\') + 1);
|
||||
return GameExes.Any(g => string.Equals(g, file, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
static bool Counted(Node shortcuts) => shortcuts.Values!.Select((v, i) => v.Type == 0 && v.Name == i.ToString()).All(ok => ok);
|
||||
|
||||
static byte[] Empty()
|
||||
{
|
||||
var o = new List<byte> { 0 };
|
||||
o.AddRange(Encoding.UTF8.GetBytes("shortcuts"));
|
||||
o.AddRange(new byte[] { 0, 8, 8 });
|
||||
return o.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>The file (no bytes: none yet) with our shortcut in it: added after the others, or, where one of ours is there, with
|
||||
/// its number, name, program, folder and icon set and everything else in it as it was (launch options, tags, hidden).</summary>
|
||||
public static byte[] With(byte[] file, string exe, string startDir, string icon, out uint id, out bool wasThere)
|
||||
{
|
||||
id = Id(exe, Name);
|
||||
if (file.Length == 0) file = Empty();
|
||||
var shortcuts = Shortcuts(Read(file));
|
||||
var number = id;
|
||||
var ours = shortcuts.Values!.FirstOrDefault(s => Ours(file, s, number));
|
||||
wasThere = ours != null;
|
||||
var o = new List<byte>();
|
||||
if (ours != null)
|
||||
{
|
||||
string[] set = { "appid", "AppName", "Exe", "StartDir", "icon" };
|
||||
void Put(string which, string spelled)
|
||||
{
|
||||
if (which == "appid") PutNumber(o, spelled, number);
|
||||
else PutText(o, spelled, which == "AppName" ? Name : which == "Exe" ? exe : which == "StartDir" ? startDir : icon);
|
||||
}
|
||||
o.AddRange(Cut(file, 0, ours.Value));
|
||||
var put = new HashSet<string>();
|
||||
foreach (var v in ours.Values!)
|
||||
{
|
||||
var which = set.FirstOrDefault(s => string.Equals(s, v.Name, StringComparison.OrdinalIgnoreCase));
|
||||
if (which == null) { o.AddRange(Cut(file, v.Start, v.End)); continue; }
|
||||
if (put.Add(which)) Put(which, v.Name); // (under the name as the file spells it; a second value of one name dropped)
|
||||
}
|
||||
foreach (var s in set.Where(s => !put.Contains(s))) Put(s, s);
|
||||
o.Add(8);
|
||||
o.AddRange(Cut(file, ours.End, file.Length));
|
||||
}
|
||||
else
|
||||
{
|
||||
var key = shortcuts.Values!.Count;
|
||||
if (!Counted(shortcuts))
|
||||
for (key = 0; shortcuts.Values.Any(v => v.Name == key.ToString()); key++) { }
|
||||
o.AddRange(Cut(file, 0, shortcuts.End - 1));
|
||||
o.Add(0);
|
||||
o.AddRange(Encoding.UTF8.GetBytes(key.ToString()));
|
||||
o.Add(0);
|
||||
PutNumber(o, "appid", number);
|
||||
PutText(o, "AppName", Name);
|
||||
PutText(o, "Exe", exe);
|
||||
PutText(o, "StartDir", startDir);
|
||||
PutText(o, "icon", icon);
|
||||
PutText(o, "ShortcutPath", "");
|
||||
PutText(o, "LaunchOptions", "");
|
||||
PutNumber(o, "IsHidden", 0);
|
||||
PutNumber(o, "AllowDesktopConfig", 1);
|
||||
PutNumber(o, "AllowOverlay", 1);
|
||||
PutNumber(o, "OpenVR", 0);
|
||||
PutNumber(o, "Devkit", 0);
|
||||
PutText(o, "DevkitGameID", "");
|
||||
PutNumber(o, "DevkitOverrideAppID", 0);
|
||||
PutNumber(o, "LastPlayTime", 0);
|
||||
PutText(o, "FlatpakAppID", "");
|
||||
o.Add(0);
|
||||
o.AddRange(Encoding.UTF8.GetBytes("tags"));
|
||||
o.AddRange(new byte[] { 0, 8 });
|
||||
o.Add(8);
|
||||
o.AddRange(Cut(file, shortcuts.End - 1, file.Length));
|
||||
}
|
||||
return Proved(file, o.ToArray(), number, Math.Max(1, shortcuts.Values!.Count(s => Ours(file, s, number))));
|
||||
}
|
||||
|
||||
/// <summary>The file without our shortcuts (ids: the numbers they had). The same bytes when none of ours is in it. The shortcuts
|
||||
/// after ours are named anew where the file counted them 0, 1, 2 ...; their values are the same bytes.</summary>
|
||||
public static byte[] Without(byte[] file, string exe, out List<uint> ids)
|
||||
{
|
||||
ids = new List<uint>();
|
||||
if (file.Length == 0) return file;
|
||||
var shortcuts = Shortcuts(Read(file));
|
||||
var number = Id(exe, Name);
|
||||
if (!shortcuts.Values!.Any(s => Ours(file, s, number))) return file;
|
||||
var counted = Counted(shortcuts);
|
||||
var o = new List<byte>();
|
||||
o.AddRange(Cut(file, 0, shortcuts.Value));
|
||||
var kept = 0;
|
||||
foreach (var s in shortcuts.Values!)
|
||||
{
|
||||
if (Ours(file, s, number))
|
||||
{
|
||||
ids.Add(Named(s.Values!, "appid", 2) is { } n ? BitConverter.ToUInt32(file, n.Value) : number);
|
||||
continue;
|
||||
}
|
||||
if (counted)
|
||||
{
|
||||
o.Add(s.Type);
|
||||
o.AddRange(Encoding.UTF8.GetBytes(kept.ToString()));
|
||||
o.Add(0);
|
||||
o.AddRange(Cut(file, s.Value, s.End));
|
||||
}
|
||||
else o.AddRange(Cut(file, s.Start, s.End));
|
||||
kept++;
|
||||
}
|
||||
o.AddRange(Cut(file, shortcuts.End - 1, file.Length));
|
||||
return Proved(file, o.ToArray(), number, 0);
|
||||
}
|
||||
|
||||
/// <summary>Does the file hold a shortcut of ours? False for a file that cannot be read.</summary>
|
||||
public static bool Has(byte[] file, string exe)
|
||||
{
|
||||
try { return file.Length > 0 && Shortcuts(Read(file)).Values!.Any(s => Ours(file, s, Id(exe, Name))); }
|
||||
catch (SteamException) { return false; }
|
||||
}
|
||||
|
||||
/// <summary>The program our shortcut starts (unquoted), "" when it names none, null when there is none.</summary>
|
||||
public static string? Where(byte[] file, string exe)
|
||||
{
|
||||
if (file.Length == 0) return null;
|
||||
var number = Id(exe, Name);
|
||||
var ours = Shortcuts(Read(file)).Values!.FirstOrDefault(s => Ours(file, s, number));
|
||||
if (ours == null) return null;
|
||||
return Named(ours.Values!, "Exe", 1) is { } e ? Text(file, e).Trim().Trim('"') : "";
|
||||
}
|
||||
|
||||
/// <summary>Before a new file is written: it reads as a shortcuts file, holds as many of ours as it should, and every shortcut of
|
||||
/// the old one that is not ours is in it, in the same order, with the same bytes.</summary>
|
||||
static byte[] Proved(byte[] old, byte[] fresh, uint id, int ours)
|
||||
{
|
||||
List<byte[]> Others(byte[] b, out int mine)
|
||||
{
|
||||
var all = Shortcuts(Read(b)).Values!;
|
||||
mine = all.Count(s => Ours(b, s, id));
|
||||
return all.Where(s => !Ours(b, s, id)).Select(s => Cut(b, s.Value, s.End)).ToList();
|
||||
}
|
||||
var before = Others(old, out _);
|
||||
var after = Others(fresh, out var now);
|
||||
if (now != ours || before.Count != after.Count || before.Where((x, i) => !x.SequenceEqual(after[i])).Any())
|
||||
throw new SteamException("The launcher could not put Steam's shortcuts file together again without changing other shortcuts, so it left the file alone. Nothing was changed.");
|
||||
return fresh;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Steam on this PC: its folder, its accounts, Add / Remove / Where for the game.</summary>
|
||||
public sealed class SteamLibrary
|
||||
{
|
||||
public const string Backup = ".triforce-backup", First = ".before-triforce", Temp = ".triforce-tmp";
|
||||
public const string CloseFirst = "Close Steam first. Steam writes its own list of shortcuts when it closes, and would take this change away again.";
|
||||
|
||||
readonly TriforceContext ctx;
|
||||
public SteamLibrary(TriforceContext ctx)
|
||||
{
|
||||
this.ctx = ctx;
|
||||
// (a test run has its own Steam folder, which the PC's Steam, running or not, has nothing to do with)
|
||||
Running = root =>
|
||||
{
|
||||
var procs = ctx.Platform.FindProcesses("steam");
|
||||
return ctx.TestRoot == null ? procs.Count > 0 : procs.Any(p => p.Exe != null && TriforceContext.Inside(ctx.TestRoot, p.Exe));
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Is Steam running? Asked before every write (a test puts its own answer here).</summary>
|
||||
public Func<string, bool> Running { get; set; }
|
||||
|
||||
public static bool Valid(string root) => Directory.Exists(Path.Combine(root, "userdata")) || File.Exists(Path.Combine(root, "steam.exe")) || File.Exists(Path.Combine(root, "steam.sh"));
|
||||
|
||||
/// <summary>Steam's folder on this PC, null when Steam is not there.</summary>
|
||||
public string? Root() => ctx.Platform.SteamRoots().FirstOrDefault(r => { try { return Valid(r); } catch (Exception) { return false; } });
|
||||
|
||||
/// <summary>The words and braces of one of Steam's text files ("name" "value", "name" { ... }).</summary>
|
||||
static List<string> Words(string text)
|
||||
{
|
||||
var words = new List<string>();
|
||||
for (var i = 0; i < text.Length; i++)
|
||||
{
|
||||
var c = text[i];
|
||||
if (c == '{' || c == '}') words.Add(c.ToString());
|
||||
else if (c == '/' && i + 1 < text.Length && text[i + 1] == '/') { while (i < text.Length && text[i] != '\n') i++; }
|
||||
else if (c == '"')
|
||||
{
|
||||
var s = new StringBuilder("\"");
|
||||
for (i++; i < text.Length && text[i] != '"'; i++)
|
||||
{
|
||||
if (text[i] == '\\' && i + 1 < text.Length) i++;
|
||||
s.Append(text[i]);
|
||||
}
|
||||
words.Add(s.ToString());
|
||||
}
|
||||
}
|
||||
return words;
|
||||
}
|
||||
|
||||
/// <summary>The accounts that have a folder under userdata, the one to use first: the one Steam marks as its most recent
|
||||
/// (config\loginusers.vdf), then by when each last signed in, then by when their folder was last written to.</summary>
|
||||
public static List<SteamUser> Users(string root)
|
||||
{
|
||||
var users = new List<SteamUser>();
|
||||
string[] folders = { };
|
||||
try { folders = Directory.GetDirectories(Path.Combine(root, "userdata")); } catch (Exception) { }
|
||||
foreach (var f in folders)
|
||||
{
|
||||
var id = Path.GetFileName(f);
|
||||
if (id != "0" && id.Length <= 10 && id.All(c => c >= '0' && c <= '9')) users.Add(new SteamUser { Root = root, Id = id });
|
||||
}
|
||||
try
|
||||
{
|
||||
var words = Words(File.ReadAllText(Path.Combine(root, "config", "loginusers.vdf")));
|
||||
const long first = 76561197960265728; // (an account's number in that file is this much more than its folder's name)
|
||||
SteamUser? user = null;
|
||||
var depth = 0;
|
||||
for (var i = 0; i < words.Count; i++)
|
||||
{
|
||||
if (words[i] == "{") { depth++; continue; }
|
||||
if (words[i] == "}") { depth--; if (depth < 2) user = null; continue; }
|
||||
var word = words[i].Substring(1);
|
||||
if (depth == 1 && i + 1 < words.Count && words[i + 1] == "{")
|
||||
user = long.TryParse(word, out var id64) && id64 > first ? users.FirstOrDefault(u => u.Id == (id64 - first).ToString()) : null;
|
||||
else if (depth == 2 && user != null && i + 1 < words.Count && words[i + 1].StartsWith('"'))
|
||||
{
|
||||
var value = words[++i].Substring(1);
|
||||
if (string.Equals(word, "PersonaName", StringComparison.OrdinalIgnoreCase)) user.Name = value;
|
||||
else if (string.Equals(word, "MostRecent", StringComparison.OrdinalIgnoreCase)) user.Recent = value == "1";
|
||||
else if (string.Equals(word, "Timestamp", StringComparison.OrdinalIgnoreCase)) long.TryParse(value, out user.Seen);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
DateTime Written(SteamUser u)
|
||||
{
|
||||
try { return Directory.GetLastWriteTimeUtc(Directory.Exists(u.Config) ? u.Config : Path.GetDirectoryName(u.Config)!); } catch (Exception) { return DateTime.MinValue; }
|
||||
}
|
||||
return users.OrderByDescending(u => u.Recent).ThenByDescending(u => u.Seen).ThenByDescending(Written).ThenBy(u => u.Id, StringComparer.Ordinal).ToList();
|
||||
}
|
||||
|
||||
/// <summary>The account Steam was last signed in with, null when there is no Steam or nobody signed in.</summary>
|
||||
public SteamUser? User() => Root() is { } r ? Users(r).FirstOrDefault() : null;
|
||||
|
||||
/// <summary>What the game's shortcut starts: Windows the game's own Triforce.exe; Linux the folder's "triforce" launcher script
|
||||
/// (research/12 6: it shows Update; the AppImage's --play would go straight to the game).</summary>
|
||||
public string ShortcutTarget(string gameFolder) => ctx.IsWindows
|
||||
? new Game(ctx).FindExe(gameFolder) ?? Path.Combine(gameFolder, "Triforce.exe")
|
||||
: Path.Combine(gameFolder, "triforce");
|
||||
|
||||
/// <summary>Only an account's own config folder is ever written to (and, in a test run, only inside the test folder).</summary>
|
||||
void Within(SteamUser user, string path)
|
||||
{
|
||||
if (!TriforceContext.Inside(user.Config, path) || TriforceContext.SamePath(user.Config, path))
|
||||
throw new InvalidOperationException("The launcher would have written outside Steam's settings folder for the account (" + path + "), and did not.");
|
||||
ctx.Require(path);
|
||||
}
|
||||
|
||||
/// <summary>A file written whole or not at all: beside its place first, then under its name in one step.</summary>
|
||||
void WriteWhole(SteamUser user, string file, byte[] bytes)
|
||||
{
|
||||
Within(user, file);
|
||||
var temp = file + Temp;
|
||||
try
|
||||
{
|
||||
using (var f = new FileStream(temp, FileMode.Create, FileAccess.Write, FileShare.None))
|
||||
{
|
||||
f.Write(bytes, 0, bytes.Length);
|
||||
f.Flush(true);
|
||||
}
|
||||
ctx.Platform.ReplaceFile(temp, file);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
try { File.Delete(temp); } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
static byte[] Bytes(string file)
|
||||
{
|
||||
try { return File.ReadAllBytes(file); }
|
||||
catch (Exception e) when (e is FileNotFoundException || e is DirectoryNotFoundException) { return Array.Empty<byte>(); }
|
||||
}
|
||||
|
||||
/// <summary>The new shortcuts file in place of the old one: the file as it was is kept first; should the file have changed since
|
||||
/// it was read, nothing is written.</summary>
|
||||
void Replace(SteamUser user, byte[] old, byte[] fresh)
|
||||
{
|
||||
var file = user.Shortcuts;
|
||||
if (old.SequenceEqual(fresh) && File.Exists(file)) return;
|
||||
if (Running(user.Root)) throw new SteamException(CloseFirst);
|
||||
if (!Bytes(file).SequenceEqual(old)) throw new SteamException("Steam's shortcuts file changed while the launcher worked on it. Nothing was changed. Close Steam and try again.");
|
||||
if (File.Exists(file))
|
||||
{
|
||||
if (!File.Exists(file + First)) WriteWhole(user, file + First, old);
|
||||
WriteWhole(user, file + Backup, old);
|
||||
}
|
||||
WriteWhole(user, file, fresh);
|
||||
}
|
||||
|
||||
static T Guarded<T>(Func<T> work)
|
||||
{
|
||||
try { return work(); }
|
||||
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
|
||||
{
|
||||
throw new SteamException("Steam's files could not be written: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
static string Quoted(string path) => "\"" + path + "\"";
|
||||
|
||||
/// <summary>Is our shortcut in this account's library?</summary>
|
||||
public bool Added(SteamUser user, string gameExe)
|
||||
{
|
||||
try { return SteamVdf.Has(Bytes(user.Shortcuts), Quoted(gameExe)); } catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
/// <summary>The program our shortcut in this account's library starts, null when there is none (the "Set to this folder" case
|
||||
/// when it is another folder's).</summary>
|
||||
public string? Where(SteamUser user, string gameExe)
|
||||
{
|
||||
try { return SteamVdf.Where(Bytes(user.Shortcuts), Quoted(gameExe)); } catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
/// <summary>Adds the game to an account's library, or sets a shortcut of ours that is there to this game folder. pictures: each
|
||||
/// kind of SteamVdf.Pictures as a PNG file's bytes (the App draws them); where the shortcut was there already, only the pictures
|
||||
/// that are missing are written, and the pictures of its old number move to the new one. True when the shortcut is new.</summary>
|
||||
public bool Add(SteamUser user, string gameExe, IReadOnlyDictionary<string, byte[]> pictures) => Guarded(() =>
|
||||
{
|
||||
if (Running(user.Root)) throw new SteamException(CloseFirst);
|
||||
if (!Directory.Exists(Path.GetDirectoryName(user.Config)))
|
||||
throw new SteamException("Steam has no folder for that account. Start Steam, sign in once, close it, then try again.");
|
||||
var old = Bytes(user.Shortcuts);
|
||||
var exe = Quoted(gameExe);
|
||||
var icon = Path.Combine(user.Grid, SteamVdf.Id(exe, SteamVdf.Name) + "_icon.png");
|
||||
var fresh = SteamVdf.With(old, exe, Quoted(Path.GetDirectoryName(gameExe) ?? ""), pictures.ContainsKey("icon") ? icon : gameExe, out var id, out var wasThere);
|
||||
Within(user, Path.Combine(user.Grid, "x"));
|
||||
Directory.CreateDirectory(user.Grid);
|
||||
var had = new List<uint>();
|
||||
if (wasThere) SteamVdf.Without(old, exe, out had);
|
||||
foreach (var (kind, name, _, _) in SteamVdf.Pictures)
|
||||
{
|
||||
var file = Path.Combine(user.Grid, id + name);
|
||||
foreach (var before in had.Where(h => h != id).Select(h => Path.Combine(user.Grid, h + name)).Where(File.Exists))
|
||||
{
|
||||
Within(user, before);
|
||||
if (File.Exists(file)) File.Delete(before); else File.Move(before, file);
|
||||
}
|
||||
if (pictures.TryGetValue(kind, out var png) && (!wasThere || !File.Exists(file))) WriteWhole(user, file, png);
|
||||
}
|
||||
Replace(user, old, fresh);
|
||||
// (no account's name or number in the log: it is pasted where help is asked for)
|
||||
ctx.Log.Write("steam: the shortcut was " + (wasThere ? "set to " + gameExe : "added") + " for the account Steam was last signed in with");
|
||||
return !wasThere;
|
||||
});
|
||||
|
||||
/// <summary>Takes our shortcut out of an account's library again, and its pictures out of config\grid. False when it was not there.</summary>
|
||||
public bool Remove(SteamUser user, string gameExe) => Guarded(() =>
|
||||
{
|
||||
if (Running(user.Root)) throw new SteamException(CloseFirst);
|
||||
var old = Bytes(user.Shortcuts);
|
||||
var fresh = SteamVdf.Without(old, Quoted(gameExe), out var ids);
|
||||
if (ids.Count == 0) return false;
|
||||
Replace(user, old, fresh);
|
||||
foreach (var id in ids)
|
||||
foreach (var (_, name, _, _) in SteamVdf.Pictures)
|
||||
{
|
||||
var file = Path.Combine(user.Grid, id + name);
|
||||
Within(user, file);
|
||||
try { if (File.Exists(file)) File.Delete(file); } catch (Exception) { }
|
||||
}
|
||||
ctx.Log.Write("steam: the shortcut was removed for the account Steam was last signed in with");
|
||||
return true;
|
||||
});
|
||||
}
|
||||
425
launcher/Logic/Tools.cs
Normal file
425
launcher/Logic/Tools.cs
Normal file
@@ -0,0 +1,425 @@
|
||||
// The Triforce tools beside the installed launcher: nx2/make_game.py and its own Python (Windows: <install>\tools from
|
||||
// Triforce-Tools.zip; Linux: the AppImage's usr/share/hookshot, HOOKSHOT_TOOLS). Old Setup.cs Tools and Shell.cs Merge step 2.
|
||||
using System.IO.Compression;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>Where make_game.py is and the Python that runs it.</summary>
|
||||
public sealed record ToolSet(string Root, string Python)
|
||||
{
|
||||
public string MakeGame => Path.Combine(Root, "nx2", "make_game.py");
|
||||
}
|
||||
|
||||
/// <summary>A step of a tools update: what it does now and how far it is.</summary>
|
||||
public sealed record ToolsProgress(ToolsStep Step, double Fraction, long Bytes, long Total, string Text);
|
||||
|
||||
public enum ToolsStep { Download, CheckBase, DownloadBase, Unpack, Done }
|
||||
|
||||
public sealed class Tools
|
||||
{
|
||||
readonly TriforceContext ctx;
|
||||
public Tools(TriforceContext ctx) { this.ctx = ctx; }
|
||||
|
||||
/// <summary><install>\tools (tools.part and tools.old beside it during a swap).</summary>
|
||||
public string Folder => ctx.ToolsFolder;
|
||||
|
||||
/// <summary>The release these tools came from (tools\version.txt, Linux usr/share/hookshot/VERSION), null when there are none.</summary>
|
||||
public string? InstalledVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
var v = Path.Combine(Folder, "version.txt");
|
||||
if (File.Exists(v) && File.Exists(Path.Combine(Folder, "nx2", "make_game.py"))) return ReadLine(v);
|
||||
if (!ctx.IsWindows && LinuxTools() is { } t)
|
||||
foreach (var name in new[] { "VERSION", "version.txt" })
|
||||
if (ReadLine(Path.Combine(t.Root, name)) is { Length: > 0 } tag) return tag;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static string? ReadLine(string file)
|
||||
{
|
||||
try { return File.Exists(file) ? File.ReadLines(file).FirstOrDefault()?.Trim() : null; } catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
/// <summary>The tools to run make_game with, null when there are none. Windows: <install>\tools with its python\python.exe (or
|
||||
/// "python" from the PATH when that file is missing); else, outside a test run, a development checkout above the exe
|
||||
/// (TRIFORCE_PYTHON or "python"). Linux: HOOKSHOT_TOOLS, with HOOKSHOT_PYTHON or the image's usr/python/bin/python3.</summary>
|
||||
public ToolSet? Find()
|
||||
{
|
||||
var bundled = Folder;
|
||||
if (File.Exists(Path.Combine(bundled, "nx2", "make_game.py")))
|
||||
{
|
||||
var py = ctx.IsWindows ? Path.Combine(bundled, "python", "python.exe") : Path.Combine(bundled, "python", "bin", "python3");
|
||||
return new ToolSet(bundled, File.Exists(py) ? py : ctx.IsWindows ? "python" : "python3");
|
||||
}
|
||||
if (!ctx.IsWindows && LinuxTools() is { } lt) return lt;
|
||||
// (a development copy: the launcher run from inside a checkout uses its sources and the PC's Python. Never in a test run,
|
||||
// which has its own tools or none)
|
||||
if (ctx.TestRoot != null) return null;
|
||||
for (var d = new DirectoryInfo(ctx.SelfDir); d != null; d = d.Parent)
|
||||
if (File.Exists(Path.Combine(d.FullName, "nx2", "make_game.py")))
|
||||
return new ToolSet(d.FullName, ctx.Env("TRIFORCE_PYTHON") ?? (ctx.IsWindows ? "python" : "python3"));
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Linux: the AppImage's tools (AppRun exports HOOKSHOT_TOOLS; research/12 1.3). Its Python: HOOKSHOT_PYTHON when
|
||||
/// AppRun exports it (research/12 4.1 asks for that), else <root>/usr/python/bin/python3 beside usr/share/hookshot.</summary>
|
||||
ToolSet? LinuxTools()
|
||||
{
|
||||
var tools = ctx.Env("HOOKSHOT_TOOLS");
|
||||
if (string.IsNullOrEmpty(tools) && ctx.Env("APPDIR") is { Length: > 0 } appdir) tools = Path.Combine(appdir, "usr", "share", "hookshot");
|
||||
if (string.IsNullOrEmpty(tools) || !File.Exists(Path.Combine(tools, "nx2", "make_game.py"))) return null;
|
||||
var py = ctx.Env("HOOKSHOT_PYTHON");
|
||||
if (string.IsNullOrEmpty(py))
|
||||
{
|
||||
var root = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetFullPath(tools).TrimEnd('/'))));
|
||||
var guess = root != null ? Path.Combine(root, "usr", "python", "bin", "python3") : null;
|
||||
py = guess != null && File.Exists(guess) ? guess : "python3";
|
||||
}
|
||||
return new ToolSet(tools, py);
|
||||
}
|
||||
|
||||
/// <summary>What an unpacking that was cut off left behind: a tools.part of up to a gigabyte that is never used and stood in
|
||||
/// the way of the next try's room, and a tools.old whose removal failed (the tools that were there are the rollback point).</summary>
|
||||
public void Sweep()
|
||||
{
|
||||
try { if (Directory.Exists(Folder + ".part")) Directory.Delete(Folder + ".part", true); } catch (Exception) { }
|
||||
try { if (!Directory.Exists(Folder) && Directory.Exists(Folder + ".old")) Directory.Move(Folder + ".old", Folder); } catch (Exception) { }
|
||||
try { if (Directory.Exists(Folder) && Directory.Exists(Folder + ".old")) Directory.Delete(Folder + ".old", true); } catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>Unpacks Triforce-Tools.zip as the tools folder (the old one replaced only once the new one is complete).</summary>
|
||||
public void Unpack(string zip, string tag, Action<double>? progress)
|
||||
{
|
||||
var target = Folder;
|
||||
ctx.Require(target);
|
||||
var part = target + ".part";
|
||||
if (Directory.Exists(part)) Directory.Delete(part, true);
|
||||
try
|
||||
{
|
||||
using (var z = ZipFile.OpenRead(zip))
|
||||
{
|
||||
// (room for all of it, asked before the first file: the zip says what each one unpacks to, and 4 KB are counted for
|
||||
// each on top, since a file takes whole clusters. The tools there now stay until the new ones are complete)
|
||||
var bytes = z.Entries.Sum(e => e.Length) + z.Entries.Count * 4096L;
|
||||
if (ctx.SpaceProblem("the Triforce tools", bytes, part) is { } none) throw new NoRoomException(none);
|
||||
Directory.CreateDirectory(part);
|
||||
ExtractChecked(z, part, progress);
|
||||
}
|
||||
File.WriteAllText(Path.Combine(part, "version.txt"), tag + "\n");
|
||||
// ((Triforce) a whole zip's base is the one its list names: the next update keeps it without reading it again)
|
||||
if (ReadBaseList(Path.Combine(part, BaseList)) is { } listed) File.WriteAllText(Path.Combine(part, BaseHave), listed.Id + "\n");
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// (half a tools folder, a gigabyte of it, is of no use and stood in the way of the next try's room)
|
||||
try { if (Directory.Exists(part)) Directory.Delete(part, true); } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
SwapIn(part, target, null);
|
||||
progress?.Invoke(1);
|
||||
}
|
||||
|
||||
/// <summary>tools.part into tools' place: tools to tools.old, tools.part to tools; a failure puts the old folder back (a virus
|
||||
/// scanner holding the new one left no tools folder at all, and the next start found no tools).</summary>
|
||||
static void SwapIn(string part, string target, Action? putBack)
|
||||
{
|
||||
var old = target + ".old";
|
||||
if (Directory.Exists(old)) Directory.Delete(old, true);
|
||||
if (Directory.Exists(target)) Directory.Move(target, old);
|
||||
try { Directory.Move(part, target); }
|
||||
catch (Exception)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(target) && Directory.Exists(old)) Directory.Move(old, target);
|
||||
putBack?.Invoke();
|
||||
}
|
||||
catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
try { if (Directory.Exists(old)) Directory.Delete(old, true); } catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>A tools zip's files into folder. The prefix tools/ is stripped when every entry has it (\ read as /). Every name is
|
||||
/// checked before the first file is written, as a mod archive's are (Mods.Unsafe): a device name, a colon, a name that ends in
|
||||
/// a dot or a space, a path out of the folder. Such a zip is refused whole.</summary>
|
||||
static void ExtractChecked(ZipArchive z, string folder, Action<double>? progress)
|
||||
{
|
||||
var prefix = z.Entries.All(e => e.FullName.Replace('\\', '/').StartsWith("tools/", StringComparison.OrdinalIgnoreCase)) ? "tools/" : "";
|
||||
foreach (var e in z.Entries)
|
||||
{
|
||||
var name = e.FullName.Replace('\\', '/').Substring(prefix.Length);
|
||||
if (name.Length > 0 && Mods.Unsafe(name, true) is { } why)
|
||||
throw new InvalidDataException("The tools' zip holds " + why + " (\"" + (name.Length > 120 ? name.Substring(0, 117) + "..." : name) + "\"): it was not unpacked.");
|
||||
}
|
||||
var full = Path.GetFullPath(folder) + Path.DirectorySeparatorChar;
|
||||
var cmp = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
for (var i = 0; i < z.Entries.Count; i++)
|
||||
{
|
||||
var e = z.Entries[i];
|
||||
var name = e.FullName.Replace('\\', '/').Substring(prefix.Length);
|
||||
if (name.Length == 0) continue;
|
||||
var dest = Path.GetFullPath(Path.Combine(folder, name));
|
||||
if (!dest.StartsWith(full, cmp)) continue; // (no paths out of the folder)
|
||||
if (name.EndsWith('/')) { Directory.CreateDirectory(dest); continue; }
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(dest)!);
|
||||
e.ExtractToFile(dest, true);
|
||||
if ((i & 15) == 0) progress?.Invoke((double)i / z.Entries.Count);
|
||||
}
|
||||
}
|
||||
|
||||
void Extract(string zip, string folder, Action<double>? progress)
|
||||
{
|
||||
using var z = ZipFile.OpenRead(zip);
|
||||
var bytes = z.Entries.Sum(e => e.Length) + z.Entries.Count * 4096L;
|
||||
if (ctx.SpaceProblem("the Triforce tools", bytes, folder) is { } none) throw new NoRoomException(none);
|
||||
ExtractChecked(z, folder, progress);
|
||||
}
|
||||
|
||||
// ---- (Triforce, 11-18) the tools in two parts: the base kept from one release to the next ----
|
||||
// setup/pack_tools.ps1 lists the base (the compiler, Python, the libraries: the folders that do not change between releases,
|
||||
// 95 % of Triforce-Tools.zip) in tools/base.list, which the code part and the whole zip carry. An update of tools that hold
|
||||
// that base fetches the code part alone and moves the base folders over from the tools there now. The base is the list's
|
||||
// when every file it names is there with its size and SHA-256 (read once: base.have then remembers the list's id, and later
|
||||
// updates check the sizes alone). Anything else fetches the base part as well.
|
||||
public const string BaseList = "base.list", BaseHave = "base.have";
|
||||
|
||||
public sealed class Base
|
||||
{
|
||||
public string Id = ""; // (the SHA-256 of the list's dir and file lines)
|
||||
public readonly List<string> Dirs = new();
|
||||
public readonly List<(string Path, long Size, string Sha)> Files = new();
|
||||
}
|
||||
|
||||
/// <summary>A base list's text: "triforce-tools-base\t1", "id\t<sha256>", then "dir\t<name>" and
|
||||
/// "file\t<size>\t<sha256>\t<path>" lines (paths with /). Null when it is not one; an unknown line makes it none.</summary>
|
||||
public static Base? ParseBaseList(string text)
|
||||
{
|
||||
var lines = text.Replace("\r", "").Split('\n');
|
||||
if (lines.Length < 2 || lines[0].Trim() != "triforce-tools-base\t1") return null;
|
||||
var b = new Base();
|
||||
foreach (var line in lines.Skip(1))
|
||||
{
|
||||
var f = line.Split('\t');
|
||||
if (f.Length == 2 && f[0] == "id") b.Id = f[1].Trim().ToLowerInvariant();
|
||||
else if (f.Length == 2 && f[0] == "dir" && f[1].Length > 0 && Mods.Unsafe(f[1], true) == null && !f[1].Contains('/')) b.Dirs.Add(f[1]);
|
||||
else if (f.Length == 4 && f[0] == "file" && long.TryParse(f[1], out var size) && f[2].Length == 64 && Mods.Unsafe(f[3], true) == null)
|
||||
b.Files.Add((f[3], size, f[2].ToLowerInvariant()));
|
||||
else if (line.Length > 0) return null; // (a line it does not know: another format, not guessed at)
|
||||
}
|
||||
return b.Id.Length == 64 && b.Dirs.Count > 0 && b.Files.Count > 0 ? b : null;
|
||||
}
|
||||
|
||||
public static Base? ReadBaseList(string path)
|
||||
{
|
||||
try { return File.Exists(path) ? ParseBaseList(File.ReadAllText(path)) : null; } catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
/// <summary>The base list in a code (or whole) zip, null when it has none.</summary>
|
||||
public static Base? BaseListIn(string zip)
|
||||
{
|
||||
using var z = ZipFile.OpenRead(zip);
|
||||
var e = z.Entries.FirstOrDefault(x => x.FullName.Replace('\\', '/') is var n && (n == "tools/" + BaseList || n == BaseList));
|
||||
if (e == null) return null;
|
||||
using var r = new StreamReader(e.Open());
|
||||
return ParseBaseList(r.ReadToEnd());
|
||||
}
|
||||
|
||||
/// <summary>Whether the tools in folder hold base b whole (progress: 0..1 while it reads the files). Remembers a match in base.have.</summary>
|
||||
public static bool HasBase(Base b, string folder, Action<double>? progress)
|
||||
{
|
||||
foreach (var d in b.Dirs)
|
||||
if (!Directory.Exists(Path.Combine(folder, d))) return false;
|
||||
foreach (var f in b.Files) // (every file there, at its size: quick, and enough once base.have says the rest was read)
|
||||
{
|
||||
var fi = new FileInfo(Path.Combine(folder, f.Path));
|
||||
if (!fi.Exists || fi.Length != f.Size) return false;
|
||||
}
|
||||
string? had = null;
|
||||
try { had = File.Exists(Path.Combine(folder, BaseHave)) ? File.ReadAllText(Path.Combine(folder, BaseHave)).Trim() : null; } catch (Exception) { }
|
||||
if (had == b.Id) return true;
|
||||
long total = Math.Max(1, b.Files.Sum(f => f.Size)), done = 0;
|
||||
foreach (var f in b.Files)
|
||||
{
|
||||
string got;
|
||||
using (var s = File.OpenRead(Path.Combine(folder, f.Path))) got = Convert.ToHexStringLower(SHA256.HashData(s));
|
||||
if (got != f.Sha) return false;
|
||||
done += f.Size;
|
||||
progress?.Invoke((double)done / total);
|
||||
}
|
||||
try { File.WriteAllText(Path.Combine(folder, BaseHave), b.Id + "\n"); } catch (Exception) { }
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The tools folder made again from a code zip and either a base zip (baseZip) or the base folders of the tools there
|
||||
/// now (baseZip null: HasBase said they are b's). The old folder is replaced only once the new one is complete; what fails on
|
||||
/// the way puts the base folders back where they were.</summary>
|
||||
public void UnpackParts(string codeZip, string? baseZip, Base b, string tag, Action<double>? progress)
|
||||
{
|
||||
var target = Folder;
|
||||
ctx.Require(target);
|
||||
var part = target + ".part";
|
||||
if (Directory.Exists(part)) Directory.Delete(part, true);
|
||||
var moved = new List<string>();
|
||||
void PutBack()
|
||||
{
|
||||
foreach (var d in moved)
|
||||
try { if (Directory.Exists(target) && !Directory.Exists(Path.Combine(target, d))) Directory.Move(Path.Combine(part, d), Path.Combine(target, d)); }
|
||||
catch (Exception) { }
|
||||
}
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(part);
|
||||
Extract(codeZip, part, f => progress?.Invoke(baseZip == null ? f * 0.9 : f * 0.1));
|
||||
if (baseZip != null) Extract(baseZip, part, f => progress?.Invoke(0.1 + f * 0.8));
|
||||
else
|
||||
foreach (var d in b.Dirs)
|
||||
{
|
||||
var into = Path.Combine(part, d);
|
||||
if (Directory.Exists(into)) Directory.Delete(into, true); // (a code zip has none of them; never mixed)
|
||||
Directory.Move(Path.Combine(target, d), into);
|
||||
moved.Add(d);
|
||||
}
|
||||
foreach (var f in b.Files) // (the base whole in the new folder, whichever way it came)
|
||||
{
|
||||
var fi = new FileInfo(Path.Combine(part, f.Path));
|
||||
if (!fi.Exists || fi.Length != f.Size) throw new InvalidDataException("The tools' base lacks " + f.Path + " (or it has another size): they were not changed.");
|
||||
}
|
||||
File.WriteAllText(Path.Combine(part, "version.txt"), tag + "\n");
|
||||
File.WriteAllText(Path.Combine(part, BaseHave), b.Id + "\n");
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
PutBack();
|
||||
try { if (Directory.Exists(part)) Directory.Delete(part, true); } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
SwapIn(part, target, PutBack);
|
||||
progress?.Invoke(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Merge's step 2 (old Shell.cs Merge and ToolsInParts): the release's tools into <install>\tools, downloaded through
|
||||
/// Downloader into <install>\downloads\Triforce-Tools-<tag>.zip with the sizes the release lists. Windows only: on Linux the
|
||||
/// tools come with the AppImage.</summary>
|
||||
public sealed class ToolsInstaller
|
||||
{
|
||||
readonly TriforceContext ctx;
|
||||
readonly Tools tools;
|
||||
readonly Downloader downloader;
|
||||
public ToolsInstaller(TriforceContext ctx, Downloader? downloader = null)
|
||||
{
|
||||
this.ctx = ctx;
|
||||
tools = new Tools(ctx);
|
||||
this.downloader = downloader ?? new Downloader(ctx);
|
||||
}
|
||||
|
||||
// (what the tools take unpacked, until their zip is here to say it exactly: v0.4.0's Triforce-Tools.zip is 284 MB and unpacks
|
||||
// to 1.1 GB in 13,230 files, 3.9 times its size)
|
||||
public const int UnpackedTimes = 5;
|
||||
|
||||
public event Action<ToolsProgress>? Progress;
|
||||
void Say(ToolsStep step, double f, long bytes, long total, string text) => Progress?.Invoke(new ToolsProgress(step, f, bytes, total, text));
|
||||
|
||||
/// <summary>Are the release's tools another than the ones here?</summary>
|
||||
public bool Needed(Release r) => tools.InstalledVersion != r.Tag;
|
||||
|
||||
static string SafeTag(string tag) => string.Concat(tag.Where(c => char.IsLetterOrDigit(c) || c == '.' || c == '-'));
|
||||
static long Length(string file) { try { return File.Exists(file) ? new FileInfo(file).Length : 0; } catch (Exception) { return 0; } }
|
||||
|
||||
/// <summary>The tools of release r, when the ones here are not its own. Parts when the tools are here and the release has its
|
||||
/// code and base apart (the code alone, the base only when the one here is not the release's); otherwise, or when the code
|
||||
/// part carries no base list, the whole zip. A zip that is there whole (by its size) is not fetched again.</summary>
|
||||
public async Task UpdateAsync(HttpClient http, Release r, CancellationToken token)
|
||||
{
|
||||
if (!Needed(r)) return;
|
||||
if (r.ToolsUrl == null) throw new InvalidOperationException("The release " + r.Tag + " has no " + BuildInfo.ToolsAsset + ".");
|
||||
var have = tools.InstalledVersion;
|
||||
var cache = ctx.DownloadsFolder;
|
||||
ctx.Require(cache);
|
||||
Directory.CreateDirectory(cache);
|
||||
var zip = Path.Combine(cache, "Triforce-Tools-" + SafeTag(r.Tag) + ".zip");
|
||||
await Task.Run(tools.Sweep, token).ConfigureAwait(false);
|
||||
var parts = have != null && r.ToolsCodeUrl != null && r.ToolsBaseUrl != null && await InPartsAsync(http, r, have, cache, token).ConfigureAwait(false);
|
||||
if (!parts)
|
||||
{
|
||||
var whole = r.ToolsSize > 0 && Length(zip) == r.ToolsSize;
|
||||
var unpacked = r.ToolsSize * UnpackedTimes;
|
||||
if (r.ToolsSize > 0 && ctx.SpaceProblem("the Triforce tools (a download of " + (r.ToolsSize >> 20) + " MB that unpacks to about " + (unpacked >> 20) + " MB)",
|
||||
(whole ? 0 : Math.Max(0, r.ToolsSize - Length(zip + ".part"))) + unpacked, cache) is { } none)
|
||||
throw new NoRoomException(none);
|
||||
var text = have == null ? "Downloading Triforce's tools" : "Downloading the tools of " + r.Tag;
|
||||
Say(ToolsStep.Download, 0, 0, r.ToolsSize, text);
|
||||
if (!whole)
|
||||
await downloader.ToFileAsync(http, r.ToolsUrl, zip, r.ToolsSize, p => Say(ToolsStep.Download, p.Fraction, p.Bytes, p.Total, text), token).ConfigureAwait(false);
|
||||
else ctx.Log.Write("tools " + r.Tag + ": the zip is here already, whole (" + r.ToolsSize + " bytes)");
|
||||
Say(ToolsStep.Unpack, 0, 0, 0, "Unpacking the tools");
|
||||
try { await Task.Run(() => tools.Unpack(zip, r.Tag, f => Say(ToolsStep.Unpack, f, 0, 0, "Unpacking the tools")), CancellationToken.None).ConfigureAwait(false); }
|
||||
catch (Exception e) when (e is not NoRoomException && !ctx.Platform.IsDiskFull(e))
|
||||
{
|
||||
// (a zip that does not unpack is fetched again at the next try, not tried again; one there was no room for is kept)
|
||||
try { File.Delete(zip); } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
Leavings(cache);
|
||||
ctx.Log.Write("tools " + r.Tag + " unpacked into " + tools.Folder);
|
||||
}
|
||||
Say(ToolsStep.Done, 1, 0, 0, "The tools are ready");
|
||||
}
|
||||
|
||||
/// <summary>The downloads of this and other releases: parts nothing will go on from.</summary>
|
||||
static void Leavings(string cache)
|
||||
{
|
||||
string[] leavings = { };
|
||||
try { leavings = Directory.GetFiles(cache, "Triforce-Tools-*"); } catch (Exception) { }
|
||||
foreach (var f in leavings)
|
||||
try { File.Delete(f); } catch (Exception) { }
|
||||
}
|
||||
|
||||
async Task<bool> InPartsAsync(HttpClient http, Release r, string have, string cache, CancellationToken token)
|
||||
{
|
||||
var tag = SafeTag(r.Tag);
|
||||
var code = Path.Combine(cache, "Triforce-Tools-code-" + tag + ".zip");
|
||||
var baseZip = Path.Combine(cache, "Triforce-Tools-base-" + tag + ".zip");
|
||||
var text = "Downloading the new code of " + r.Tag + "; the compiler and Python you have are kept";
|
||||
Say(ToolsStep.Download, 0, 0, r.ToolsCodeSize, text);
|
||||
if (!(r.ToolsCodeSize > 0 && Length(code) == r.ToolsCodeSize))
|
||||
await downloader.ToFileAsync(http, r.ToolsCodeUrl!, code, r.ToolsCodeSize, p => Say(ToolsStep.Download, p.Fraction, p.Bytes, p.Total, text), token).ConfigureAwait(false);
|
||||
var b = await Task.Run(() => { try { return Tools.BaseListIn(code); } catch (Exception) { return null; } }, token).ConfigureAwait(false);
|
||||
if (b == null)
|
||||
{
|
||||
ctx.Log.Write("tools " + r.Tag + ": the code part names no base: the whole zip instead");
|
||||
try { File.Delete(code); } catch (Exception) { }
|
||||
return false;
|
||||
}
|
||||
Say(ToolsStep.CheckBase, 0, 0, 0, "Checking the tools you have");
|
||||
var keep = await Task.Run(() => { try { return Tools.HasBase(b, tools.Folder, f => Say(ToolsStep.CheckBase, f, 0, 0, "Checking the tools you have")); } catch (Exception) { return false; } }, token).ConfigureAwait(false);
|
||||
ctx.Log.Write("tools " + r.Tag + ": the base (" + b.Files.Count + " files) " + (keep ? "is the one here: kept" : "is not the one here: fetched"));
|
||||
if (!keep)
|
||||
{
|
||||
var unpacked = r.ToolsBaseSize * UnpackedTimes;
|
||||
if (r.ToolsBaseSize > 0 && ctx.SpaceProblem("the Triforce tools (a download of " + (r.ToolsBaseSize >> 20) + " MB that unpacks to about " + (unpacked >> 20) + " MB)",
|
||||
Math.Max(0, r.ToolsBaseSize - Length(baseZip + ".part")) + unpacked, cache) is { } none)
|
||||
throw new NoRoomException(none);
|
||||
var bt = "Downloading the compiler and Python (" + (r.ToolsBaseSize >> 20) + " MB)";
|
||||
Say(ToolsStep.DownloadBase, 0, 0, r.ToolsBaseSize, bt);
|
||||
if (!(r.ToolsBaseSize > 0 && Length(baseZip) == r.ToolsBaseSize))
|
||||
await downloader.ToFileAsync(http, r.ToolsBaseUrl!, baseZip, r.ToolsBaseSize, p => Say(ToolsStep.DownloadBase, p.Fraction, p.Bytes, p.Total, bt), token).ConfigureAwait(false);
|
||||
}
|
||||
Say(ToolsStep.Unpack, 0, 0, 0, "Unpacking the tools");
|
||||
try { await Task.Run(() => tools.UnpackParts(code, keep ? null : baseZip, b, r.Tag, f => Say(ToolsStep.Unpack, f, 0, 0, "Unpacking the tools")), CancellationToken.None).ConfigureAwait(false); }
|
||||
catch (Exception e) when (e is not NoRoomException && !ctx.Platform.IsDiskFull(e))
|
||||
{
|
||||
// (parts that do not unpack are fetched again at the next try, not tried again)
|
||||
try { File.Delete(code); } catch (Exception) { }
|
||||
try { File.Delete(baseZip); } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
Leavings(cache);
|
||||
ctx.Log.Write("tools " + r.Tag + " unpacked into " + tools.Folder + " from its parts (" + (keep ? "the base kept" : "the base fetched") + ")");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
37
launcher/Logic/Triforce.Logic.csproj
Normal file
37
launcher/Logic/Triforce.Logic.csproj
Normal file
@@ -0,0 +1,37 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- The launcher's logic without a window: install, update, tools, game intake, the build, play, saves, mods, Steam,
|
||||
uninstall. Ported from the old WPF Setup (setup/*.cs) and the Linux Tk builder (builder/linux/*.py). The App calls it;
|
||||
nothing here draws. -->
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>Triforce.Logic</RootNamespace>
|
||||
<AssemblyName>Triforce.Logic</AssemblyName>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<!-- (the release tag this launcher is: the ONE place it is set. build/release: dotnet publish -p:TriforceVersion=v0.5.2.
|
||||
Old Setups compare it with the release's tag_name by plain string inequality (research/02 2.3, 2.8 point 6): it must
|
||||
be the tag exactly, "v" included, or every Setup downloads it again at every start. "dev" for a local build, which
|
||||
never replaces itself) -->
|
||||
<TriforceVersion Condition="'$(TriforceVersion)' == ''">dev</TriforceVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Triforce.LogicTests" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- BuildInfo.Version as a const, written from TriforceVersion before each compile -->
|
||||
<Target Name="TriforceVersionFile" BeforeTargets="CoreCompile">
|
||||
<PropertyGroup>
|
||||
<TriforceVersionFile>$(IntermediateOutputPath)TriforceVersion.g.cs</TriforceVersionFile>
|
||||
</PropertyGroup>
|
||||
<WriteLinesToFile File="$(TriforceVersionFile)" Overwrite="true" WriteOnlyWhenDifferent="true"
|
||||
Lines="// generated from the TriforceVersion property (Triforce.Logic.csproj): do not edit;namespace Triforce.Logic%3B;public static partial class BuildInfo { public const string Version = "$(TriforceVersion)"%3B }" />
|
||||
<ItemGroup>
|
||||
<Compile Include="$(TriforceVersionFile)" />
|
||||
<FileWrites Include="$(TriforceVersionFile)" />
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
107
launcher/Logic/TriforceContext.cs
Normal file
107
launcher/Logic/TriforceContext.cs
Normal file
@@ -0,0 +1,107 @@
|
||||
// One launcher run's view of the PC: the platform, the settings, the log and where Triforce is installed. Every service in
|
||||
// Triforce.Logic takes one; nothing keeps state in statics (a test makes as many contexts, with as many test folders, as it
|
||||
// likes, side by side).
|
||||
namespace Triforce.Logic;
|
||||
|
||||
public sealed class TriforceContext
|
||||
{
|
||||
public IPlatform Platform { get; }
|
||||
public Settings Settings { get; }
|
||||
public Log Log { get; }
|
||||
/// <summary>(old --snapshot) nothing is written to the settings or the log.</summary>
|
||||
public bool NoWrites { get; set; }
|
||||
/// <summary>The running launcher's executable (Environment.ProcessPath); a test may name another.</summary>
|
||||
public string SelfPath { get; }
|
||||
public string SelfDir => Path.GetDirectoryName(SelfPath)!;
|
||||
/// <summary>Free bytes of the disk a folder is on (the platform's answer; a test puts its own here).</summary>
|
||||
public Func<string, long?> FreeBytes { get; set; }
|
||||
|
||||
public TriforceContext(IPlatform platform, string? selfPath = null)
|
||||
{
|
||||
Platform = platform;
|
||||
SelfPath = Path.GetFullPath(selfPath ?? Environment.ProcessPath ?? Path.Combine(AppContext.BaseDirectory, BuildInfo.SetupAsset));
|
||||
Settings = new Settings(platform.Settings, () => NoWrites);
|
||||
FreeBytes = platform.FreeBytes;
|
||||
Log = new Log(this);
|
||||
}
|
||||
|
||||
/// <summary>The context of this process: its platform, with the environment (or a test's own values over it).</summary>
|
||||
public static TriforceContext Create(IReadOnlyDictionary<string, string?>? env = null, string? selfPath = null) =>
|
||||
new(PlatformBase.Create(env), selfPath);
|
||||
|
||||
public string? TestRoot => Platform.TestRoot;
|
||||
public string? Env(string name) => Platform.Env(name);
|
||||
public bool IsWindows => Platform.IsWindows;
|
||||
|
||||
static StringComparison PathCase => OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
|
||||
/// <summary>The install folder from the Apps-list entry, when Triforce is installed (only when its TriforceSetup.exe is there:
|
||||
/// old Setup.cs InstalledDir). Linux: none (the AppImage is wherever the player keeps it).</summary>
|
||||
public string? InstalledDir
|
||||
{
|
||||
get
|
||||
{
|
||||
var d = Platform.Settings.GetUninstall("InstallLocation");
|
||||
return d != null && File.Exists(Path.Combine(d, BuildInfo.SetupAsset)) ? d : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The folder this launcher works in: tools\, downloads\, save-backups\, setup.log, TriforceSetup.old.exe. The install
|
||||
/// folder, else the folder it runs from (Windows); the self-update root ~/.local/share/triforce/builder (Linux).</summary>
|
||||
public string Home => InstalledDir ?? (Platform.IsWindows ? SelfDir : Platform.DefaultInstallDir);
|
||||
|
||||
/// <summary>Is this run the installed launcher (its folder is the install folder)?</summary>
|
||||
public bool RunningInstalled => InstalledDir is { } d && SamePath(d, SelfDir);
|
||||
|
||||
public static bool SamePath(string a, string b)
|
||||
{
|
||||
try { return string.Equals(Path.GetFullPath(a).TrimEnd('\\', '/'), Path.GetFullPath(b).TrimEnd('\\', '/'), PathCase); }
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
/// <summary>Is path the folder or inside it?</summary>
|
||||
public static bool Inside(string folder, string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
string root = Path.GetFullPath(folder).TrimEnd('\\', '/'), full = Path.GetFullPath(path).TrimEnd('\\', '/');
|
||||
return string.Equals(full, root, PathCase) || full.StartsWith(root + Path.DirectorySeparatorChar, PathCase) ||
|
||||
OperatingSystem.IsWindows() && full.StartsWith(root + "/", PathCase);
|
||||
}
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
/// <summary>May this run write there? Always, except in a test run (TRIFORCE_TEST_ROOT), which installs, builds, copies saves
|
||||
/// and starts games only inside its own folder, whatever folder is typed or picked: so a look at the launcher cannot change
|
||||
/// the PC's real install, real game or real saves (old Setup.cs Install.Allowed).</summary>
|
||||
public bool Allowed(string path) => TestRoot == null || Inside(TestRoot, path);
|
||||
|
||||
/// <summary>Playing and the game's own settings file: as Allowed, and in a test run also inside the one game folder
|
||||
/// TRIFORCE_TEST_GAME names (the owner's try-it run: Play, the benchmark and the game's options file on his real game,
|
||||
/// while saves, mods, the install and everything else stay inside the test folder).</summary>
|
||||
public bool AllowedForGame(string path) => Allowed(path) || Env("TRIFORCE_TEST_GAME") is { Length: > 0 } g && Inside(Path.GetFullPath(g), path);
|
||||
|
||||
public string TestOnly => "This is a test run of Triforce: it only writes inside its own folder, " + TestRoot + ".";
|
||||
|
||||
/// <summary>Throws the TestOnly sentence when a path is not allowed.</summary>
|
||||
public void Require(string path)
|
||||
{
|
||||
if (!Allowed(path)) throw new InvalidOperationException(TestOnly);
|
||||
}
|
||||
|
||||
// ---- folders the launcher keeps (old research/02 1.1) ----
|
||||
public string ToolsFolder => Path.Combine(Home, "tools");
|
||||
public string DownloadsFolder => Path.Combine(Home, "downloads");
|
||||
public string SaveBackupsFolder => Path.Combine(Home, "save-backups");
|
||||
public string NgxSdkFolder => Platform.NgxSdkFolder(Home);
|
||||
public string WorkFolder => Platform.WorkFolder;
|
||||
public string DefaultGameFolder => Platform.DefaultGameFolder;
|
||||
/// <summary>The launcher's exe in the install folder: what HOOKSHOT_BUILDER_EXE names, so every game folder's builder= line
|
||||
/// points back here (old Setup.cs Runner.Info). Linux: AppRun sets HOOKSHOT_BUILDER_EXE itself ($APPIMAGE or AppRun).</summary>
|
||||
public string BuilderExe => Platform.IsWindows
|
||||
? (InstalledDir is { } d ? Path.Combine(d, BuildInfo.SetupAsset) : SelfPath)
|
||||
: Env("HOOKSHOT_BUILDER_EXE") ?? Env("APPIMAGE") ?? SelfPath;
|
||||
|
||||
/// <summary>The space a disk lacks for something, in the old words; null when there is room (or it is not known).</summary>
|
||||
public string? SpaceProblem(string what, long need, string folder) => Space.Problem(what, need, FreeBytes(folder), Platform.Disk(folder));
|
||||
}
|
||||
197
launcher/Logic/Updater.cs
Normal file
197
launcher/Logic/Updater.cs
Normal file
@@ -0,0 +1,197 @@
|
||||
// Every start: ask what is newest, then decide (old Shell.cs Gather, Merge, StartNewSetup; research/02 2.3-2.4a).
|
||||
// Merge = 1. the launcher itself (it restarts and carries on), 2. the tools, 3. the game folder built again.
|
||||
using System.Diagnostics;
|
||||
using System.Net.Http;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>What the start page does once the check has answered.</summary>
|
||||
public enum CheckOutcome
|
||||
{
|
||||
/// <summary>Update & merge now (a first start with no tools and no game, or --merge / --update).</summary>
|
||||
Merge,
|
||||
/// <summary>Home: an update may be offered there (Updater.State).</summary>
|
||||
Home,
|
||||
/// <summary>The check failed but there is something to play or build with: Home, offline.</summary>
|
||||
HomeOffline,
|
||||
/// <summary>The check failed and there is nothing: the failure screen (Try again).</summary>
|
||||
Failed,
|
||||
}
|
||||
|
||||
public enum FailureKind { Cancelled, Offline, NoRoom, CutOff, NotStarted, NoRelease, Other }
|
||||
|
||||
/// <summary>A failure in the old words: a title and one plain sentence (old Shell.cs Failed).</summary>
|
||||
public sealed record Failure(FailureKind Kind, string Title, string Note)
|
||||
{
|
||||
public static Failure Of(Exception e, bool cancelled)
|
||||
{
|
||||
var offline = e is HttpRequestException || e is TaskCanceledException && !cancelled;
|
||||
if (cancelled) return new(FailureKind.Cancelled, "Stopped", "Nothing was changed.");
|
||||
if (offline) return new(FailureKind.Offline, "The Triforce site could not be reached", "Check your internet connection, then try again.");
|
||||
return e switch
|
||||
{
|
||||
NoRoomException => new(FailureKind.NoRoom, "Not enough room on the disk", e.Message),
|
||||
CutOffException => new(FailureKind.CutOff, "The download stopped", e.Message),
|
||||
NotStartedException => new(FailureKind.NotStarted, "The new launcher could not start", e.Message),
|
||||
NoReleaseException => new(FailureKind.NoRelease, "There is no Triforce release yet", e.Message),
|
||||
_ => new(FailureKind.Other, "Something went wrong", e.Message),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record CheckDecision(CheckOutcome Outcome, Release? Release, Failure? Failure);
|
||||
|
||||
/// <summary>What Home shows about updates (old Shell.Home.cs: setupNewer || toolsNewer || gameBehind).</summary>
|
||||
public sealed record UpdateState(bool LauncherNewer, bool ToolsNewer, bool GameBehind, string? GameFolder, string? GameVersion, string? ToolsVersion, Release? Release)
|
||||
{
|
||||
public bool Any => LauncherNewer || ToolsNewer || GameBehind;
|
||||
}
|
||||
|
||||
/// <summary>The steps a Merge will take, in order.</summary>
|
||||
public sealed record MergePlan(bool SelfUpdate, bool Tools, string? RebuildFolder, bool BuildForm);
|
||||
|
||||
/// <summary>After the launcher replaced itself: close (the new one is up, or left to itself).</summary>
|
||||
public enum SelfUpdateResult { CloseNow }
|
||||
|
||||
public sealed class Updater
|
||||
{
|
||||
readonly TriforceContext ctx;
|
||||
readonly Tools tools;
|
||||
readonly Game game;
|
||||
public Updater(TriforceContext ctx)
|
||||
{
|
||||
this.ctx = ctx;
|
||||
tools = new Tools(ctx);
|
||||
game = new Game(ctx);
|
||||
}
|
||||
|
||||
/// <summary>How long a new launcher has to give its sign (old: 30 s).</summary>
|
||||
public TimeSpan HandoverLimit { get; set; } = TimeSpan.FromSeconds(30);
|
||||
/// <summary>Set by the App when the OS is ending the session (a new launcher ended then says nothing about it).</summary>
|
||||
public bool SessionEnding { get; set; }
|
||||
|
||||
/// <summary>Ask the release server what is newest (nothing downloaded yet), and log what it said.</summary>
|
||||
public async Task<Release> CheckAsync(HttpClient http, CancellationToken token)
|
||||
{
|
||||
var r = await Release.LatestAsync(ctx, http, token).ConfigureAwait(false);
|
||||
ctx.Log.Write("latest release " + r.Tag + " (setup " + (r.SetupUrl != null) + ", tools " + (r.ToolsUrl != null) + "); this launcher " + BuildInfo.Version +
|
||||
", tools " + (tools.InstalledVersion ?? "none"));
|
||||
if (ctx.Settings.SetupSkip == r.Tag) ctx.Log.Write("launcher " + r.Tag + " is not fetched: it could not start on this PC (SetupSkip)");
|
||||
return r;
|
||||
}
|
||||
|
||||
bool HasGame => game.Current != null;
|
||||
|
||||
/// <summary>What the start does with the check's answer (old Shell.cs Gather): with nothing to play yet the tools come
|
||||
/// straight away; --merge carries on; else Home. A failure shows Home all the same when there is something to play or tools
|
||||
/// to build with.</summary>
|
||||
public CheckDecision Decide(StartArgs args, Release? release, Exception? error, bool cancelled = false)
|
||||
{
|
||||
if (release != null && error == null)
|
||||
{
|
||||
var toolsHere = tools.InstalledVersion != null || !ctx.IsWindows;
|
||||
return new CheckDecision(!toolsHere && !HasGame || args.Merge ? CheckOutcome.Merge : CheckOutcome.Home, release, null);
|
||||
}
|
||||
var e = error ?? new InvalidOperationException("no answer");
|
||||
ctx.Log.Write("update check failed: " + e.GetType().Name + ": " + e.Message);
|
||||
if (!cancelled && (tools.InstalledVersion != null || HasGame)) return new CheckDecision(CheckOutcome.HomeOffline, null, Failure.Of(e, false));
|
||||
return new CheckDecision(CheckOutcome.Failed, null, Failure.Of(e, cancelled));
|
||||
}
|
||||
|
||||
/// <summary>Is the release's launcher one to replace this one with? Not a dev build, not the same tag (plain string inequality:
|
||||
/// any other tag counts, even an older one), not one that could not start here (SetupSkip). Windows only: on Linux the
|
||||
/// launcher comes with the AppImage (LinuxUpdate).</summary>
|
||||
public bool LauncherNewer(Release r) =>
|
||||
ctx.IsWindows && !BuildInfo.IsDev && r.Tag != BuildInfo.Version && r.SetupUrl != null && ctx.Settings.SetupSkip != r.Tag;
|
||||
|
||||
public bool ToolsNewer(Release r) => ctx.IsWindows ? tools.InstalledVersion != r.Tag : LinuxUpdate.BuilderNewer(r.Tag, tools.InstalledVersion);
|
||||
|
||||
/// <summary>The game is behind the tools: built with other tools than the ones here.</summary>
|
||||
public bool GameBehind(string folder) => game.FindExe(folder) != null && Game.BuiltVersion(folder) is var built && built != tools.InstalledVersion && tools.InstalledVersion != null;
|
||||
|
||||
public UpdateState State(Release? r)
|
||||
{
|
||||
var folder = game.Current;
|
||||
return new UpdateState(r != null && LauncherNewer(r), r != null && ToolsNewer(r), folder != null && GameBehind(folder), folder,
|
||||
folder != null ? Game.BuiltVersion(folder) : null, tools.InstalledVersion, r);
|
||||
}
|
||||
|
||||
/// <summary>The steps of Update & merge for these arguments (old Shell.cs Merge): the launcher when not just relaunched and a
|
||||
/// newer one is out; the tools when theirs is another tag; then the folder the game's offer named (else the one built last)
|
||||
/// built again when its version is not the tools' (re-asked after the tools step: RebuildFolderNow).</summary>
|
||||
public MergePlan Plan(StartArgs args, Release r)
|
||||
{
|
||||
var self = !args.Relaunched && LauncherNewer(r);
|
||||
var t = ctx.IsWindows && tools.InstalledVersion != r.Tag;
|
||||
var folder = RebuildFolderNow(args);
|
||||
return new MergePlan(self, t, folder, folder == null && game.FindExe(args.UpdateFolder ?? ctx.Settings.GameFolder) == null);
|
||||
}
|
||||
|
||||
/// <summary>Merge step 3: the folder to build again now (it has a game, its version is not the tools', and there are tools), or null.</summary>
|
||||
public string? RebuildFolderNow(StartArgs args)
|
||||
{
|
||||
var folder = args.UpdateFolder ?? ctx.Settings.GameFolder;
|
||||
return folder != null && game.FindExe(folder) != null && Game.BuiltVersion(folder) != tools.InstalledVersion && tools.Find() != null ? folder : null;
|
||||
}
|
||||
|
||||
/// <summary>Merge step 1, the launcher itself (research/02 2.4a): the release's TriforceSetup.exe downloaded to
|
||||
/// <install>\TriforceSetup.new.exe (checked against the listed size only), swapped in under the running one's name (this one
|
||||
/// runs on as TriforceSetup.old.exe), started with the same arguments plus --relaunched (and --merge), and watched for 30 s:
|
||||
/// Up or Unclear: CloseNow (the App closes; the new one carries on with the merge).
|
||||
/// Failed (it ended with an error before its sign): the lock taken again, the old exe put back under the name, SetupSkip=tag,
|
||||
/// and NotStartedException: the App shows its window again with that sentence.
|
||||
/// hide: called when the new one has been started (the App hides its window while it waits).</summary>
|
||||
public async Task<SelfUpdateResult> SelfUpdateAsync(HttpClient http, Release r, StartArgs args, InstanceLock? held, Action<DownloadProgress>? progress, Action? hide, CancellationToken token)
|
||||
{
|
||||
if (r.SetupUrl == null) throw new InvalidOperationException("The release " + r.Tag + " has no " + BuildInfo.SetupAsset + ".");
|
||||
var dir = ctx.InstalledDir ?? ctx.SelfDir;
|
||||
var fresh = Path.Combine(dir, "TriforceSetup.new.exe");
|
||||
var self = Path.Combine(dir, BuildInfo.SetupAsset);
|
||||
var old = Path.Combine(dir, "TriforceSetup.old.exe");
|
||||
ctx.Require(fresh);
|
||||
await new Downloader(ctx).ToFileAsync(http, r.SetupUrl, fresh, r.SetupSize, progress, token).ConfigureAwait(false);
|
||||
Handover.Swap(fresh, self, old);
|
||||
ctx.Log.Write("launcher updated to " + r.Tag + ", restarting");
|
||||
var next = args with { Merge = true };
|
||||
var startArgs = next.PassOn(afterSelfUpdate: true);
|
||||
|
||||
EventWaitHandle? up = null;
|
||||
try { up = Handover.Expect(dir, ctx.TestRoot); } catch (Exception) { }
|
||||
var outcome = Handover.Outcome.Unclear;
|
||||
var why = "";
|
||||
using (up)
|
||||
{
|
||||
Process? started = null;
|
||||
held?.Release(); // (the launcher started here takes this install over: it must find the folder free)
|
||||
try
|
||||
{
|
||||
started = Installer.Start(self, startArgs);
|
||||
if (started == null) throw new InvalidOperationException("it did not start");
|
||||
}
|
||||
catch (Exception e) { outcome = Handover.Outcome.Failed; why = e.Message; }
|
||||
if (started != null)
|
||||
{
|
||||
using (started)
|
||||
{
|
||||
if (up == null) return SelfUpdateResult.CloseNow; // (no sign can be waited for here: started and left to itself)
|
||||
hide?.Invoke();
|
||||
try { outcome = await Task.Run(() => Handover.Watch(started, up, HandoverLimit), CancellationToken.None).ConfigureAwait(false); }
|
||||
catch (Exception) { }
|
||||
try { if (outcome == Handover.Outcome.Failed) why = "it ended at once, with exit code 0x" + started.ExitCode.ToString("X8"); } catch (Exception) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.Log.Write("launcher " + r.Tag + " after the restart: " + (outcome == Handover.Outcome.Up ? "its window is up"
|
||||
: outcome == Handover.Outcome.Failed ? "it did not start (" + why + ")" : "no sign of its window, left to itself"));
|
||||
// (when the OS ends the session the new launcher is ended like everything else, which says nothing about it. And when another
|
||||
// launcher has the folder by now, the new one started after all: the player started it again)
|
||||
if (outcome != Handover.Outcome.Failed || SessionEnding || held != null && !held.TakeAgain()) return SelfUpdateResult.CloseNow;
|
||||
var back = await Task.Run(() => Handover.Restore(ctx.Platform, old, self), CancellationToken.None).ConfigureAwait(false);
|
||||
ctx.Log.Write(back ? "launcher " + BuildInfo.Version + " is back under its name, and " + r.Tag + " will not be fetched again"
|
||||
: "launcher " + BuildInfo.Version + " could not be put back under its name");
|
||||
if (back) ctx.Settings.SetupSkip = r.Tag;
|
||||
throw new NotStartedException(back
|
||||
? "Triforce " + r.Tag + " could not start on this PC (" + why + "), so " + BuildInfo.Version + " is back in its place. Try again goes on with this one."
|
||||
: "Triforce " + r.Tag + " could not start on this PC (" + why + "), and " + BuildInfo.Version + " could not be put back in its place. Keep this window open and download Triforce again from " + BuildInfo.Home + ".");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user